private void DrawSockets() { var originalColor = GUI.color; for (int i = 0; i < targetGraph.AllNodes.Count; i++) { var node = targetGraph.AllNodes[i]; if (node == null) { continue; } foreach (var thisInput in node.InputSockets) { if (thisInput == null) { continue; } var socketRect = thisInput.SocketRect; socketRect = new Rect(socketRect.x + node.Position.x + dragging_Position.x, socketRect.y + node.Position.y + dragging_Position.y, socketRect.width, socketRect.height); thisInput.DrawSocket(socketRect); #if HOVER_EFFECTS if (connection_CanEdit) { var linkedSocket = thisInput.SourceSocket; if (connection_Start != null) { if (IsValidAttach(connection_Start, thisInput)) { if (linkedSocket == null) { EditorGUIUtility.AddCursorRect(socketRect, MouseCursor.ArrowPlus); } else { EditorGUIUtility.AddCursorRect(socketRect, MouseCursor.ArrowMinus); } } } else { if (linkedSocket == null) { EditorGUIUtility.AddCursorRect(socketRect, MouseCursor.ArrowPlus); } else { EditorGUIUtility.AddCursorRect(socketRect, MouseCursor.ArrowMinus); } } } #endif if (connection_CanEdit && (currentEvent.type == EventType.MouseDown || currentEvent.type == EventType.MouseUp) && socketRect.Contains(currentEvent.mousePosition)) { if (currentEvent.button == 0) { if (connection_Start != null || currentEvent.type != EventType.MouseUp) { connection_End = thisInput; } if (connection_Start != null) { Attach(connection_Start, connection_End); connection_End = null; connection_Start = null; currentEvent.Use(); } } else if (currentEvent.button == 1) { Detatch(thisInput); } currentEvent.Use(); } } foreach (var thisOutput in node.OutputSockets) { if (thisOutput == null) { continue; } var socketRect = thisOutput.socketRect; socketRect = new Rect(socketRect.x + node.Position.x + dragging_Position.x, socketRect.y + node.Position.y + dragging_Position.y, socketRect.width, socketRect.height); thisOutput.DrawSocket(socketRect); if (connection_CanEdit) { #if HOVER_EFFECTS if (connection_End != null) { if (IsValidAttach(thisOutput, connection_End)) { EditorGUIUtility.AddCursorRect(socketRect, MouseCursor.ArrowPlus); } } else { EditorGUIUtility.AddCursorRect(socketRect, MouseCursor.ArrowPlus); } #endif if ((currentEvent.type == EventType.MouseDown || currentEvent.type == EventType.MouseUp) && socketRect.Contains(currentEvent.mousePosition)) { if (currentEvent.button == 0) { if (connection_End != null || currentEvent.type != EventType.MouseUp) { connection_Start = thisOutput; } if (connection_End != null) { Attach(connection_Start, connection_End); connection_End = null; connection_Start = null; } currentEvent.Use(); } else if (currentEvent.button == 1) { Detatch(thisOutput); Repaint(); currentEvent.Use(); } } } } } GUI.color = originalColor; }
//... void OnGUI() { EditorGUILayout.HelpBox("In PlayMode only, you can use this Utility, to search and find GraphOwners in the scene which are actively running.", MessageType.Info); search = EditorUtils.SearchField(search); EditorUtils.BoldSeparator(); scrollPos = EditorGUILayout.BeginScrollView(scrollPos, false, false); var hasResult = false; foreach (var owner in activeOwners) { if (owner == null) { continue; } hasResult = true; var displayName = string.Format("<size=9><b>{0}</b> ({1})</size>", owner.name, owner.graphType.FriendlyName()); if (!string.IsNullOrEmpty(search)) { if (!StringUtils.SearchMatch(search, displayName)) { continue; } } GUILayout.BeginHorizontal(GUI.skin.box); GUILayout.Label(displayName); GUILayout.EndHorizontal(); var elementRect = GUILayoutUtility.GetLastRect(); EditorGUIUtility.AddCursorRect(elementRect, MouseCursor.Link); if (elementRect.Contains(Event.current.mousePosition)) { if (Event.current.type == EventType.MouseMove) { willRepaint = true; } GUI.color = new Color(0.5f, 0.5f, 1, 0.3f); GUI.DrawTexture(elementRect, EditorGUIUtility.whiteTexture); GUI.color = Color.white; if (Event.current.type == EventType.MouseDown) { Selection.activeObject = owner; EditorGUIUtility.PingObject(owner); if (Event.current.clickCount >= 2) { GraphEditor.OpenWindow(owner); } Event.current.Use(); } } } EditorGUILayout.EndScrollView(); if (!hasResult) { ShowNotification(new GUIContent(Application.isPlaying ? "No GraphOwner is actively running." : "Application is not playing.")); } if (Event.current.type == EventType.MouseLeaveWindow) { willRepaint = true; } }
Vector2 PivotSlider(Rect sprite, Vector2 pos, GUIStyle pivotDot, GUIStyle pivotDotActive) { int controlID = GUIUtility.GetControlID("Slider1D".GetHashCode(), FocusType.Keyboard); pos = new Vector2(sprite.xMin + sprite.width * pos.x, sprite.yMin + sprite.height * pos.y); Vector2 vector = Handles.matrix.MultiplyPoint(pos); Rect position = new Rect(vector.x - pivotDot.fixedWidth * 0.5f, vector.y - pivotDot.fixedHeight * 0.5f, pivotDotActive.fixedWidth, pivotDotActive.fixedHeight); Event current = Event.current; switch (current.GetTypeForControl(controlID)) { case EventType.MouseDown: if (current.button == 0 && position.Contains(Event.current.mousePosition) && !current.alt) { int num = controlID; GUIUtility.keyboardControl = num; GUIUtility.hotControl = num; currentMousePosition = current.mousePosition; dragStartScreenPosition = current.mousePosition; Vector2 b = Handles.matrix.MultiplyPoint(pos); dragScreenOffset = currentMousePosition - b; current.Use(); EditorGUIUtility.SetWantsMouseJumping(1); } break; case EventType.MouseUp: if (GUIUtility.hotControl == controlID && (current.button == 0 || current.button == 2)) { GUIUtility.hotControl = 0; current.Use(); EditorGUIUtility.SetWantsMouseJumping(0); } break; case EventType.MouseDrag: if (GUIUtility.hotControl == controlID) { currentMousePosition += current.delta; Vector2 a = pos; Vector3 vector2 = Handles.inverseMatrix.MultiplyPoint(currentMousePosition - dragScreenOffset); pos = new Vector2(vector2.x, vector2.y); if (!Mathf.Approximately((a - pos).magnitude, 0f)) { GUI.changed = true; } current.Use(); } break; case EventType.KeyDown: if (GUIUtility.hotControl == controlID && current.keyCode == KeyCode.Escape) { pos = Handles.inverseMatrix.MultiplyPoint(dragStartScreenPosition - dragScreenOffset); GUIUtility.hotControl = 0; GUI.changed = true; current.Use(); } break; case EventType.Repaint: EditorGUIUtility.AddCursorRect(position, MouseCursor.Arrow, controlID); if (GUIUtility.hotControl == controlID) { pivotDotActive.Draw(position, GUIContent.none, controlID); } else { pivotDot.Draw(position, GUIContent.none, controlID); } break; } pos = new Vector2((pos.x - sprite.xMin) / sprite.width, (pos.y - sprite.yMin) / sprite.height); return(pos); }
public override void OnUI(bool selected) { List <MeasureBase> measures = CourseBase.Measures; List <PinBase> pins = CourseBase.Pins; List <ShotBase> shots = CourseBase.Shots; List <TeeBase> tees = CourseBase.Tees; List <FlyByBase> flyBys = CourseBase.FlyBys; if (selected) { #region Delete if (CourseBase.ActivePlant != null && Event.current.keyCode == KeyCode.Delete && Event.current.type == EventType.KeyDown) { Event.current.Use(); MonoBehaviour.DestroyImmediate(CourseBase.ActivePlant.Transform.gameObject); return; } #endregion if (CourseBase.ActivePlant != null) { BeginUI(); Move(3, 0); SetColor(Green); if (!(CourseBase.ActivePlant is MeasureBase)) { SetColor(Red); Popup("Hole", CourseBase.ActivePlant.HoleIndex, CourseBase.HoleNames, 1); SetColor(); Move(1, 0); } if (CourseBase.ActivePlant is TeeBase) { TeeBase tee = (CourseBase.ActivePlant as TeeBase); tee.Type = TeeTypeField(tee.Type, tee.HoleIndex, true, 2); Move(2, 0); tee.Par = ParField(tee.Par, 2); Move(2, 0); tee.StrokeIndex = StrokeIndexField(tee.HoleIndex, tee.Type, tee.StrokeIndex, true, 2); Move(2, 0); tee.TeeInfo.width = LengthSlider(tee.TeeInfo.width, "Width", 0.0f, 10, 0, 4); Move(4, 0); tee.TeeInfo.height = LengthSlider(tee.TeeInfo.height, "Height", 0.0f, 10, 0, 4); Move(4, 0); if (tee.TestLeft && tee.TestRight) { if (Button("Remove Marker", 4)) { if (tee.TestLeft != null) { MonoBehaviour.DestroyImmediate(tee.TestLeft); } if (tee.TestRight != null) { MonoBehaviour.DestroyImmediate(tee.TestRight); } } } else { if (Button("Test Tee Marker", 4)) { Vector3 forward = Vector3.right; if (CourseBase.Holes[tee.HoleIndex].pins.Count != 0) { forward = (CourseBase.AimPoint(tee.Position, tee, CourseBase.Holes[tee.HoleIndex].shots, CourseBase.Holes[tee.HoleIndex].pins[0]) - tee.Position).normalized; } forward.y = 0; Vector3 right = Vector3.Cross(forward, Vector3.up); Vector3 teePosition = tee.Position + forward * tee.Height / 2 * Random.insideUnitCircle.x + right * tee.Width / 2 * Random.insideUnitCircle.x; teePosition.y = CourseBase.MeshHeight(teePosition.x, teePosition.z); GameObject courseTeeMarker = CourseBase.GetTeeMarker(tee.Type); if (courseTeeMarker) { tee.TestLeft = (GameObject)GameObject.Instantiate(courseTeeMarker, teePosition - right * Utility.markerOffset, Quaternion.identity); tee.TestRight = (GameObject)GameObject.Instantiate(courseTeeMarker, teePosition + right * Utility.markerOffset, Quaternion.identity); tee.TestLeft.transform.forward = forward; tee.TestRight.transform.forward = forward; } } } Move(4, 0); } else if (CourseBase.ActivePlant is ShotBase) { } else if (CourseBase.ActivePlant is PinBase) { (CourseBase.ActivePlant as PinBase).Difficulty = DifficultyField((CourseBase.ActivePlant as PinBase).Difficulty, 2); Move(2, 0); } else if (CourseBase.ActivePlant is MeasureBase) { } else if (CourseBase.ActivePlant is FlyByBase) { FlyByBase flyby = (CourseBase.ActivePlant as FlyByBase); FlyByBase.Info.Node node = (activeInfo as FlyByBase.Info.Node); flyby.Type = FlyByTypeField(flyby.Type, flyby.HoleIndex, true, 1); Move(1, 0); if (node != null) { node.target = TargetField(node.target, node, 2); } Move(2, 0); node.velocity = VelocityField("Velocity", node.velocity, 15.0f, 3); Move(3, 0); node.RotationCurve = CurveField("Rotation Step", node.RotationCurve, AnimationCurve.Linear(0, 0, 1, 1), 3); Move(3, 0); FlyByBase flyBy = CourseBase.ActivePlant as FlyByBase; float originalTime = timer.Elapsed; float time = originalTime; VideoSlider(ref time, 3); Move(3, 0); if (node == (CourseBase.ActivePlant as FlyByBase).Nodes[0] || node == (CourseBase.ActivePlant as FlyByBase).Nodes[1] || node == (CourseBase.ActivePlant as FlyByBase).Nodes[2]) { SetColor(Green); node.position.Set(VectorField("Position", node.position.ToVector3(), 5)); Move(5, 0); SetColor(); } if (play) { if (time == timer.MaxTime) { time = 0; timer.Stop(); pause = false; play = false; } else if (time != originalTime) { timer.MoveToTime(time / timer.MaxTime); if (!pause) { timer.Resume(); } } HandleUtility.Repaint(); Camera.main.transform.position = (CourseBase.ActivePlant as FlyByBase).GetPosition(timer.Elapsed); Camera.main.transform.LookAt((CourseBase.ActivePlant as FlyByBase).GetTargetPosition(timer.Elapsed, Vector3.zero, Vector3.zero, Vector3.zero)); } else { if (time != originalTime) { play = true; pause = true; timer.Start((CourseBase.ActivePlant as FlyByBase).Time); timer.MoveToTime(time / timer.MaxTime); HandleUtility.Repaint(); } Camera.main.transform.position = node.position; Camera.main.transform.LookAt(node.TargetPosition(flyBy.HoleIndex, flyBy.Nodes, Vector3.zero, Vector3.zero, Vector3.zero)); } if (Event.current.type == EventType.Repaint && Camera.main) { Selection.activeTransform = Camera.main.transform; } } SetColor(); EndUI(); } else { BeginUI(); Move(3, 0); holeIndex = Popup("Hole", holeIndex, CourseBase.HoleNames, 1); Move(1, 0); TeeField(); Move(1, 0); if (teePlanting && CourseBase.FreeTees(holeIndex).Length == 0) { teePlanting = false; } if (teePlanting) { teeType = TeeTypeField(teeType, holeIndex, false, 2); Move(2, 0); teePar = ParField(teePar, 2); Move(2, 0); teeStrokeIndex = StrokeIndexField(holeIndex, teeType, teeStrokeIndex, false, 2); Move(2, 0); teeWidth = LengthSlider(teeWidth, "Width", 0.0f, 10, 0, 4); Move(4, 0); teeHeight = LengthSlider(teeHeight, "Height", 0.0f, 10, 0, 4); Move(4, 0); } ShotField(); Move(1, 0); PinField(); Move(1, 0); if (pinPlanting) { pinDifficulty = DifficultyField(pinDifficulty, 2); Move(2, 0); } MeasureField(); Move(1, 0); FlyByField(); Move(1, 0); if (flyByPlanting) { flyByType = FlyByTypeField(flyByType, holeIndex, false, 2); Move(2, 0); } SetColor(); EndUI(); } } #region UnClick if (activeInfo != null && LeftMouseUp && !(activeInfo is FlyByBase.Info.Node)) { Event.current.Use(); activeInfo = null; return; } #endregion if (selected) { for (int i = 0; i < pins.Count; ++i) { OnPlantUI(pins[i], pins[i].PlantInfo); } for (int i = 0; i < shots.Count; ++i) { OnPlantUI(shots[i], shots[i].PlantInfo); } for (int i = 0; i < tees.Count; ++i) { OnPlantUI(tees[i], tees[i].PlantInfo); } for (int i = 0; i < flyBys.Count; ++i) { for (int n = 0; n < flyBys[i].Nodes.Count; ++n) { OnFlyByUI(flyBys[i], flyBys[i].Nodes[n]); } } } for (int i = 0; i < measures.Count; ++i) { OnPlantUI(measures[i], measures[i].StartInfo); OnPlantUI(measures[i], measures[i].EndInfo); } if (selected) { OnMouse(); if (Event.current.type == EventType.Repaint) { EditorGUIUtility.AddCursorRect(new Rect(0, 0, Screen.width, Screen.height), MouseCursor.Arrow); } } if (CourseBase.ActivePlant != null && LeftMouseDown) { Event.current.Use(); CourseBase.ActivePlant = null; activeInfo = null; } }
private void AboutGUI() { GUILayout.BeginVertical(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button(_githubGUIContent, EditorGlobalTools.Styles.Label)) { Application.OpenURL("https://github.com/SaiTingHu/HTFramework"); } EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link); if (GUILayout.Button(_csdnGUIContent, EditorGlobalTools.Styles.Label)) { Application.OpenURL("https://blog.csdn.net/qq992817263/category_9283445.html"); } EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link); GUILayout.EndHorizontal(); GUILayout.FlexibleSpace(); GUILayout.BeginHorizontal(); GUILayout.Label("Release Notes: [Date " + _versionInfo.CurrentVersion.ReleaseDate + "]"); GUILayout.EndHorizontal(); GUILayout.BeginVertical(GUILayout.Height(100)); _scroll = GUILayout.BeginScrollView(_scroll); GUILayout.Label(_versionInfo.CurrentVersion.ReleaseNotes); GUILayout.EndScrollView(); GUILayout.EndVertical(); GUILayout.BeginHorizontal(); GUILayout.Label("Supported Runtime Platforms: "); GUILayout.Label(_pcGUIContent, EditorGlobalTools.Styles.Wordwrapminibutton); GUILayout.Label(_androidGUIContent, EditorGlobalTools.Styles.Wordwrapminibutton); GUILayout.Label(_webglGUIContent, EditorGlobalTools.Styles.Wordwrapminibutton); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Supported Unity Versions: " + _versionInfo.CurrentVersion.UnityVersions); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Scripting Runtime Versions: " + _versionInfo.CurrentVersion.ScriptingVersions); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Api Compatibility Level: " + _versionInfo.CurrentVersion.APIVersions); GUILayout.FlexibleSpace(); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUI.color = Color.yellow; if (GUILayout.Button("Copyright (c) 2019 HuTao", EditorGlobalTools.Styles.Label)) { Application.OpenURL("https://github.com/SaiTingHu/HTFramework/blob/master/LICENSE"); } EditorGUIUtility.AddCursorRect(GUILayoutUtility.GetLastRect(), MouseCursor.Link); GUI.color = Color.white; GUILayout.FlexibleSpace(); bool isShowOnStart = GUILayout.Toggle(_isShowOnStart, "Show On Start"); if (isShowOnStart != _isShowOnStart) { _isShowOnStart = isShowOnStart; EditorPrefs.SetBool(EditorPrefsTable.AboutIsShowOnStart, _isShowOnStart); } GUILayout.EndHorizontal(); GUILayout.EndVertical(); }
public void OnGUI() { if (!m_infoDownloaded) { m_infoDownloaded = true; // get affiliate links StartBackgroundTask(StartRequest(PackageRefURL, (www) => { var pack = PackageRef.CreateFromJSON(www.downloadHandler.text); if (pack != null) { m_packageRef = pack; Repaint(); } })); // get banner information and texture StartBackgroundTask(StartRequest(BannerInfoURL, (www) => { Info info = Info.CreateFromJSON(www.downloadHandler.text); if (info != null && !string.IsNullOrEmpty(info.ImageUrl)) { StartBackgroundTask(StartTextureRequest(info.ImageUrl, (www2) => { Texture2D texture = DownloadHandlerTexture.GetContent(www2); if (texture != null) { m_newsImage = texture; } })); } if (info != null && info.Version >= m_bannerInfo.Version) { m_bannerInfo = info; } // improve this later int major = m_bannerInfo.Version / 100; int minor = (m_bannerInfo.Version / 10) - major * 10; int release = m_bannerInfo.Version - major * 100 - minor * 10; m_newVersion = major + "." + minor + "." + release; Repaint(); })); } if (m_buttonStyle == null) { m_buttonStyle = new GUIStyle(GUI.skin.button); m_buttonStyle.alignment = TextAnchor.MiddleLeft; } if (m_labelStyle == null) { m_labelStyle = new GUIStyle("BoldLabel"); m_labelStyle.margin = new RectOffset(4, 4, 4, 4); m_labelStyle.padding = new RectOffset(2, 2, 2, 2); m_labelStyle.fontSize = 13; } if (m_linkStyle == null) { var inv = AssetDatabase.LoadAssetAtPath <Texture2D>(AssetDatabase.GUIDToAssetPath("1004d06b4b28f5943abdf2313a22790a")); // find a better solution for transparent buttons m_linkStyle = new GUIStyle(); m_linkStyle.normal.textColor = new Color(0.2980392f, 0.4901961f, 1f); m_linkStyle.hover.textColor = Color.white; m_linkStyle.active.textColor = Color.grey; m_linkStyle.margin.top = 3; m_linkStyle.margin.bottom = 2; m_linkStyle.hover.background = inv; m_linkStyle.active.background = inv; } EditorGUILayout.BeginHorizontal(GUIStyle.none, GUILayout.ExpandWidth(true)); { // left column EditorGUILayout.BeginVertical(GUILayout.Width(175)); { GUILayout.Label(ResourcesTitle, m_labelStyle); if (GUILayout.Button(WikiButton, m_buttonStyle)) { Application.OpenURL(WikiURL); } GUILayout.Space(10); GUILayout.Label("Amplify Products", m_labelStyle); if (m_packageRef.Links != null) { var webIcon = EditorGUIUtility.IconContent("BuildSettings.Web.Small").image; for (int i = 0; i < m_packageRef.Links.Length; i++) { var gc = new GUIContent(" " + m_packageRef.Links[i].Title, webIcon); if (GUILayout.Button(gc, m_buttonStyle)) { Application.OpenURL(m_packageRef.Links[i].Url + RefID); } } } GUILayout.Label("* Affiliate Links", "minilabel"); } EditorGUILayout.EndVertical(); // right column EditorGUILayout.BeginVertical(GUILayout.Width(650 - 175 - 9), GUILayout.ExpandHeight(true)); { GUILayout.Label(CommunityTitle, m_labelStyle); EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); { if (GUILayout.Button(DiscordButton, GUILayout.ExpandWidth(true))) { Application.OpenURL(DiscordURL); } if (GUILayout.Button(ForumButton, GUILayout.ExpandWidth(true))) { Application.OpenURL(ForumURL); } } EditorGUILayout.EndHorizontal(); GUILayout.Label(UpdateTitle, m_labelStyle); if (m_newsImage != null) { var gc = new GUIContent(m_newsImage); int width = 650 - 175 - 9 - 8; width = Mathf.Min(m_newsImage.width, width); int height = m_newsImage.height; height = (int)((width + 8) * ((float)m_newsImage.height / (float)m_newsImage.width)); Rect buttonRect = EditorGUILayout.GetControlRect(false, height); EditorGUIUtility.AddCursorRect(buttonRect, MouseCursor.Link); if (GUI.Button(buttonRect, gc, m_linkStyle)) { Application.OpenURL(m_bannerInfo.LinkUrl); } } m_scrollPosition = GUILayout.BeginScrollView(m_scrollPosition, GUILayout.ExpandHeight(true), GUILayout.ExpandWidth(true)); GUILayout.Label(m_bannerInfo.NewsText, "WordWrappedMiniLabel", GUILayout.ExpandHeight(true)); GUILayout.EndScrollView(); EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); { EditorGUILayout.BeginVertical(); GUILayout.Label(TitleSTR, m_labelStyle); GUILayout.Label("Installed Version: " + Major + "." + Minor + "." + Release); if (m_bannerInfo.Version > FullNumber) { var cache = GUI.color; GUI.color = Color.red; GUILayout.Label("New version available: " + m_newVersion, "BoldLabel"); GUI.color = cache; } else { var cache = GUI.color; GUI.color = Color.green; GUILayout.Label("You are using the latest version", "BoldLabel"); GUI.color = cache; } EditorGUILayout.BeginHorizontal(); GUILayout.Label("Download links:"); if (GUILayout.Button("Amplify", m_linkStyle)) { Application.OpenURL(SiteURL); } GUILayout.Label("-"); if (GUILayout.Button("Asset Store", m_linkStyle)) { Application.OpenURL(StoreURL); } EditorGUILayout.EndHorizontal(); GUILayout.Space(7); EditorGUILayout.EndVertical(); GUILayout.FlexibleSpace(); EditorGUILayout.BeginVertical(); GUILayout.Space(7); GUILayout.Label(Icon); EditorGUILayout.EndVertical(); } EditorGUILayout.EndHorizontal(); } EditorGUILayout.EndVertical(); } EditorGUILayout.EndHorizontal(); EditorGUILayout.BeginHorizontal("ProjectBrowserBottomBarBg", GUILayout.ExpandWidth(true), GUILayout.Height(22)); { GUILayout.FlexibleSpace(); EditorGUI.BeginChangeCheck(); var cache = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = 100; m_startup = EditorGUILayout.ToggleLeft("Show At Startup", m_startup, GUILayout.Width(120)); EditorGUIUtility.labelWidth = cache; if (EditorGUI.EndChangeCheck()) { EditorPrefs.SetBool(Preferences.PrefStartUp, m_startup); } } EditorGUILayout.EndHorizontal(); // Find a better way to update link buttons without repainting the window Repaint(); }
void DrawFakeSlider(ref float value, DrawInfo drawInfo) { float rangeWidth = 30 * drawInfo.InvertedZoom; float rangeSpacing = 5 * drawInfo.InvertedZoom; //Min Rect minRect = m_propertyDrawPos; minRect.width = rangeWidth; EditorGUIUtility.AddCursorRect(minRect, MouseCursor.Text); if (m_previousValue[1] != m_min) { m_previousValue[1] = m_min; m_fieldText[1] = m_min.ToString(); } GUI.Label(minRect, m_fieldText[1], UIUtils.MainSkin.textField); //Value Area Rect valRect = m_propertyDrawPos; valRect.width = rangeWidth; valRect.x = m_propertyDrawPos.xMax - rangeWidth - rangeWidth - rangeSpacing; EditorGUIUtility.AddCursorRect(valRect, MouseCursor.Text); if (m_previousValue[0] != value) { m_previousValue[0] = value; m_fieldText[0] = value.ToString(); } GUI.Label(valRect, m_fieldText[0], UIUtils.MainSkin.textField); //Max Rect maxRect = m_propertyDrawPos; maxRect.width = rangeWidth; maxRect.x = m_propertyDrawPos.xMax - rangeWidth; EditorGUIUtility.AddCursorRect(maxRect, MouseCursor.Text); if (m_previousValue[2] != m_max) { m_previousValue[2] = m_max; m_fieldText[2] = m_max.ToString(); } GUI.Label(maxRect, m_fieldText[2], UIUtils.MainSkin.textField); Rect sliderValRect = m_propertyDrawPos; sliderValRect.x = minRect.xMax + rangeSpacing; sliderValRect.xMax = valRect.xMin - rangeSpacing; Rect sliderBackRect = sliderValRect; sliderBackRect.height = 5 * drawInfo.InvertedZoom; sliderBackRect.center = new Vector2(sliderValRect.center.x, Mathf.Round(sliderValRect.center.y)); GUI.Label(sliderBackRect, string.Empty, UIUtils.GetCustomStyle(CustomStyle.SliderStyle)); sliderValRect.width = 10; float percent = (value - m_min) / (m_max - m_min); sliderValRect.x += percent * (sliderBackRect.width - 10 * drawInfo.InvertedZoom); GUI.Label(sliderValRect, string.Empty, UIUtils.RangedFloatSliderThumbStyle); }
private void DoColorSceneGUI() { Event e = Event.current; int controlID = GUIUtility.GetControlID(FocusType.Passive); HandleUtility.AddDefaultControl(controlID); EventType currentEventType = Event.current.GetTypeForControl(controlID); bool skip = false; //int saveControl = GUIUtility.hotControl; //FIX: Should not grab hot control with an active capture //Shortcuts if (e.type == EventType.ScrollWheel && e.control) { s_colorSettings.radius += e.delta.y * 0.1f; e.Use(); } try { if (currentEventType == EventType.Layout) { skip = true; } else if (currentEventType == EventType.ScrollWheel) { skip = true; } if (m_tilemap.Tileset == null) { return; } if (!skip) { EditorGUIUtility.AddCursorRect(new Rect(0f, 0f, (float)Screen.width, (float)Screen.height), MouseCursor.Arrow); //GUIUtility.hotControl = controlID; //FIX: Should not grab hot control with an active capture { Plane chunkPlane = new Plane(m_tilemap.transform.forward, m_tilemap.transform.position); Vector2 mousePos = Event.current.mousePosition; mousePos.y = Screen.height - mousePos.y; Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); float dist; if (chunkPlane.Raycast(ray, out dist)) { Vector3 brushWorldPos = ray.GetPoint(dist); // Update brush transform m_localBrushPos = (Vector2)m_tilemap.transform.InverseTransformPoint(brushWorldPos); EditorCompatibilityUtils.CircleCap(0, brushWorldPos, m_tilemap.transform.rotation, s_colorSettings.radius); if ( (EditorWindow.focusedWindow == EditorWindow.mouseOverWindow) && // fix painting tiles when closing another window popup over the SceneView like GameObject Selection window (e.type == EventType.MouseDown || e.type == EventType.MouseDrag) ) { if (e.button == 0) { if (e.alt) { //Color Pickup Color pickedColor = m_tilemap.GetTileColor(m_localBrushPos).c0; pickedColor.a = s_colorSettings.color.a; s_colorSettings.color = pickedColor; } else if (s_colorSettings.paintTilemapGroup && m_tilemap.ParentTilemapGroup) { m_tilemap.ParentTilemapGroup.IterateTilemapWithAction((STETilemap tilemap) => { if (tilemap && tilemap.IsVisible) { if (s_enableUndoColorPainting) { RegisterTilemapUndo(tilemap); } TilemapVertexPaintUtils.VertexPaintCircle(tilemap, m_localBrushPos, s_colorSettings.radius, s_colorSettings.color, s_colorSettings.blendMode, s_colorSettings.tileColorPaintMode == eTileColorPaintMode.Vertex, s_colorSettings.brushIntensity); tilemap.UpdateMesh(); } }); } else { if (s_enableUndoColorPainting) { RegisterTilemapUndo(m_tilemap); } TilemapVertexPaintUtils.VertexPaintCircle(m_tilemap, m_localBrushPos, s_colorSettings.radius, s_colorSettings.color, s_colorSettings.blendMode, s_colorSettings.tileColorPaintMode == eTileColorPaintMode.Vertex, s_colorSettings.brushIntensity); m_tilemap.UpdateMesh(); } } } } } if (currentEventType == EventType.MouseDrag && Event.current.button < 2) // 2 is for central mouse button { // avoid dragging the map Event.current.Use(); } } } // Avoid loosing the hotControl because of a triggered exception catch (System.Exception ex) { Debug.LogException(ex); } SceneView.RepaintAll(); //GUIUtility.hotControl = saveControl; //FIX: Should not grab hot control with an active capture }
//Show the target blackboard window static Rect ShowBlackboardGUIPanel(Graph graph, Vector2 canvasMousePos) { //SL-- var inspectorPanel = default(Rect); if (!Prefs.showBlackboard) { return(inspectorPanel); } var blackboardPanel = default(Rect); if (graph.blackboard == null) { return(blackboardPanel); } blackboardPanel.xMin = screenWidth - Prefs.blackboardPanelWidth; blackboardPanel.yMin = 30; blackboardPanel.xMax = screenWidth - 20; blackboardPanel.height = blackboardPanelHeight; var resizeRect = Rect.MinMaxRect(blackboardPanel.xMin - 2, blackboardPanel.yMin, blackboardPanel.xMin + 2, blackboardPanel.yMax); EditorGUIUtility.AddCursorRect(resizeRect, MouseCursor.ResizeHorizontal); if (e.type == EventType.MouseDown && resizeRect.Contains(e.mousePosition)) { isResizingBlackboardPanel = true; e.Use(); } if (isResizingBlackboardPanel && e.type == EventType.Layout) { Prefs.blackboardPanelWidth -= e.delta.x; } if (e.rawType == EventType.MouseUp) { isResizingBlackboardPanel = false; } var headerRect = new Rect(blackboardPanel.x, blackboardPanel.y, blackboardPanel.width, 30); EditorGUIUtility.AddCursorRect(headerRect, MouseCursor.Link); if (GUI.Button(headerRect, string.Empty, StyleSheet.button)) { Prefs.showBlackboard = !Prefs.showBlackboard; } GUI.Box(blackboardPanel, string.Empty, StyleSheet.windowShadow); var title = graph.blackboard == graph.localBlackboard ? string.Format("Local {0} Variables", graph.GetType().Name) : "Variables"; if (Prefs.showBlackboard) { var viewRect = new Rect(blackboardPanel.x, blackboardPanel.y, blackboardPanel.width + 16, screenHeight - blackboardPanel.y - 30); var r = new Rect(blackboardPanel.x - 3, blackboardPanel.y, blackboardPanel.width, blackboardPanel.height); blackboardPanelScrollPos = GUI.BeginScrollView(viewRect, blackboardPanelScrollPos, r); GUILayout.BeginArea(blackboardPanel, title, StyleSheet.editorPanel); GUILayout.Space(5); BlackboardEditor.ShowVariables(graph.blackboard, graph.blackboard == graph.localBlackboard ? graph : graph.blackboard as Object); EditorUtils.EndOfInspector(); if (e.type == EventType.Repaint) { blackboardPanelHeight = GUILayoutUtility.GetLastRect().yMax + 5; } GUILayout.EndArea(); GUI.EndScrollView(); } else { blackboardPanelHeight = 55; GUILayout.BeginArea(blackboardPanel, title, StyleSheet.editorPanel); GUI.color = new Color(1, 1, 1, 0.2f); if (GUILayout.Button("...", StyleSheet.button)) { Prefs.showBlackboard = true; } GUILayout.EndArea(); GUI.color = Color.white; } if (graph.canAcceptVariableDrops && BlackboardEditor.pickedVariable != null && BlackboardEditor.pickedVariableBlackboard == graph.blackboard) { GUI.Label(new Rect(e.mousePosition.x + 15, e.mousePosition.y, 100, 18), "Drop Variable", StyleSheet.labelOnCanvas); if (e.type == EventType.MouseUp) { graph.CallbackOnVariableDropInGraph(BlackboardEditor.pickedVariable, canvasMousePos); BlackboardEditor.ResetPick(); } } return(blackboardPanel); }
/// <summary> /// Renders an interactive Noise Preview along with tooltip icons and an optional Export button that opens a new ExportNoiseWindow. /// A background image is also rendered behind the preview that takes up the entire width of the EditorWindow currently being drawn. /// </summary> /// <param name = "minSize"> Minimum size for the Preview </param> /// <param name = "showExportButton"> Whether or not to render the Export button </param> public void DrawPreviewTexture(float minSize, bool showExportButton = true) { // Draw label with tooltip GUILayout.Label(Styles.noisePreview); float padding = 4f; float iconWidth = 40f; int size = (int)Mathf.Min(minSize, EditorGUIUtility.currentViewWidth); Rect totalRect = GUILayoutUtility.GetRect(EditorGUIUtility.currentViewWidth, size + padding * 2); // extra pixels for highlight border Color prev = GUI.color; GUI.color = new Color(.15f, .15f, .15f, 1f); GUI.DrawTexture(totalRect, Texture2D.whiteTexture, ScaleMode.StretchToFill, false); GUI.color = Color.white; // draw info icon // if(totalRect.Contains(Event.current.mousePosition)) { Rect infoIconRect = new Rect(totalRect.x + padding, totalRect.y + padding, iconWidth, iconWidth); GUI.Label(infoIconRect, Styles.infoIcon); // GUI.Label( infoIconRect, Styles.noiseTooltip ); } // draw export button float buttonWidth = GUI.skin.button.CalcSize(Styles.export).x; float buttonHeight = EditorGUIUtility.singleLineHeight; Rect exportRect = new Rect(totalRect.xMax - buttonWidth - padding, totalRect.yMax - buttonHeight - padding, buttonWidth, buttonHeight); if (GUI.Button(exportRect, Styles.export)) { serializedNoise.ApplyModifiedProperties(); serializedNoise.Update(); ExportNoiseWindow.ShowWindow(serializedNoise.targetObject as NoiseSettings); } float safeSpace = Mathf.Max(iconWidth * 2, buttonWidth * 2) + padding * 4; float minWidth = Mathf.Min(size, totalRect.width - safeSpace); Rect previewRect = new Rect(totalRect.x + totalRect.width / 2 - minWidth / 2, totalRect.y + totalRect.height / 2 - minWidth / 2, minWidth, minWidth); EditorGUIUtility.AddCursorRect(previewRect, MouseCursor.Pan); if (previewRect.Contains(Event.current.mousePosition)) { serializedNoise.Update(); HandlePreviewTextureInput(previewRect); serializedNoise.ApplyModifiedProperties(); } if (Event.current.type == EventType.Repaint) { // create preview RT here and keep until the next Repaint if (m_previewRT != null) { RenderTexture.ReleaseTemporary(m_previewRT); } NoiseSettings noiseSettings = serializedNoise.targetObject as NoiseSettings; m_previewRT = RenderTexture.GetTemporary(512, 512, 0, RenderTextureFormat.ARGB32); RenderTexture tempRT = RenderTexture.GetTemporary(512, 512, 0, RenderTextureFormat.RFloat); RenderTexture prevActive = RenderTexture.active; NoiseUtils.Blit2D(noiseSettings, tempRT); NoiseUtils.BlitPreview2D(tempRT, m_previewRT); RenderTexture.active = prevActive; GUI.DrawTexture(previewRect, m_previewRT, ScaleMode.ScaleToFit, false); RenderTexture.ReleaseTemporary(tempRT); } GUI.color = prev; }
void HandleEvents(Event e) { //set repaint counter if need be if (mouseOverWindow == this && (e.isMouse || e.isKey)) { willRepaint = true; } //snap all nodes on assumption change if (e.type == EventType.MouseUp || e.type == EventType.KeyUp) { SnapNodes(); } if (e.type == EventType.KeyDown && e.keyCode == KeyCode.F && GUIUtility.keyboardControl == 0) { if (currentGraph.allNodes.Count > 0) { FocusPosition(GetNodeBounds(currentGraph, viewRect, false).center); } else { FocusPosition(virtualCenter); } } if (e.type == EventType.MouseDown && e.button == 2 && e.clickCount == 2) { FocusPosition(ViewToCanvas(e.mousePosition)); } if (e.type == EventType.ScrollWheel && Graph.allowClick) { if (canvasRect.Contains(e.mousePosition)) { var zoomDelta = e.shift? 0.1f : 0.25f; ZoomAt(e.mousePosition, -e.delta.y > 0? zoomDelta : -zoomDelta); } } if ((e.button == 2 && e.type == EventType.MouseDrag && canvasRect.Contains(e.mousePosition)) || ((e.type == EventType.MouseDown || e.type == EventType.MouseDrag) && e.alt && e.isMouse)) { pan += e.delta; smoothPan = null; smoothZoomFactor = null; e.Use(); } if (e.type == EventType.MouseDown && e.button == 2 && canvasRect.Contains(e.mousePosition)) { mouseButton2Down = true; } if (e.type == EventType.MouseUp && e.button == 2) { mouseButton2Down = false; } if (mouseButton2Down == true) { EditorGUIUtility.AddCursorRect(new Rect(0, 0, screenWidth, screenHeight), MouseCursor.Pan); } }
public override void OnInspectorGUI() { oldSkin = GUI.skin; serializedObject.Update(); if (skin) { GUI.skin = skin; } GUILayout.BeginVertical("Item Manager", "window"); GUILayout.Label(m_Logo, GUILayout.MaxHeight(25)); openCloseWindow = GUILayout.Toggle(openCloseWindow, openCloseWindow ? "Close" : "Open", EditorStyles.toolbarButton); if (openCloseWindow) { GUI.skin = oldSkin; DrawPropertiesExcluding(serializedObject, ignoreProperties.Append(ignore_vMono)); GUI.skin = skin; if (GUILayout.Button("Open Item List")) { vItemListWindow.CreateWindow(manager.itemListData); } if (manager.itemListData) { GUILayout.BeginVertical("box"); if (itemReferenceList.arraySize > manager.itemListData.items.Count) { manager.startItems.Resize(manager.itemListData.items.Count); } GUILayout.Box("Start Items " + manager.startItems.Count); filteredItems = manager.itemsFilter.Count > 0 ? GetItemByFilter(manager.itemListData.items, manager.itemsFilter) : manager.itemListData.items; if (!inAddItem && filteredItems.Count > 0 && GUILayout.Button("Add Item", EditorStyles.miniButton)) { inAddItem = true; } if (inAddItem && filteredItems.Count > 0) { GUILayout.BeginVertical("box"); selectedItem = EditorGUILayout.Popup(new GUIContent("SelectItem"), selectedItem, GetItemContents(filteredItems)); bool isValid = true; var indexSelected = manager.itemListData.items.IndexOf(filteredItems[selectedItem]); if (manager.startItems.Find(i => i.id == manager.itemListData.items[indexSelected].id) != null) { isValid = false; EditorGUILayout.HelpBox("This item already exist", MessageType.Error); } GUILayout.BeginHorizontal(); if (isValid && GUILayout.Button("Add", EditorStyles.miniButton)) { itemReferenceList.arraySize++; itemReferenceList.GetArrayElementAtIndex(itemReferenceList.arraySize - 1).FindPropertyRelative("id").intValue = manager.itemListData.items[indexSelected].id; itemReferenceList.GetArrayElementAtIndex(itemReferenceList.arraySize - 1).FindPropertyRelative("amount").intValue = 1; EditorUtility.SetDirty(manager); serializedObject.ApplyModifiedProperties(); inAddItem = false; } if (GUILayout.Button("Cancel", EditorStyles.miniButton)) { inAddItem = false; } GUILayout.EndHorizontal(); GUILayout.EndVertical(); } GUIStyle boxStyle = new GUIStyle(GUI.skin.box); scroll = GUILayout.BeginScrollView(scroll, GUILayout.MinHeight(200), GUILayout.ExpandHeight(false), GUILayout.ExpandWidth(false)); for (int i = 0; i < manager.startItems.Count; i++) { var item = manager.itemListData.items.Find(t => t.id.Equals(manager.startItems[i].id)); if (item) { GUILayout.BeginVertical("box"); GUILayout.BeginHorizontal(); GUILayout.BeginHorizontal(); var rect = GUILayoutUtility.GetRect(50, 50); if (item.icon != null) { DrawTextureGUI(rect, item.icon, new Vector2(50, 50)); } var name = " ID " + item.id.ToString("00") + "\n - " + item.name + "\n - " + item.type.ToString(); var content = new GUIContent(name, null, "Click to Open"); GUILayout.Label(content, EditorStyles.miniLabel); GUILayout.BeginVertical("box"); GUILayout.BeginHorizontal(); GUILayout.Label("Auto Equip", EditorStyles.miniLabel); manager.startItems[i].autoEquip = EditorGUILayout.Toggle("", manager.startItems[i].autoEquip, GUILayout.Width(30)); if (manager.startItems[i].autoEquip) { GUILayout.Label("IndexArea", EditorStyles.miniLabel); manager.startItems[i].indexArea = EditorGUILayout.IntField("", manager.startItems[i].indexArea, GUILayout.Width(30)); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Amount", EditorStyles.miniLabel); manager.startItems[i].amount = EditorGUILayout.IntField(manager.startItems[i].amount, GUILayout.Width(30)); if (manager.startItems[i].amount < 1) { manager.startItems[i].amount = 1; } GUILayout.EndHorizontal(); if (item.attributes.Count > 0) { manager.startItems[i].changeAttributes = GUILayout.Toggle(manager.startItems[i].changeAttributes, new GUIContent("Change Attributes", "This is a override of the original item attributes"), EditorStyles.miniButton, GUILayout.ExpandWidth(true)); } GUILayout.EndVertical(); GUILayout.EndHorizontal(); if (GUILayout.Button("x", GUILayout.Width(25), GUILayout.Height(25))) { itemReferenceList.DeleteArrayElementAtIndex(i); EditorUtility.SetDirty(target); serializedObject.ApplyModifiedProperties(); break; } GUILayout.EndHorizontal(); Color backgroundColor = GUI.backgroundColor; GUI.backgroundColor = Color.clear; var _rec = GUILayoutUtility.GetLastRect(); _rec.width -= 100; EditorGUIUtility.AddCursorRect(_rec, MouseCursor.Link); if (GUI.Button(_rec, "")) { if (manager.itemListData.inEdition) { if (vItemListWindow.Instance != null) { vItemListWindow.SetCurrentSelectedItem(manager.itemListData.items.IndexOf(item)); } else { vItemListWindow.CreateWindow(manager.itemListData, manager.itemListData.items.IndexOf(item)); } } else { vItemListWindow.CreateWindow(manager.itemListData, manager.itemListData.items.IndexOf(item)); } } GUILayout.Space(7); GUI.backgroundColor = backgroundColor; if (item.attributes != null && item.attributes.Count > 0) { if (manager.startItems[i].changeAttributes) { if (GUILayout.Button("Reset", EditorStyles.miniButton)) { manager.startItems[i].attributes = null; } if (manager.startItems[i].attributes == null) { manager.startItems[i].attributes = item.attributes.CopyAsNew(); } else if (manager.startItems[i].attributes.Count != item.attributes.Count) { manager.startItems[i].attributes = item.attributes.CopyAsNew(); } else { for (int a = 0; a < manager.startItems[i].attributes.Count; a++) { GUILayout.BeginHorizontal(); GUILayout.Label(manager.startItems[i].attributes[a].name.ToString()); manager.startItems[i].attributes[a].value = EditorGUILayout.IntField(manager.startItems[i].attributes[a].value, GUILayout.MaxWidth(60)); GUILayout.EndHorizontal(); } } } } GUILayout.EndVertical(); } else { itemReferenceList.DeleteArrayElementAtIndex(i); EditorUtility.SetDirty(manager); serializedObject.ApplyModifiedProperties(); break; } } GUILayout.EndScrollView(); GUI.skin.box = boxStyle; GUILayout.EndVertical(); if (GUI.changed) { EditorUtility.SetDirty(manager); serializedObject.ApplyModifiedProperties(); } } var equipPoints = serializedObject.FindProperty("equipPoints"); var applyAttributeEvents = serializedObject.FindProperty("applyAttributeEvents"); var onUseItem = serializedObject.FindProperty("onUseItem"); var onAddItem = serializedObject.FindProperty("onAddItem"); var onLeaveItem = serializedObject.FindProperty("onLeaveItem"); var onDropItem = serializedObject.FindProperty("onDropItem"); var onOpenCloseInventoty = serializedObject.FindProperty("onOpenCloseInventory"); var onEquipItem = serializedObject.FindProperty("onEquipItem"); var onUnequipItem = serializedObject.FindProperty("onUnequipItem"); var onCollectItems = serializedObject.FindProperty("onCollectItems"); if (equipPoints.arraySize != inEdition.Length) { inEdition = new bool[equipPoints.arraySize]; newPointNames = new string[manager.equipPoints.Count]; } if (equipPoints != null) { DrawEquipPoints(equipPoints); } if (applyAttributeEvents != null) { DrawAttributeEvents(applyAttributeEvents); } GUILayout.BeginVertical("box"); showManagerEvents = GUILayout.Toggle(showManagerEvents, showManagerEvents ? "Close Events" : "Open Events", EditorStyles.miniButton); GUI.skin = oldSkin; if (showManagerEvents) { if (onOpenCloseInventoty != null) { EditorGUILayout.PropertyField(onOpenCloseInventoty); } if (onAddItem != null) { EditorGUILayout.PropertyField(onAddItem); } if (onUseItem != null) { EditorGUILayout.PropertyField(onUseItem); } if (onDropItem != null) { EditorGUILayout.PropertyField(onDropItem); } if (onLeaveItem != null) { EditorGUILayout.PropertyField(onLeaveItem); } if (onCollectItems != null) { EditorGUILayout.PropertyField(onCollectItems); } if (onEquipItem != null) { EditorGUILayout.PropertyField(onEquipItem); } if (onUnequipItem != null) { EditorGUILayout.PropertyField(onUnequipItem); } } GUI.skin = skin; GUILayout.EndVertical(); } GUILayout.EndVertical(); if (GUI.changed) { EditorUtility.SetDirty(manager); serializedObject.ApplyModifiedProperties(); } GUI.skin = oldSkin; }
/// <summary> /// Draw a button looks like a hyperlink /// </summary> /// <param name="r"></param> /// <param name="label"></param> /// <returns></returns> public static bool LinkButton(Rect r, string label) { EditorGUIUtility.AddCursorRect(r, MouseCursor.Link); return(GUI.Button(r, label, LinkLabel)); }
//Draw the ports and connections sealed protected override void DrawNodeConnections(Rect drawCanvas, bool fullDrawPass, Vector2 canvasMousePos, float zoomFactor) { var e = Event.current; //Receive connections first if (clickedPort != null && e.type == EventType.MouseUp && e.button == 0) { if (rect.Contains(e.mousePosition)) { graph.ConnectNodes(clickedPort.parent, this); clickedPort = null; e.Use(); } else { dragDropMisses++; if (dragDropMisses == graph.allNodes.Count && clickedPort != null) { var source = clickedPort.parent; var pos = Event.current.mousePosition; var menu = new GenericMenu(); clickedPort = null; menu.AddItem(new GUIContent("Add Action State"), false, () => { var newState = graph.AddNode <ActionState>(pos); graph.ConnectNodes(source, newState); }); //PostGUI cause of zoom factors GraphEditorUtility.PostGUI += () => { menu.ShowAsContext(); }; Event.current.Use(); e.Use(); } } } var portRectLeft = new Rect(0, 0, 20, 20); var portRectRight = new Rect(0, 0, 20, 20); var portRectBottom = new Rect(0, 0, 20, 20); portRectLeft.center = new Vector2(rect.x - 11, rect.center.y); portRectRight.center = new Vector2(rect.xMax + 11, rect.center.y); portRectBottom.center = new Vector2(rect.center.x, rect.yMax + 11); if (maxOutConnections != 0) { if (fullDrawPass || drawCanvas.Overlaps(rect)) { EditorGUIUtility.AddCursorRect(portRectLeft, MouseCursor.ArrowPlus); EditorGUIUtility.AddCursorRect(portRectRight, MouseCursor.ArrowPlus); EditorGUIUtility.AddCursorRect(portRectBottom, MouseCursor.ArrowPlus); GUI.color = new Color(1, 1, 1, 0.3f); GUI.DrawTexture(portRectLeft, StyleSheet.arrowLeft); GUI.DrawTexture(portRectRight, StyleSheet.arrowRight); if (maxInConnections == 0) { GUI.DrawTexture(portRectBottom, StyleSheet.arrowBottom); } GUI.color = Color.white; if (GraphEditorUtility.allowClick && e.type == EventType.MouseDown && e.button == 0) { if (portRectLeft.Contains(e.mousePosition)) { clickedPort = new GUIPort(this, portRectLeft.center); dragDropMisses = 0; e.Use(); } if (portRectRight.Contains(e.mousePosition)) { clickedPort = new GUIPort(this, portRectRight.center); dragDropMisses = 0; e.Use(); } if (maxInConnections == 0 && portRectBottom.Contains(e.mousePosition)) { clickedPort = new GUIPort(this, portRectBottom.center); dragDropMisses = 0; e.Use(); } } } } //draw new linking if (clickedPort != null && clickedPort.parent == this) { Handles.DrawBezier(clickedPort.pos, e.mousePosition, clickedPort.pos, e.mousePosition, new Color(0.5f, 0.5f, 0.8f, 0.8f), null, 2); } //draw out connections for (var i = 0; i < outConnections.Count; i++) { var connection = outConnections[i] as FSMConnection; var targetState = connection.targetNode as FSMState; if (targetState == null) //In case of MissingNode type { continue; } var targetPos = targetState.GetConnectedInPortPosition(connection); var sourcePos = Vector2.zero; if (rect.center.x <= targetPos.x) { sourcePos = portRectRight.center; } if (rect.center.x > targetPos.x) { sourcePos = portRectLeft.center; } if (maxInConnections == 0 && rect.center.y < targetPos.y - 50 && Mathf.Abs(rect.center.x - targetPos.x) < 200) { sourcePos = portRectBottom.center; } var boundRect = RectUtils.GetBoundRect(sourcePos, targetPos); if (fullDrawPass || drawCanvas.Overlaps(boundRect)) { connection.DrawConnectionGUI(sourcePos, targetPos); } } }
static bool DoOrientationHandle(FaceData face, ShapeComponent shapeComponent) { Event evt = Event.current; bool hasRotated = false; switch (evt.type) { case EventType.MouseDown: if (s_OrientationControlIDs.Contains(HandleUtility.nearestControl) && evt.button == 0) { s_CurrentId = HandleUtility.nearestControl; GUIUtility.hotControl = s_CurrentId; evt.Use(); } break; case EventType.MouseUp: if (s_OrientationControlIDs.Contains(HandleUtility.nearestControl) && evt.button == 0) { GUIUtility.hotControl = 0; evt.Use(); if (s_CurrentId == HandleUtility.nearestControl) { //Execute rotation Vector3 targetedNormal = Vector3.zero; for (int i = 0; i < s_OrientationControlIDs.Length; i++) { if (s_OrientationControlIDs[i] == s_CurrentId) { targetedNormal = (s_ArrowsLines[i][1] - face.CenterPosition).normalized; break; } } var currentNormal = face.Normal; currentNormal.Scale(Math.Sign(shapeComponent.size)); targetedNormal.Scale(Math.Sign(shapeComponent.size)); Vector3 rotationAxis = Vector3.Cross(currentNormal, targetedNormal); var angle = Vector3.SignedAngle(currentNormal, targetedNormal, rotationAxis); s_ShapeRotation = Quaternion.AngleAxis(angle, rotationAxis); s_CurrentAngle = (s_CurrentAngle + angle) % 360; hasRotated = true; } s_CurrentId = -1; } break; case EventType.Layout: for (int i = 0; i < 4; i++) { var rectPos = 0.8f * s_ArrowsLines[i][1] + 0.2f * face.CenterPosition; float dist = HandleUtility.DistanceToRectangle(rectPos, Quaternion.LookRotation(face.Normal), HandleUtility.GetHandleSize(face.CenterPosition) * s_DefaultMidpointSquareSize / 2f); HandleUtility.AddControl(s_OrientationControlIDs[i], dist); } break; case EventType.Repaint: if (s_CurrentArrowHovered != HandleUtility.nearestControl) { s_CurrentAngle = 0f; } int pointsCount = face.Points.Length; s_CurrentArrowHovered = -1; for (int i = 0; i < pointsCount; i++) { var rectHandleSize = HandleUtility.GetHandleSize(face.CenterPosition) * s_DefaultMidpointSquareSize; var sideDirection = (face.Points[(i + 1) % pointsCount] - face.Points[i]).normalized; var arrowDirection = Vector3.Cross(face.Normal.normalized, sideDirection).normalized; var topDirection = 2.5f * rectHandleSize * arrowDirection; var top = face.CenterPosition + topDirection; var A = topDirection.magnitude; var a = 0.33f * Mathf.Sqrt(2f * A * A); var h = 0.5f * Mathf.Sqrt(2f * a * a); s_ArrowsLines[i][0] = top - (h * arrowDirection + h * sideDirection); s_ArrowsLines[i][1] = top; s_ArrowsLines[i][2] = top - (h * arrowDirection - h * sideDirection); bool selected = HandleUtility.nearestControl == s_OrientationControlIDs[i]; Color color = selected ? EditorHandleDrawing.edgeSelectedColor : k_BoundsHandleColor; color.a = 1.0f; using (new Handles.DrawingScope(color)) { Handles.DrawAAPolyLine(5f, s_ArrowsLines[i]); if (selected) { EditorGUIUtility.AddCursorRect(new Rect(0, 0, Screen.width, Screen.height), MouseCursor.RotateArrow); s_CurrentArrowHovered = HandleUtility.nearestControl; Handles.DrawAAPolyLine(3f, new Vector3[] { Vector3.Scale(shapeComponent.rotation * Vector3.up, shapeComponent.size / 2f), Vector3.zero, Vector3.Scale(shapeComponent.rotation * Vector3.forward, shapeComponent.size / 2f) }); } } } break; case EventType.MouseDrag: if (s_OrientationControlIDs.Contains(s_CurrentId) && HandleUtility.nearestControl != s_CurrentId) { GUIUtility.hotControl = 0; s_CurrentId = -1; } break; } return(hasRotated); }
//This is the window shown at the top left with a GUI for extra editing opions of the selected node. static Rect ShowInspectorGUIPanel(Graph graph, Vector2 canvasMousePos) { var inspectorPanel = default(Rect); if ((GraphEditorUtility.activeNode == null && GraphEditorUtility.activeConnection == null) || Prefs.useExternalInspector) { return(inspectorPanel); } inspectorPanel.x = 10; inspectorPanel.y = 30; inspectorPanel.width = Prefs.inspectorPanelWidth; inspectorPanel.height = inspectorPanelHeight; var resizeRect = Rect.MinMaxRect(inspectorPanel.xMax - 2, inspectorPanel.yMin, inspectorPanel.xMax + 2, inspectorPanel.yMax); EditorGUIUtility.AddCursorRect(resizeRect, MouseCursor.ResizeHorizontal); if (e.type == EventType.MouseDown && resizeRect.Contains(e.mousePosition)) { isResizingInspectorPanel = true; e.Use(); } if (isResizingInspectorPanel && e.type == EventType.Layout) { Prefs.inspectorPanelWidth += e.delta.x; } if (e.rawType == EventType.MouseUp) { isResizingInspectorPanel = false; } var headerRect = new Rect(inspectorPanel.x, inspectorPanel.y, inspectorPanel.width, 30); EditorGUIUtility.AddCursorRect(headerRect, MouseCursor.Link); if (GUI.Button(headerRect, string.Empty, StyleSheet.button)) { Prefs.showNodePanel = !Prefs.showNodePanel; } GUI.Box(inspectorPanel, string.Empty, StyleSheet.windowShadow); var title = GraphEditorUtility.activeNode != null ? GraphEditorUtility.activeNode.name : "Connection"; if (Prefs.showNodePanel) { var viewRect = new Rect(inspectorPanel.x, inspectorPanel.y, inspectorPanel.width + 18, screenHeight - inspectorPanel.y - 30); inspectorPanelScrollPos = GUI.BeginScrollView(viewRect, inspectorPanelScrollPos, inspectorPanel); GUILayout.BeginArea(inspectorPanel, title, StyleSheet.editorPanel); GUILayout.Space(5); if (GraphEditorUtility.activeNode != null) { Node.ShowNodeInspectorGUI(GraphEditorUtility.activeNode); } else if (GraphEditorUtility.activeConnection != null) { Connection.ShowConnectionInspectorGUI(GraphEditorUtility.activeConnection); } EditorUtils.EndOfInspector(); if (e.type == EventType.Repaint) { inspectorPanelHeight = GUILayoutUtility.GetLastRect().yMax + 5; } GUILayout.EndArea(); GUI.EndScrollView(); if (GUI.changed) { EditorUtility.SetDirty(graph); } } else { inspectorPanelHeight = 55; GUILayout.BeginArea(inspectorPanel, title, StyleSheet.editorPanel); GUI.color = new Color(1, 1, 1, 0.2f); if (GUILayout.Button("...", StyleSheet.button)) { Prefs.showNodePanel = true; } GUILayout.EndArea(); GUI.color = Color.white; } return(inspectorPanel); }
/* * private void DrawAnimEditBoneHandles( Event a_rEvent ) * { * // TODO * } */ private void DrawPoseEditBoneHandles(Event a_rEvent) { Color oInnerBoneDiscColor = Uni2DEditorPreferences.InnerBoneDiscHandleColor; Color oOuterBoneDiscColor = Uni2DEditorPreferences.OuterBoneDiscHandleColor; Color oInnerRootBoneDiscColor = Uni2DEditorPreferences.InnerRootBoneDiscHandleColor; Color oOuterRootBoneDiscColor = Uni2DEditorPreferences.OuterRootBoneDiscHandleColor; Vector3 f3CameraForward = SceneView.currentDrawingSceneView.camera.transform.forward; BoneHandle eBoneHandle; Uni2DSmoothBindingBone rNearestBone = Uni2DEditorSmoothBindingUtils.PickNearestBoneArticulationInPosingMode(ms_rSprite, a_rEvent.mousePosition, out eBoneHandle, null); Uni2DSmoothBindingBone[] oBones = ms_rSprite.Bones.Except(new Uni2DSmoothBindingBone[] { rNearestBone }).ToArray( ); //Transform rActiveBone = Uni2DEditorSmoothBindingGUI.activeBone; //Selection.activeTransform.GetComponentsInChildren<Transform>( false ).Except( new Transform[ ]{ rRootBone, rNearestBone } ).ToArray( ); Transform rActiveBoneTransform = Uni2DEditorSmoothBindingGUI.activeBone != null ? Uni2DEditorSmoothBindingGUI.activeBone.transform : null; oInnerBoneDiscColor.a = 0.2f; oOuterBoneDiscColor.a = 0.2f; oInnerRootBoneDiscColor.a = 0.2f; oOuterRootBoneDiscColor.a = 0.2f; for (int iBoneIndex = 0, iBoneCount = oBones.Length; iBoneIndex < iBoneCount; ++iBoneIndex) { Uni2DSmoothBindingBone rBone = oBones[iBoneIndex]; if (rBone.IsFakeRootBone == false) { Vector3 f3BonePosition = rBone.transform.position; float fHandleSize = HandleUtility.GetHandleSize(f3BonePosition); if (rBone.Parent != null) { // Outer disc Handles.color = oOuterBoneDiscColor; Handles.DrawSolidDisc(f3BonePosition, f3CameraForward, 0.25f * fHandleSize); // Inner disc Handles.color = oInnerBoneDiscColor; Handles.DrawSolidDisc(f3BonePosition, f3CameraForward, 0.125f * fHandleSize); } else { // Outer disc Handles.color = oOuterRootBoneDiscColor; Handles.DrawSolidDisc(f3BonePosition, f3CameraForward, 0.25f * fHandleSize); // Inner disc Handles.color = oInnerRootBoneDiscColor; Handles.DrawSolidDisc(f3BonePosition, f3CameraForward, 0.125f * fHandleSize); } } } if (rNearestBone != null) { MouseCursor eMouseCursor; //Color oHandleColor; if (eBoneHandle == BoneHandle.InnerDisc) { #if UNITY_3_5 // Unity 3.5.x: Display an arrow while moving, and a link cursor while hovering eMouseCursor = rActiveBoneTransform != null ? MouseCursor.Arrow : MouseCursor.Link; #else // Unity 4.x.y: Display an arrow with a plus sign eMouseCursor = MouseCursor.ArrowPlus; #endif oInnerBoneDiscColor.a = 0.8f; oInnerRootBoneDiscColor.a = 0.8f; oOuterBoneDiscColor.a = 0.2f; oOuterRootBoneDiscColor.a = 0.2f; } else { eMouseCursor = MouseCursor.MoveArrow; oInnerBoneDiscColor.a = 0.2f; oInnerRootBoneDiscColor.a = 0.2f; oOuterBoneDiscColor.a = 0.8f; oOuterRootBoneDiscColor.a = 0.8f; } Handles.BeginGUI( ); { Vector2 f2MousePos = a_rEvent.mousePosition; Rect oCursorRect = new Rect(f2MousePos.x - 16.0f, f2MousePos.y - 16.0f, 32.0f, 32.0f); EditorGUIUtility.AddCursorRect(oCursorRect, eMouseCursor); } Handles.EndGUI( ); Vector3 f3NearestBonePos = rNearestBone.transform.position; float fHandleSize = HandleUtility.GetHandleSize(f3NearestBonePos); if (rNearestBone.Parent != null) { // Outer disc Handles.color = oOuterBoneDiscColor; Handles.DrawSolidDisc(f3NearestBonePos, f3CameraForward, 0.25f * fHandleSize); // Inner disc Handles.color = oInnerBoneDiscColor; Handles.DrawSolidDisc(f3NearestBonePos, f3CameraForward, 0.125f * fHandleSize); } else { // Outer disc Handles.color = oOuterRootBoneDiscColor; Handles.DrawSolidDisc(f3NearestBonePos, f3CameraForward, 0.25f * fHandleSize); // Inner disc Handles.color = oInnerRootBoneDiscColor; Handles.DrawSolidDisc(f3NearestBonePos, f3CameraForward, 0.125f * fHandleSize); } } if (rActiveBoneTransform != null) { Handles.color = Uni2DEditorSmoothBindingGUI.activeBone.Parent != null ? Uni2DEditorPreferences.SelectedBoneDiscHandleOutlineColor : Uni2DEditorPreferences.SelectedRootBoneDiscHandleOutlineColor; float fHandleSize = HandleUtility.GetHandleSize(rActiveBoneTransform.position); Handles.DrawWireDisc(rActiveBoneTransform.position, f3CameraForward, 0.25f * fHandleSize); } }
void HandleEvents(Event e) { //set repaint counter if need be if (mouseOverWindow == this && (e.isMouse || e.isKey)) { willRepaint += 2; } //snap all nodes on assumption change if (e.type == EventType.MouseUp || e.type == EventType.KeyUp) { SnapNodes(); } if (e.type == EventType.KeyDown && e.keyCode == KeyCode.F && GUIUtility.keyboardControl == 0) { if (currentGraph.allNodes.Count > 0) { FocusPosition(GetNodeBounds(viewRect, false).center); } else { FocusPosition(virtualCenter); } } if (e.type == EventType.MouseDown && e.button == 2 && e.clickCount == 2) { FocusPosition(ViewToCanvas(e.mousePosition)); } if (e.type == EventType.ScrollWheel && Graph.allowClick) { if (canvasRect.Contains(e.mousePosition)) { ZoomAt(e.mousePosition, -e.delta.y > 0? 0.5f : -0.5f); } } //Control + Space for default zoom level (1f) if (e.type == EventType.KeyDown && e.control && e.keyCode == KeyCode.Space) { ZoomAt(e.mousePosition, 1); } if ((e.button == 2 && e.type == EventType.MouseDrag && canvasRect.Contains(e.mousePosition)) /* || (e.button == 0 && e.type == EventType.MouseDrag && e.shift && e.isMouse) */) { pan += e.delta; smoothPan = null; smoothZoomFactor = null; } if (e.type == EventType.MouseDown && e.button == 2 && canvasRect.Contains(e.mousePosition)) { mouseButton2Down = true; } if (e.type == EventType.MouseUp && e.button == 2) { mouseButton2Down = false; } if (mouseButton2Down == true) { EditorGUIUtility.AddCursorRect(new Rect(0, 0, Screen.width, Screen.height), MouseCursor.Pan); } }
public override void Draw(DrawInfo drawInfo) { base.Draw(drawInfo); if (!m_isVisible) { return; } if (m_isEditingFields && m_currentParameterType != PropertyType.Global) { if (m_materialMode && m_currentParameterType != PropertyType.Constant) { EditorGUI.BeginChangeCheck(); if (m_floatMode) { UIUtils.DrawFloat(this, ref m_propertyDrawPos, ref m_materialValue, LabelWidth * drawInfo.InvertedZoom); } else { DrawSlider(ref m_materialValue, drawInfo); } if (EditorGUI.EndChangeCheck()) { PreviewIsDirty = true; m_requireMaterialUpdate = true; if (m_currentParameterType != PropertyType.Constant) { BeginDelayedDirtyProperty(); } } } else { EditorGUI.BeginChangeCheck(); if (m_floatMode) { UIUtils.DrawFloat(this, ref m_propertyDrawPos, ref m_defaultValue, LabelWidth * drawInfo.InvertedZoom); } else { DrawSlider(ref m_defaultValue, drawInfo); } if (EditorGUI.EndChangeCheck()) { PreviewIsDirty = true; BeginDelayedDirtyProperty(); } } } else if (drawInfo.CurrentEventType == EventType.Repaint && ContainerGraph.LodLevel <= ParentGraph.NodeLOD.LOD4) { if (m_currentParameterType == PropertyType.Global) { bool guiEnabled = GUI.enabled; GUI.enabled = false; DrawFakeFloatMaterial(drawInfo); GUI.enabled = guiEnabled; } else if (m_materialMode && m_currentParameterType != PropertyType.Constant) { DrawFakeFloatMaterial(drawInfo); } else { if (m_floatMode) { //UIUtils.DrawFloat( this, ref m_propertyDrawPos, ref m_defaultValue, LabelWidth * drawInfo.InvertedZoom ); Rect fakeField = m_propertyDrawPos; fakeField.xMin += LabelWidth * drawInfo.InvertedZoom; Rect fakeLabel = m_propertyDrawPos; fakeLabel.xMax = fakeField.xMin; EditorGUIUtility.AddCursorRect(fakeLabel, MouseCursor.SlideArrow); EditorGUIUtility.AddCursorRect(fakeField, MouseCursor.Text); if (m_previousValue[0] != m_defaultValue) { m_previousValue[0] = m_defaultValue; m_fieldText[0] = m_defaultValue.ToString(); } GUI.Label(fakeField, m_fieldText[0], UIUtils.MainSkin.textField); } else { DrawFakeSlider(ref m_defaultValue, drawInfo); } } } }
void DoCanvasGroups(Event e) { if (currentGraph.canvasGroups == null) { return; } for (var i = 0; i < currentGraph.canvasGroups.Count; i++) { var style = EditorGUIUtility.isProSkin? (GUIStyle)"editorPanel" : "box"; var group = currentGraph.canvasGroups[i]; var handleRect = new Rect(group.rect.x, group.rect.y, group.rect.width, 25); var scaleRect = new Rect(group.rect.xMax - 20, group.rect.yMax - 20, 20, 20); GUI.color = new Color(1, 1, 1, 0.4f); GUI.Box(group.rect, "", style); GUI.Box(new Rect(scaleRect.x + 10, scaleRect.y + 10, 6, 6), "", (GUIStyle)"scaleArrow"); GUI.color = Color.white; GUI.Box(handleRect, group.name, style); EditorGUIUtility.AddCursorRect(handleRect, group.isRenaming? MouseCursor.Text : MouseCursor.Link); EditorGUIUtility.AddCursorRect(scaleRect, MouseCursor.ResizeUpLeft); if (group.isRenaming) { group.name = EditorGUI.TextField(handleRect, group.name, style); if (e.keyCode == KeyCode.Return || (e.type == EventType.MouseDown && !handleRect.Contains(e.mousePosition))) { group.isRenaming = false; GUIUtility.hotControl = 0; GUIUtility.keyboardControl = 0; } } if (e.type == EventType.MouseDown && Graph.allowClick) { //calc group nodes tempGroupNodes = currentGraph.allNodes.Where(n => RectEncapsulates(group.rect, n.nodeRect)).ToArray(); tempNestedGroups = currentGraph.canvasGroups.Where(c => RectEncapsulates(group.rect, c.rect)).ToArray(); if (handleRect.Contains(e.mousePosition)) { if (e.button == 1) { Undo.RecordObject(this, "Group Operation"); var menu = new GenericMenu(); menu.AddItem(new GUIContent("Rename"), false, () => { group.isRenaming = true; }); menu.AddItem(new GUIContent("Select Nodes"), false, () => { Graph.multiSelection = tempGroupNodes.Cast <object>().ToList(); }); menu.AddItem(new GUIContent("Delete Group"), false, () => { currentGraph.canvasGroups.Remove(group); }); Graph.PostGUI += () => { menu.ShowAsContext(); }; } else if (e.button == 0) { group.isDragging = true; } e.Use(); } if (e.button == 0 && scaleRect.Contains(e.mousePosition)) { group.isRescaling = true; e.Use(); } } if (e.type == EventType.MouseUp) { group.isDragging = false; group.isRescaling = false; } if (e.type == EventType.MouseDrag) { if (group.isDragging) { Undo.RecordObject(currentGraph, "Move Canvas Group"); group.rect.x += e.delta.x; group.rect.y += e.delta.y; foreach (var node in tempGroupNodes) { node.nodePosition += e.delta; } foreach (var otherGroup in tempNestedGroups) { otherGroup.rect.x += e.delta.x; otherGroup.rect.y += e.delta.y; } } if (group.isRescaling) { Undo.RecordObject(currentGraph, "Scale Canvas Group"); group.rect.xMax = Mathf.Max(e.mousePosition.x + 5, group.rect.x + 100); group.rect.yMax = Mathf.Max(e.mousePosition.y + 5, group.rect.y + 100); } } } }
public void DrawSequenceControls(Rect ViewportArea, ImageSequencer editor) { m_PlayControlsRect = new Rect(ViewportArea.x, (ViewportArea.y + ViewportArea.height), ViewportArea.width, 100); using (new GUILayout.AreaScope(m_PlayControlsRect, GUIContent.none, ImageSequencer.styles.playbackControlWindow)) { Rect area = new Rect(16, 16, m_PlayControlsRect.width - 32, m_PlayControlsRect.height - 32); //GUILayout.BeginArea(area); using (new GUILayout.VerticalScope()) { // TRACKBAR int count = sequence.length; GUILayout.Space(16); // Reserve Layout for labels Rect bar_rect = GUILayoutUtility.GetRect(area.width, 16); EditorGUIUtility.AddCursorRect(bar_rect, MouseCursor.ResizeHorizontal); if (Event.current.type == EventType.MouseDown && bar_rect.Contains(Event.current.mousePosition)) { m_IsScrobbing = true; } if (Event.current.type == EventType.MouseUp || Event.current.rawType == EventType.MouseUp) { m_IsScrobbing = false; } if (m_IsScrobbing && (Event.current.type == EventType.MouseDrag || Event.current.type == EventType.MouseDown)) { float pos = (Event.current.mousePosition.x - bar_rect.x) / bar_rect.width; int frame = (int)Mathf.Round(pos * numFrames); if (frame != currentFrameIndex) { currentFrameIndex = frame; Invalidate(true); } } EditorGUI.DrawRect(bar_rect, ImageSequencer.styles.CookBarDirty); float width = bar_rect.width / count; Rect textpos; for (int i = 0; i < count; i++) { if (!sequence.frames[i].dirty) { Rect cell = new Rect(bar_rect.x + i * width, bar_rect.y, width, bar_rect.height); EditorGUI.DrawRect(cell, ImageSequencer.styles.CookBarCooked); } if (i == currentFrameIndex) { Rect cursor = new Rect(bar_rect.x + i * width, bar_rect.y, width, bar_rect.height); EditorGUI.DrawRect(cursor, new Color(1.0f, 1.0f, 1.0f, 0.5f)); } // Labels : Every multiple of 10 based on homemade formula int step = 10 * (int)Mathf.Max(1, Mathf.Floor(8 * (float)count / bar_rect.width)); if (((i + 1) % step) == 0) { textpos = new Rect(bar_rect.x + i * width, bar_rect.y - 16, 32, 16); GUI.Label(textpos, (i + 1).ToString(), EditorStyles.largeLabel); Rect cursor = new Rect(bar_rect.x + i * width, bar_rect.y, 1, bar_rect.height); EditorGUI.DrawRect(cursor, new Color(1.0f, 1.0f, 1.0f, 0.2f)); } } // Labels : First textpos = new Rect(bar_rect.x, bar_rect.y - 16, 32, 16); GUI.Label(textpos, VFXToolboxGUIUtility.Get("1"), EditorStyles.largeLabel); GUILayout.Space(16); // PLAY CONTROLS bool lastplay; using (new GUILayout.HorizontalScope(EditorStyles.toolbar)) { lastplay = m_IsPlaying; if (GUILayout.Button(ImageSequencer.styles.iconFirst, VFXToolboxStyles.toolbarButton, GUILayout.Width(32))) { FirstFrame(); } if (GUILayout.Button(ImageSequencer.styles.iconBack, VFXToolboxStyles.toolbarButton, GUILayout.Width(24))) { PreviousFrame(); } bool playing = GUILayout.Toggle(m_IsPlaying, ImageSequencer.styles.iconPlay, VFXToolboxStyles.toolbarButton, GUILayout.Width(24)); if (m_IsPlaying != playing) { TogglePlaySequence(); } if (GUILayout.Button(ImageSequencer.styles.iconForward, VFXToolboxStyles.toolbarButton, GUILayout.Width(24))) { NextFrame(); } if (GUILayout.Button(ImageSequencer.styles.iconLast, VFXToolboxStyles.toolbarButton, GUILayout.Width(32))) { LastFrame(); } if (lastplay != m_IsPlaying) { m_EditorTime = EditorApplication.timeSinceStartup; } GUILayout.FlexibleSpace(); GUILayout.Label(VFXToolboxGUIUtility.GetTextAndIcon("Frame : ", "Profiler.Record"), VFXToolboxStyles.toolbarButton); m_CurrentFrame = Mathf.Clamp(EditorGUILayout.IntField(m_CurrentFrame + 1, VFXToolboxStyles.toolbarTextField, GUILayout.Width(42)) - 1, 0, numFrames - 1); GUILayout.Label(" on " + numFrames + " ( TCR : " + GetTCR(m_CurrentFrame, (int)m_PlayFramerate) + " ) ", VFXToolboxStyles.toolbarButton); GUILayout.FlexibleSpace(); ShowFrameratePopup(); } } //GUILayout.EndArea(); } }
void HandleNodeEvents(Rect rect, int nodeId, Event e) { if (Utils.BitMask.IsSet(m_nodeMask, nodeId) == false) { return; } // // Translate node position to preview window // Vector2 nodePos = m_nodePositions[nodeId]; nodePos = nodePos * m_previewScale; nodePos = nodePos + m_previewOffset; Rect nodeRect = new Rect(rect.center.x + nodePos.x - 8, rect.center.y + nodePos.y - 8, 16, 16); Vector2 rotateHandlePos = nodeRect.center + (Vector2)(Quaternion.Euler(0, 0, -m_nodeAngles[nodeId]) * Vector2.right * ROTATE_ARROW_LENGTH); Rect nodeRotateRect = new Rect(rotateHandlePos.x - 8, rotateHandlePos.y - 8, 16, 16); // // Handle Events // if (m_playing == false) { if (m_dragState == eDragState.None) { if (e.button == 0 && rect.Contains(e.mousePosition)) { // Event rect EditorGUIUtility.AddCursorRect(nodeRect, MouseCursor.MoveArrow); // Node if (e.type == EventType.MouseDown && nodeRect.Contains(e.mousePosition)) { ClearSelection(); m_selectedNode = nodeId; m_dragState = eDragState.MoveNode; GUI.FocusControl("none"); e.Use(); } else if (e.type == EventType.MouseDrag && m_selectedNode == nodeId && nodeRect.Contains(e.mousePosition)) { m_dragState = eDragState.MoveNode; e.Use(); } // Node rotate Handle else if (m_selectedNode == nodeId) { EditorGUIUtility.AddCursorRect(nodeRotateRect, MouseCursor.RotateArrow); if (e.type == EventType.MouseDown && nodeRotateRect.Contains(e.mousePosition)) { m_dragState = eDragState.RotateNode; GUI.FocusControl("none"); e.Use(); } if (e.type == EventType.MouseDrag) { m_dragState = eDragState.RotateNode; e.Use(); } } } } else if (m_dragState == eDragState.MoveNode) { EditorGUIUtility.AddCursorRect(rect, MouseCursor.MoveArrow); if (e.button == 0 && m_selectedNode == nodeId && e.type == EventType.MouseDrag) { MoveNode(m_selectedNode, (e.mousePosition - rect.center - m_previewOffset) / m_previewScale, (e.modifiers & (EventModifiers.Shift)) == 0); // only snap if not holding shift e.Use(); } else if (e.button == 0 && m_selectedNode == nodeId && e.type == EventType.MouseUp) { m_dragState = eDragState.None; e.Use(); ApplyChanges(); } } else if (m_dragState == eDragState.RotateNode) { EditorGUIUtility.AddCursorRect(rect, MouseCursor.RotateArrow); if (e.button == 0 && m_selectedNode == nodeId && e.type == EventType.MouseDrag) { Vector2 endPos = (e.mousePosition - rect.center - m_previewOffset) / m_previewScale; float angle = -(endPos - m_nodePositions[m_selectedNode]).normalized.GetDirectionAngle(); // Snap to 15 if holding control/command if ((e.modifiers & (EventModifiers.Control | EventModifiers.Command)) > 0) { angle = Utils.Snap(angle, 15.0f); } // Snap to 1 (if not holding shift) else if ((e.modifiers & (EventModifiers.Shift)) == 0) { angle = Utils.Snap(angle, 1.0f); } RotateNode(m_selectedNode, angle); e.Use(); } else if (e.button == 0 && m_selectedNode == nodeId && e.type == EventType.MouseUp) { m_dragState = eDragState.None; e.Use(); ApplyChanges(); } } } }
public void OnGUI() { //GUI.DrawTexture(this.mWelcomeScreenImageRect, this.mWelcomeScreenImage); GUI.Label(this.mWelcomeIntroRect, "欢迎使用LuaFramework,它是个基于tolua#,\n将C#类注册进Lua,并且附带了AssetBundle管理的演示框架。入门步骤如下:"); GUI.DrawTexture(this.mSamplesImageRect, this.mSamplesImage); GUI.Label(this.mSamplesHeaderRect, "新手入门 - 生成Wrap文件(必须)"); GUI.Label(this.mSamplesDescriptionRect, "单击Lua菜单里面Generate All子菜单."); GUI.DrawTexture(this.mDocImageRect, this.mDocImage); GUI.Label(this.mDocHeaderRect, "新手入门 - 根据不同平台生成AssetBundle资源(必须)"); GUI.Label(this.mDocDescriptionRect, "单击Game菜单里面Build XXX Resources子菜单."); GUI.DrawTexture(this.mVideoImageRect, this.mVideoImage); GUI.Label(this.mVideoHeaderRect, "新手入门 - 改完注册到Lua的C#类,需清除文件缓存,重新生成"); GUI.Label(this.mVideoDescriptionRect, "单击Lua菜单里面Clear Wrap Files子菜单."); GUI.DrawTexture(this.mForumImageRect, this.mForumImage); GUI.Label(this.mForumHeaderRect, "新手入门 - Lua需要统一的UTF-8文件编码"); GUI.Label(this.mForumDescriptionRect, "单击Lua菜单里面Encode LuaFile with UTF-8子菜单."); GUI.DrawTexture(this.mContactImageRect, this.mContactImage); GUI.Label(this.mContactHeaderRect, " 加入技术支持社群"); GUI.Label(this.mContactDescriptionRect, "QQ群:469941220 或者 QQ群:62978170"); GUI.Label(this.mVersionRect, version); flag = GUI.Toggle(this.mToggleButtonRect, flag, "开始时候显示对话框"); if (flag) { PlayerPrefs.SetInt("ShowWelcomeScreen", 1); } else { PlayerPrefs.SetInt("ShowWelcomeScreen", 0); } EditorGUIUtility.AddCursorRect(this.mSamplesImageRect, MouseCursor.Link); EditorGUIUtility.AddCursorRect(this.mSamplesHeaderRect, MouseCursor.Link); EditorGUIUtility.AddCursorRect(this.mSamplesDescriptionRect, MouseCursor.Link); EditorGUIUtility.AddCursorRect(this.mDocImageRect, MouseCursor.Link); EditorGUIUtility.AddCursorRect(this.mDocHeaderRect, MouseCursor.Link); EditorGUIUtility.AddCursorRect(this.mDocDescriptionRect, MouseCursor.Link); EditorGUIUtility.AddCursorRect(this.mVideoImageRect, MouseCursor.Link); EditorGUIUtility.AddCursorRect(this.mVideoHeaderRect, MouseCursor.Link); EditorGUIUtility.AddCursorRect(this.mVideoDescriptionRect, MouseCursor.Link); EditorGUIUtility.AddCursorRect(this.mForumImageRect, MouseCursor.Link); EditorGUIUtility.AddCursorRect(this.mForumHeaderRect, MouseCursor.Link); EditorGUIUtility.AddCursorRect(this.mForumDescriptionRect, MouseCursor.Link); EditorGUIUtility.AddCursorRect(this.mContactImageRect, MouseCursor.Link); EditorGUIUtility.AddCursorRect(this.mContactHeaderRect, MouseCursor.Link); EditorGUIUtility.AddCursorRect(this.mContactDescriptionRect, MouseCursor.Link); if (Event.current.type == EventType.MouseUp) { Vector2 mousePosition = Event.current.mousePosition; if ((this.mSamplesImageRect.Contains(mousePosition) || this.mSamplesHeaderRect.Contains(mousePosition)) || this.mSamplesDescriptionRect.Contains(mousePosition)) { //LuaBinding.Binding(); } else if ((this.mDocImageRect.Contains(mousePosition) || this.mDocHeaderRect.Contains(mousePosition)) || this.mDocDescriptionRect.Contains(mousePosition)) { if (Application.platform == RuntimePlatform.WindowsEditor) { //Packager.BuildWindowsResource(); } if (Application.platform == RuntimePlatform.OSXEditor) { //Packager.BuildiPhoneResource(); } } else if ((this.mVideoImageRect.Contains(mousePosition) || this.mVideoHeaderRect.Contains(mousePosition)) || this.mVideoDescriptionRect.Contains(mousePosition)) { //LuaBinding.ClearLuaBinder(); } else if ((this.mForumImageRect.Contains(mousePosition) || this.mForumHeaderRect.Contains(mousePosition)) || this.mForumDescriptionRect.Contains(mousePosition)) { //LuaBinding.EncodeLuaFile(); } else if ((this.mContactImageRect.Contains(mousePosition) || this.mContactHeaderRect.Contains(mousePosition)) || this.mContactDescriptionRect.Contains(mousePosition)) { Application.OpenURL("http://shang.qq.com/wpa/qunwpa?idkey=20a9db3bac183720c13a13420c7c805ff4a2810c532db916e6f5e08ea6bc3a8f"); } } }
void OnCurveGUI(Rect rect, SerializedProperty curve, CurveState state) { // Discard invisible curves if (!state.visible) { return; } var animCurve = curve.animationCurveValue; var keys = animCurve.keys; var length = keys.Length; // Curve drawing // Slightly dim non-editable curves var color = state.color; if (!state.editable) { color.a *= 0.5f; } Handles.color = color; var bounds = settings.bounds; if (length == 0) { var p1 = CurveToCanvas(new Vector3(bounds.xMin, state.zeroKeyConstantValue)); var p2 = CurveToCanvas(new Vector3(bounds.xMax, state.zeroKeyConstantValue)); Handles.DrawAAPolyLine(state.width, p1, p2); } else if (length == 1) { var p1 = CurveToCanvas(new Vector3(bounds.xMin, keys[0].value)); var p2 = CurveToCanvas(new Vector3(bounds.xMax, keys[0].value)); Handles.DrawAAPolyLine(state.width, p1, p2); } else { var prevKey = keys[0]; for (int k = 1; k < length; k++) { var key = keys[k]; var pts = BezierSegment(prevKey, key); if (float.IsInfinity(prevKey.outTangent) || float.IsInfinity(key.inTangent)) { var s = HardSegment(prevKey, key); Handles.DrawAAPolyLine(state.width, s[0], s[1], s[2]); } else { Handles.DrawBezier(pts[0], pts[3], pts[1], pts[2], color, null, state.width); } prevKey = key; } // Curve extents & loops if (keys[0].time > bounds.xMin) { if (state.loopInBounds) { var p1 = keys[length - 1]; p1.time -= settings.bounds.width; var p2 = keys[0]; var pts = BezierSegment(p1, p2); if (float.IsInfinity(p1.outTangent) || float.IsInfinity(p2.inTangent)) { var s = HardSegment(p1, p2); Handles.DrawAAPolyLine(state.width, s[0], s[1], s[2]); } else { Handles.DrawBezier(pts[0], pts[3], pts[1], pts[2], color, null, state.width); } } else { var p1 = CurveToCanvas(new Vector3(bounds.xMin, keys[0].value)); var p2 = CurveToCanvas(keys[0]); Handles.DrawAAPolyLine(state.width, p1, p2); } } if (keys[length - 1].time < bounds.xMax) { if (state.loopInBounds) { var p1 = keys[length - 1]; var p2 = keys[0]; p2.time += settings.bounds.width; var pts = BezierSegment(p1, p2); if (float.IsInfinity(p1.outTangent) || float.IsInfinity(p2.inTangent)) { var s = HardSegment(p1, p2); Handles.DrawAAPolyLine(state.width, s[0], s[1], s[2]); } else { Handles.DrawBezier(pts[0], pts[3], pts[1], pts[2], color, null, state.width); } } else { var p1 = CurveToCanvas(keys[length - 1]); var p2 = CurveToCanvas(new Vector3(bounds.xMax, keys[length - 1].value)); Handles.DrawAAPolyLine(state.width, p1, p2); } } } // Make sure selection is correct (undo can break it) bool isCurrentlySelectedCurve = curve == m_SelectedCurve; if (isCurrentlySelectedCurve && m_SelectedKeyframeIndex >= length) { m_SelectedKeyframeIndex = -1; } // Handles & keys for (int k = 0; k < length; k++) { bool isCurrentlySelectedKeyframe = k == m_SelectedKeyframeIndex; var e = Event.current; var pos = CurveToCanvas(keys[k]); var hitRect = new Rect(pos.x - 8f, pos.y - 8f, 16f, 16f); var offset = isCurrentlySelectedCurve ? new RectOffset(5, 5, 5, 5) : new RectOffset(6, 6, 6, 6); var outTangent = pos + CurveTangentToCanvas(keys[k].outTangent).normalized * 40f; var inTangent = pos - CurveTangentToCanvas(keys[k].inTangent).normalized * 40f; var inTangentHitRect = new Rect(inTangent.x - 7f, inTangent.y - 7f, 14f, 14f); var outTangentHitrect = new Rect(outTangent.x - 7f, outTangent.y - 7f, 14f, 14f); // Draw if (state.showNonEditableHandles) { if (e.type == EventType.Repaint) { var selectedColor = (isCurrentlySelectedCurve && isCurrentlySelectedKeyframe) ? settings.selectionColor : state.color; // Keyframe EditorGUI.DrawRect(offset.Remove(hitRect), selectedColor); // Tangents if (isCurrentlySelectedCurve && (!state.onlyShowHandlesOnSelection || (state.onlyShowHandlesOnSelection && isCurrentlySelectedKeyframe))) { Handles.color = selectedColor; if (k > 0 || state.loopInBounds) { Handles.DrawAAPolyLine(state.handleWidth, pos, inTangent); EditorGUI.DrawRect(offset.Remove(inTangentHitRect), selectedColor); } if (k < length - 1 || state.loopInBounds) { Handles.DrawAAPolyLine(state.handleWidth, pos, outTangent); EditorGUI.DrawRect(offset.Remove(outTangentHitrect), selectedColor); } } } } // Events if (state.editable) { // Keyframe move if (m_EditMode == EditMode.Moving && e.type == EventType.MouseDrag && isCurrentlySelectedCurve && isCurrentlySelectedKeyframe) { EditMoveKeyframe(animCurve, keys, k); } // Tangent editing if (m_EditMode == EditMode.TangentEdit && e.type == EventType.MouseDrag && isCurrentlySelectedCurve && isCurrentlySelectedKeyframe) { bool alreadyBroken = !(Mathf.Approximately(keys[k].inTangent, keys[k].outTangent) || (float.IsInfinity(keys[k].inTangent) && float.IsInfinity(keys[k].outTangent))); EditMoveTangent(animCurve, keys, k, m_TangentEditMode, e.shift || !(alreadyBroken || e.control)); } // Keyframe selection & mo menu if (e.type == EventType.MouseDown && rect.Contains(e.mousePosition)) { if (hitRect.Contains(e.mousePosition)) { if (e.button == 0) { SelectKeyframe(curve, k); m_EditMode = EditMode.Moving; e.Use(); } else if (e.button == 1) { // Keyframe context menu var menu = new GenericMenu(); menu.AddItem(new GUIContent("Delete Key"), false, (x) => { var action = (MenuAction)x; var curveValue = action.curve.animationCurveValue; action.curve.serializedObject.Update(); RemoveKeyframe(curveValue, action.index); m_SelectedKeyframeIndex = -1; SaveCurve(action.curve, curveValue); action.curve.serializedObject.ApplyModifiedProperties(); }, new MenuAction(curve, k)); menu.ShowAsContext(); e.Use(); } } } // Tangent selection & edit mode if (e.type == EventType.MouseDown && rect.Contains(e.mousePosition)) { if (inTangentHitRect.Contains(e.mousePosition) && (k > 0 || state.loopInBounds)) { SelectKeyframe(curve, k); m_EditMode = EditMode.TangentEdit; m_TangentEditMode = Tangent.In; e.Use(); } else if (outTangentHitrect.Contains(e.mousePosition) && (k < length - 1 || state.loopInBounds)) { SelectKeyframe(curve, k); m_EditMode = EditMode.TangentEdit; m_TangentEditMode = Tangent.Out; e.Use(); } } // Mouse up - clean up states if (e.rawType == EventType.MouseUp && m_EditMode != EditMode.None) { m_EditMode = EditMode.None; } // Set cursors { EditorGUIUtility.AddCursorRect(hitRect, MouseCursor.MoveArrow); if (k > 0 || state.loopInBounds) { EditorGUIUtility.AddCursorRect(inTangentHitRect, MouseCursor.RotateArrow); } if (k < length - 1 || state.loopInBounds) { EditorGUIUtility.AddCursorRect(outTangentHitrect, MouseCursor.RotateArrow); } } } } Handles.color = Color.white; SaveCurve(curve, animCurve); }
private void PaintClauses() { int removeClauseIndex = -1; int duplicateClauseIndex = -1; int copyClauseIndex = -1; bool forceRepaint = false; int clauseSize = this.spClauses.arraySize; for (int i = 0; i < clauseSize; ++i) { if (this.subEditors == null || i >= this.subEditors.Length || this.subEditors[i] == null) { continue; } bool repaint = this.editorSortableList.CaptureSortEvents(this.subEditors[i].handleDragRect, i); forceRepaint = repaint || forceRepaint; EditorGUILayout.BeginVertical(); Rect rectHeader = GUILayoutUtility.GetRect(GUIContent.none, CoreGUIStyles.GetToggleButtonNormalOn()); this.PaintDragHandle(i, rectHeader); EditorGUIUtility.AddCursorRect(this.subEditors[i].handleDragRect, MouseCursor.Pan); string name = (this.isExpanded[i].target ? "▾ " : "▸ ") + this.instance.clauses[i].description; GUIStyle style = (this.isExpanded[i].target ? CoreGUIStyles.GetToggleButtonMidOn() : CoreGUIStyles.GetToggleButtonMidOff() ); Rect rectDelete = new Rect( rectHeader.x + rectHeader.width - 25f, rectHeader.y, 25f, rectHeader.height ); Rect rectDuplicate = new Rect( rectDelete.x - 25f, rectHeader.y, 25f, rectHeader.height ); Rect rectCopy = new Rect( rectDuplicate.x - 25f, rectHeader.y, 25f, rectHeader.height ); Rect rectMain = new Rect( rectHeader.x + 25f, rectHeader.y, rectHeader.width - (25f * 4f), rectHeader.height ); if (GUI.Button(rectMain, name, style)) { this.ToggleExpand(i); } GUIContent gcCopy = ClausesUtilities.Get(ClausesUtilities.Icon.Copy); GUIContent gcDuplicate = ClausesUtilities.Get(ClausesUtilities.Icon.Duplicate); GUIContent gcDelete = ClausesUtilities.Get(ClausesUtilities.Icon.Delete); if (GUI.Button(rectCopy, gcCopy, CoreGUIStyles.GetButtonMid())) { copyClauseIndex = i; } if (GUI.Button(rectDuplicate, gcDuplicate, CoreGUIStyles.GetButtonMid())) { duplicateClauseIndex = i; } if (GUI.Button(rectDelete, gcDelete, CoreGUIStyles.GetButtonRight())) { if (EditorUtility.DisplayDialog(MSG_REMOVE_TITLE, MSG_REMOVE_DESCR, "Yes", "Cancel")) { removeClauseIndex = i; } } using (var group = new EditorGUILayout.FadeGroupScope(this.isExpanded[i].faded)) { if (group.visible) { EditorGUILayout.BeginVertical(CoreGUIStyles.GetBoxExpanded()); this.subEditors[i].OnClauseGUI(); EditorGUILayout.EndVertical(); } } EditorGUILayout.EndVertical(); if (UnityEngine.Event.current.type == EventType.Repaint) { this.subEditors[i].clauseRect = GUILayoutUtility.GetLastRect(); } this.editorSortableList.PaintDropPoints(this.subEditors[i].clauseRect, i, clauseSize); } if (copyClauseIndex >= 0) { Clause source = (Clause)this.subEditors[copyClauseIndex].target; GameObject copyInstance = EditorUtility.CreateGameObjectWithHideFlags( "Clause (Copy)", HideFlags.HideAndDontSave ); CLIPBOARD_CLAUSE = (Clause)copyInstance.AddComponent(source.GetType()); EditorUtility.CopySerialized(source, CLIPBOARD_CLAUSE); if (CLIPBOARD_CLAUSE.conditionsList != null) { IConditionsList conditionsListSource = CLIPBOARD_CLAUSE.conditionsList; IConditionsList conditionsListCopy = this.instance.gameObject.AddComponent <IConditionsList>(); EditorUtility.CopySerialized(conditionsListSource, conditionsListCopy); ConditionsEditor.DuplicateIConditionList(conditionsListSource, conditionsListCopy); SerializedObject soCopy = new SerializedObject(CLIPBOARD_CLAUSE); soCopy.FindProperty(ClauseEditor.PROP_CONDITIONSLIST).objectReferenceValue = conditionsListCopy; soCopy.ApplyModifiedPropertiesWithoutUndo(); soCopy.Update(); } } if (duplicateClauseIndex >= 0) { int srcIndex = duplicateClauseIndex; int dstIndex = duplicateClauseIndex + 1; Clause source = (Clause)this.subEditors[srcIndex].target; Clause copy = (Clause)this.instance.gameObject.AddComponent(source.GetType()); EditorUtility.CopySerialized(source, copy); if (copy.conditionsList != null) { IConditionsList conditionsListSource = copy.conditionsList; IConditionsList conditionsListCopy = this.instance.gameObject.AddComponent <IConditionsList>(); EditorUtility.CopySerialized(conditionsListSource, conditionsListCopy); ConditionsEditor.DuplicateIConditionList(conditionsListSource, conditionsListCopy); SerializedObject soCopy = new SerializedObject(copy); soCopy.FindProperty(ClauseEditor.PROP_CONDITIONSLIST).objectReferenceValue = conditionsListCopy; if (!Application.isPlaying) { EditorSceneManager.MarkSceneDirty(this.instance.gameObject.scene); } soCopy.ApplyModifiedPropertiesWithoutUndo(); soCopy.Update(); } this.spClauses.InsertArrayElementAtIndex(dstIndex); this.spClauses.GetArrayElementAtIndex(dstIndex).objectReferenceValue = copy; this.spClauses.serializedObject.ApplyModifiedPropertiesWithoutUndo(); this.spClauses.serializedObject.Update(); this.AddSubEditorElement(copy, dstIndex, true); } if (removeClauseIndex >= 0) { this.subEditors[removeClauseIndex].OnDestroyClause(); Clause rmClause = (Clause)this.spClauses .GetArrayElementAtIndex(removeClauseIndex).objectReferenceValue; this.spClauses.DeleteArrayElementAtIndex(removeClauseIndex); this.spClauses.RemoveFromObjectArrayAt(removeClauseIndex); DestroyImmediate(rmClause, true); if (!Application.isPlaying) { EditorSceneManager.MarkSceneDirty(this.instance.gameObject.scene); } } EditorSortableList.SwapIndexes swapIndexes = this.editorSortableList.GetSortIndexes(); if (swapIndexes != null) { this.spClauses.MoveArrayElement(swapIndexes.src, swapIndexes.dst); this.MoveSubEditorsElement(swapIndexes.src, swapIndexes.dst); if (!Application.isPlaying) { EditorSceneManager.MarkSceneDirty(this.instance.gameObject.scene); } } if (forceRepaint) { this.Repaint(); } }
private void PaintItems() { int itemsCount = this.spItems.arraySize; int removeIndex = -1; bool forceRepaint = false; GUIContent gcDelete = ClausesUtilities.Get(ClausesUtilities.Icon.Delete); for (int i = 0; i < itemsCount; ++i) { SerializedProperty spItem = this.spItems.GetArrayElementAtIndex(i); SerializedProperty spIOption = spItem.FindPropertyRelative(PROP_OPTION); SerializedProperty spIActions = spItem.FindPropertyRelative(PROP_ACTIONS); SerializedProperty spIConditions = spItem.FindPropertyRelative(PROP_CONDITIONS); Rect rectItem = GUILayoutUtility.GetRect(GUIContent.none, CoreGUIStyles.GetToggleButtonNormalOff()); Rect rectHandle = new Rect( rectItem.x, rectItem.y, 25f, rectItem.height ); Rect rectToggle = new Rect( rectHandle.x + rectHandle.width, rectHandle.y, 25f, rectHandle.height ); Rect rectDelete = new Rect( rectItem.x + (rectItem.width - 25f), rectToggle.y, 25f, rectToggle.height ); Rect rectCont = new Rect( rectToggle.x + rectToggle.width, rectToggle.y, rectItem.width - (rectHandle.width + rectToggle.width + rectDelete.width), rectToggle.height ); GUI.Label(rectHandle, "=", CoreGUIStyles.GetButtonLeft()); bool forceSortRepaint = this.sortableList.CaptureSortEvents(rectHandle, i); forceRepaint = forceSortRepaint || forceRepaint; EditorGUIUtility.AddCursorRect(rectHandle, MouseCursor.Pan); GUIContent gcToggle = null; if (spIOption.intValue == (int)Trigger.ItemOpts.Actions) { gcToggle = GC_ACTIONS; } if (spIOption.intValue == (int)Trigger.ItemOpts.Conditions) { gcToggle = GC_CONDITIONS; } if (GUI.Button(rectToggle, gcToggle, CoreGUIStyles.GetButtonMid())) { switch (spIOption.intValue) { case (int)Trigger.ItemOpts.Actions: spIOption.intValue = (int)Trigger.ItemOpts.Conditions; break; case (int)Trigger.ItemOpts.Conditions: spIOption.intValue = (int)Trigger.ItemOpts.Actions; break; } } GUI.Label(rectCont, string.Empty, CoreGUIStyles.GetButtonMid()); Rect rectField = new Rect( rectCont.x + 2f, rectCont.y + (rectCont.height / 2f - EditorGUIUtility.singleLineHeight / 2f), rectCont.width - 7f, EditorGUIUtility.singleLineHeight ); switch (spIOption.intValue) { case (int)Trigger.ItemOpts.Actions: EditorGUI.PropertyField(rectField, spIActions, GUIContent.none, true); break; case (int)Trigger.ItemOpts.Conditions: EditorGUI.PropertyField(rectField, spIConditions, GUIContent.none, true); break; } if (GUI.Button(rectDelete, gcDelete, CoreGUIStyles.GetButtonRight())) { removeIndex = i; } this.sortableList.PaintDropPoints(rectItem, i, itemsCount); } if (removeIndex != -1 && removeIndex < this.spItems.arraySize) { SerializedProperty spItem = this.spItems.GetArrayElementAtIndex(removeIndex); SerializedProperty spIOption = spItem.FindPropertyRelative(PROP_OPTION); SerializedProperty spIActions = spItem.FindPropertyRelative(PROP_ACTIONS); SerializedProperty spIConditions = spItem.FindPropertyRelative(PROP_CONDITIONS); UnityEngine.Object @object = null; switch (spIOption.intValue) { case (int)Trigger.ItemOpts.Actions: @object = spIActions.objectReferenceValue; break; case (int)Trigger.ItemOpts.Conditions: @object = spIConditions.objectReferenceValue; break; } this.spItems.DeleteArrayElementAtIndex(removeIndex); } EditorSortableList.SwapIndexes swapIndexes = this.sortableList.GetSortIndexes(); if (swapIndexes != null) { this.spItems.MoveArrayElement(swapIndexes.src, swapIndexes.dst); } if (forceRepaint) { this.Repaint(); } }
public void DrawCursor(Rect sliderArea) { EditorGUIUtility.AddCursorRect(GetResizeArea(sliderArea), MouseCursor.ResizeHorizontal); }
public static void ReorderableList(IList list, System.Action <int> GUICallback, UnityEngine.Object undoObject = null) { if (list.Count == 1) { GUICallback(0); return; } if (!pickedObjectList.ContainsKey(list)) { pickedObjectList[list] = null; } var e = Event.current; var lastRect = new Rect(); object picked = pickedObjectList[list]; GUILayout.BeginVertical(); for (int i = 0; i < list.Count; i++) { GUILayout.BeginVertical(); GUICallback(i); GUILayout.EndVertical(); GUI.color = Color.white; GUI.backgroundColor = Color.white; lastRect = GUILayoutUtility.GetLastRect(); EditorGUIUtility.AddCursorRect(lastRect, MouseCursor.MoveArrow); if (picked != null && picked == list[i]) { GUI.Box(lastRect, ""); } if (picked != null && lastRect.Contains(e.mousePosition) && picked != list[i]) { var markRect = new Rect(lastRect.x, lastRect.y - 2, lastRect.width, 2); if (list.IndexOf(picked) < i) { markRect.y = lastRect.yMax - 2; } GUI.Box(markRect, ""); if (e.type == EventType.MouseUp) { if (undoObject != null) { Undo.RecordObject(undoObject, "Reorder"); } list.Remove(picked); list.Insert(i, picked); pickedObjectList[list] = null; e.Use(); return; } } if (lastRect.Contains(e.mousePosition) && e.type == EventType.MouseDown) { pickedObjectList[list] = list[i]; } } GUILayout.EndVertical(); if (e.type == EventType.MouseUp) { pickedObjectList[list] = null; } }
public void BeginGUI() { if (!DTGUI.IsLayout) { CanvasRect = new Rect(0, 0, 0, 0); } if (EV.isMouse) { MousePosition = EV.mousePosition; } //Debug.Log(EV.type); switch (EV.type) { case EventType.MouseDrag: if (!IsMouseOverCanvas && !IsSelectionRectDrag && !IsModuleDrag) { IsWindowDrag = true; } if (!IsDragging) { if (IsMouseOverModule) { IsModuleDrag = true; } else { IsSelectionRectDrag = true; SelectionRectStart = ViewPortMousePosition; } } break; case EventType.Used: // dirty, but works IsWindowDrag = false; break; case EventType.MouseUp: IsModuleDrag = false; if (EV.button == 1) { UI.ContextMenu(); } break; case EventType.MouseDown: if (EV.button == 1) { if (IsMouseOverModule && !Sel.SelectedModules.Contains(MouseOverModule)) { Sel.Select(MouseOverModule); FocusSelection(); } } else if (EV.button == 2) { IsCanvasDrag = true; } break; case EventType.KeyDown: if (EV.keyCode == KeyCode.Space) { IsCanvasDrag = true; } break; case EventType.KeyUp: IsCanvasDrag = false; break; } if (EV.type != EventType.Layout) { IsMouseOverModule = false; } if (IsCanvasDrag) { EditorGUIUtility.AddCursorRect(ViewPort, MouseCursor.Pan); } }
private void DrawNodeWindow(int id) { if (Event.current.type == EventType.Layout) { return; } var node = targetGraph.AllNodes[id]; if (EventType.MouseDown == currentEvent.type || EventType.MouseUp == currentEvent.type || EventType.MouseDrag == currentEvent.type || EventType.MouseMove == currentEvent.type) { selectedWindow = id; EditorUtility.SetDirty(node); } if (!node.lastDrawRect.Overlaps(screenRect)) { return; } var settingsRect = new Rect(node.lastDrawRect.width - 20, 5, 20, 20); var iconRect = new Rect(0, 0, 18, 18); if (GUI.Button(settingsRect, "", BehaviourGUIStyles.Instance.settingsStyle)) { rightClickedNode = node; BasicNodeMenu.ShowAsContext(); } var originalColour = GUI.color; GUI.color = new Color(1.0f, 1.0f, 1.0f, 0.65f); EditorGUI.LabelField(iconRect, new GUIContent(AssetPreview.GetMiniThumbnail(node))); GUI.color = originalColour; if (currentEvent.type == EventType.MouseDown) { if (iconRect.Contains(currentEvent.mousePosition)) { if (currentEvent.button == 0) { if (currentEvent.clickCount == 1) { rightClickedNode = node; PingSourceCallback(); } else { rightClickedNode = node; OpenScriptCallback(); } currentEvent.Use(); } } } var serializedObject = SerializedObjectPool.Grab(node); //Undo.RecordObject (node, "Edit Node"); float originalLabelWidth = EditorGUIUtility.labelWidth; EditorGUIUtility.labelWidth = node.lastDrawRect.width / 2; serializedObject.FindProperty("Position").vector2Value = node.Position; //EditorGUI.BeginChangeCheck (); //string newName = EditorGUILayout.DelayedTextField (node.name); //if (EditorGUI.EndChangeCheck ()) //{ // RenameAction (node, newName); //} var contentRect = BehaviourGraphResources.Instance.NodeStyle.padding.Remove(node.lastDrawRect); node.DrawGUI(serializedObject, new Rect(contentRect.x - node.Position.x - dragging_Position.x, contentRect.y - node.Position.y - dragging_Position.y, contentRect.width, contentRect.height)); serializedObject.ApplyModifiedProperties(); if (currentEvent.type == EventType.MouseDown) { if (currentEvent.button == 1) { rightClickedNode = node; BasicNodeMenu.ShowAsContext(); } } EditorGUIUtility.labelWidth = originalLabelWidth; #if HOVER_EFFECTS if (connection_Start == null && connection_End == null) { EditorGUIUtility.AddCursorRect(new Rect(node.lastDrawRect.x - node.Position.x - dragging_Position.x, node.lastDrawRect.y - node.Position.y - dragging_Position.y, node.lastDrawRect.width, node.lastDrawRect.height), MouseCursor.MoveArrow); } #endif if (currentEvent.button != 2) { GUI.DragWindow(); } }