private void DrawNodeLinkButton(int controlId, Vector3 position, Quaternion rotation, float size) { Handles.CubeCap(controlId, position, rotation, size); }
public static void CubeCap(int controlID, Vector3 position, Quaternion rotation, float size) { Handles.CubeCap(controlID, position, rotation, size); }
void OnSceneGUI() { if (!pathArea) { return; } CheckNodes(ref pathArea.waypoints); Event e = Event.current; if (editMode) { HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)); if (e.type == EventType.MouseDown && e.button == 0 && e.shift) { Ray worldRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); RaycastHit hitInfo; if (Physics.Raycast(worldRay, out hitInfo)) { CreateNode(pathArea, hitInfo.point); EditorUtility.SetDirty(pathArea); } } else if (e.type == EventType.MouseDown && e.button == 0 && e.control && currentNode) { Ray worldRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); RaycastHit hitInfo; if (Physics.Raycast(worldRay, out hitInfo)) { CreatePatrolPoint(pathArea, hitInfo.point); EditorUtility.SetDirty(pathArea); } } } else { HandleUtility.AddDefaultControl(GUIUtility.GetControlID(FocusType.Passive)); } if (editMode) { Handles.color = Color.white; } else { Handles.color = new Color(1, 1, 1, 0.2f); } if (pathArea.waypoints.Count > 0) { var node0 = pathArea.waypoints[0]; foreach (vWaypoint node in pathArea.waypoints) { if (node != null) { if (editMode && currentNode != null) { Handles.color = node.isValid ? (currentNode.Equals(node) ? Color.green : Color.white) : Color.red; } if (!editMode) { Handles.SphereCap(0, node.transform.position, Quaternion.identity, 0.25f); } else if (Handles.Button(node.transform.position, Quaternion.identity, currentNode ? (currentNode == node ? .5f : 0.25f) : .25f, currentNode ? (currentNode == node ? .5f : 0.25f) : .25f, Handles.SphereCap)) { indexOfWaypoint = pathArea.waypoints.IndexOf(node); currentNode = node; indexOfPatrolPoint = 0; Selection.activeGameObject = node.gameObject; Repaint(); } if (editMode) { Handles.color = new Color(0, 0, 1, .2f); } Handles.DrawLine(node0.transform.position, node.transform.position); node0 = node; var index = pathArea.waypoints.IndexOf(node) + 1; if (currentNode == null || !currentNode.Equals(node)) { Handles.Label(node.transform.position, new GUIContent("WP-" + index.ToString("00"))); if (node.subPoints != null && node.subPoints.Count > 0) { var patrolPoint0 = node.subPoints[0]; Handles.DrawLine(node.transform.position, patrolPoint0.position); foreach (vPoint patrolPoint in node.subPoints) { if (patrolPoint != null) { Handles.DrawLine(patrolPoint0.transform.position, patrolPoint.position); patrolPoint0 = patrolPoint; Handles.CubeCap(0, patrolPoint.transform.position, Quaternion.identity, 0.15f); } } } } } } } Handles.color = Color.white; if (currentNode && editMode) { Handles.color = Color.green; Handles.DrawWireDisc(currentNode.transform.position, Vector3.up, currentNode.areaRadius); e = Event.current; if (e.type == EventType.MouseDown && e.button == 1 && e.shift) { Ray worldRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); RaycastHit hitInfo; if (Physics.Raycast(worldRay, out hitInfo)) { currentNode.transform.position = hitInfo.point; EditorUtility.SetDirty(pathArea); } } if (currentNode.subPoints == null) { currentNode.subPoints = new List <vPoint>(); } if (currentNode.subPoints.Count > 0) { var patrolPoint0 = currentNode.subPoints[0]; Handles.color = Color.cyan; Handles.DrawLine(currentNode.transform.position, patrolPoint0.position); foreach (vPoint patrolPoint in currentNode.subPoints) { Handles.color = Color.cyan; Handles.DrawLine(patrolPoint0.transform.position, patrolPoint.position); patrolPoint0 = patrolPoint; var index = currentNode.subPoints.IndexOf(patrolPoint); Handles.color = patrolPoint.isValid ? Color.cyan : Color.red; if (patrolPoint != null) { if (Handles.Button(patrolPoint.transform.position, Quaternion.Euler(0, 0, 0), .25f, .25f, Handles.CubeCap)) { indexOfPatrolPoint = currentNode.subPoints.IndexOf(patrolPoint); Selection.activeGameObject = patrolPoint.gameObject; Repaint(); } Handles.color = new Color(1, 1, 1, 0.1f); Handles.Label(patrolPoint.position, new GUIContent("P-" + (index + 1).ToString("00"))); } } Handles.color = Color.green; if (currentNode.subPoints.Count > 0 && indexOfPatrolPoint < currentNode.subPoints.Count) { EditorGUI.BeginChangeCheck(); Handles.DrawWireDisc(currentNode.subPoints[indexOfPatrolPoint].transform.position, Vector3.up, currentNode.subPoints[indexOfPatrolPoint].areaRadius); if (e.type == EventType.MouseDown && e.button == 1 && e.control && currentNode) { Ray worldRay = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); RaycastHit hitInfo; if (Physics.Raycast(worldRay, out hitInfo)) { currentNode.subPoints[indexOfPatrolPoint].position = hitInfo.point; EditorUtility.SetDirty(pathArea); } } } } } }
private void MouseInput() { int controlID = GUIUtility.GetControlID(FocusType.Passive); EventType eventType = Event.current.GetTypeForControl(controlID); Event e = Event.current; float mouseScale = NPVoxHandles.GetMouseScale(SceneView.currentDrawingSceneView.camera); Ray r = Camera.current.ScreenPointToRay(new Vector3(Event.current.mousePosition.x * mouseScale, -Event.current.mousePosition.y * mouseScale + Camera.current.pixelHeight)); bool bShiftHeld = e.shift; bool bAltHeld = e.alt; bool bCtrlHeld = e.control; if (Event.current.mousePosition.y < TOOLBAR_HEIGHT) { // allow to click the buttons always return; } // if (viewModel.CurrentTool == GNBlockMapEditorVM.Tool.ERASE) if (inputController.IsErasingActive()) { Handles.color = new Color(128, 0, 0, 0.25f); Handles.CubeCap(controlID, viewModel.CurrentCell, Quaternion.identity, viewModel.CellSize); } if (inputController.IsPrefabNavigationActive()) { Handles.color = new Color(128, 128, 0, 0.05f); Handles.CubeCap(controlID, viewModel.CurrentCell, Quaternion.identity, viewModel.CellSize); } if (inputController.IsPickingActive()) { Handles.color = new Color(128, 128, 0, 0.25f); Handles.CubeCap(controlID, viewModel.CurrentCell, Quaternion.identity, viewModel.CellSize); } if (inputController.IsRotationActive()) { Handles.color = new Color(0, 128, 0, 0.05f); Handles.CubeCap(controlID, viewModel.CurrentCell, Quaternion.identity, viewModel.CellSize); } switch (eventType) { case EventType.Layout: if (inputController.TakeEvents()) { HandleUtility.AddControl( controlID, HandleUtility.DistanceToCircle(r.origin, 10f) ); } break; case EventType.MouseDown: if (HandleUtility.nearestControl == controlID && e.button == 0) { GUIUtility.hotControl = controlID; if (inputController.MouseDown(e)) { e.Use(); SceneView.RepaintAll(); } } break; case EventType.MouseUp: if (GUIUtility.hotControl == controlID) { GUI.changed = true; GUIUtility.hotControl = 0; e.Use(); } break; case EventType.MouseDrag: if (GUIUtility.hotControl == controlID) { if (inputController.MouseDrag(RayCast(r))) { e.Use(); SceneView.RepaintAll(); } } break; case EventType.ScrollWheel: if (inputController.WheelScrolled(e.delta, bShiftHeld, bAltHeld, bCtrlHeld)) { e.Use(); if (inputController.MouseMoved(RayCast(r))) { } SceneView.RepaintAll(); } break; case EventType.MouseMove: if (inputController.MouseMoved(RayCast(r))) { e.Use(); SceneView.RepaintAll(); } break; } }
void OnSceneGUI() { BezierPath path = (BezierPath)target; if (Event.current.type == EventType.MouseDown) { // record positions pointPos = selectedPoint.p1; handlePos = selectedPoint.h1; } if (Event.current.type == EventType.MouseUp) { if (selectedPoint.p1 != pointPos || selectedPoint.h1 != handlePos) { // put them back, register undo Vector3 newPos = selectedPoint.p1; Vector3 newHandle = selectedPoint.h1; selectedPoint.p1 = pointPos; selectedPoint.h1 = handlePos; Undo.RegisterUndo(path, "moving point"); selectedPoint.p1 = newPos; selectedPoint.h1 = newHandle; EditorUtility.SetDirty(path); } } bool needCreatePoint = false; bool needDeletePoint = false; if (selectedPoint != null && Event.current.type != EventType.Repaint) { // add + and - buttons Handles.BeginGUI(); Vector2 screenpos = HandleUtility.WorldToGUIPoint(selectedPoint.p1); // inverse y //screenpos.y = Screen.height - screenpos.y; if (GUI.Button(new Rect(screenpos.x - 10 + 20, screenpos.y - 20, 20, 20), "+")) { needCreatePoint = true; } if (GUI.Button(new Rect(screenpos.x - 10 - 20, screenpos.y - 20, 20, 20), "-")) { needDeletePoint = true; } Handles.EndGUI(); } // disable transform tool if selected if (Selection.activeGameObject == path.gameObject) { Tools.current = Tool.None; if (selectedPoint == null && path.points.Count > 0) { selectedPoint = path.points[0]; } } // draw the handles for the points foreach (BezierPath.PathPoint point in path.points) { if (point == selectedPoint) { //if (GUI.changed) // EditorUtility.SetDirty(target); point.p1 = Handles.PositionHandle(point.p1, Quaternion.identity); point.h1 = Handles.PositionHandle(point.h1 + point.p1, Quaternion.identity) - point.p1; Handles.CubeCap(0, point.p1, Quaternion.identity, 1); Handles.CubeCap(0, point.h1 + point.p1, Quaternion.identity, 0.5f); } else { // draw button float size = 1;//HandleUtility.GetHandleSize(point.p1) / 3; if (Handles.Button(point.p1, Quaternion.identity, 1, size, Handles.CubeCap)) { selectedPoint = point; } } } Handles.color = path.lineColor; // draw the lines for (int i = 0; i < path.points.Count - 1; i++) { // draw line from point i to point i+1 path.points[i].bezier.p1 = path.points[i].p1; path.points[i].bezier.h1 = path.points[i].h1; path.points[i].bezier.p2 = path.points[i + 1].p1; path.points[i].bezier.h2 = -path.points[i + 1].h1; // negative of this handle Vector3 oldPos = path.points[i].bezier.GetPointAtTime(0); for (float t = 0; t < 1.01; t += 0.1f) { Vector3 newPos = path.points[i].bezier.GetPointAtTime(t); Handles.DrawLine(oldPos, newPos); oldPos = newPos; } } if (selectedPoint != null && Event.current.type == EventType.Repaint) { // add + and - buttons Handles.BeginGUI(); Vector2 screenpos = HandleUtility.WorldToGUIPoint(selectedPoint.p1); // inverse y //screenpos.y = Screen.height - screenpos.y; if (GUI.Button(new Rect(screenpos.x - 10 + 20, screenpos.y - 20, 20, 20), "+")) { needCreatePoint = true; } if (GUI.Button(new Rect(screenpos.x - 10 - 20, screenpos.y - 20, 20, 20), "-")) { needDeletePoint = true; } Handles.EndGUI(); } if (needCreatePoint) { addPoint(path, selectedPoint); } if (needDeletePoint) { deletePoint(path, selectedPoint); } if (GUI.changed) { EditorUtility.SetDirty(target); } }
public static bool ScaleSlider(float scale, Vector3 position, Vector3 direction, Quaternion rotation, float length, float size, float snap, out float delta) { int id = GUIUtility.GetControlID("ScaleSliderHash".GetHashCode(), FocusType.Keyboard); float newScale = scale; Event current = Event.current; switch (current.GetTypeForControl(id)) { case EventType.MouseDown: if ((HandleUtility.nearestControl == id && current.button == 0) || (GUIUtility.keyboardControl == id && current.button == 2)) { GUIUtility.keyboardControl = id; GUIUtility.hotControl = id; s_CurrentMousePosition = (s_StartMousePosition = current.mousePosition); s_StartScale = scale; current.Use(); EditorGUIUtility.SetWantsMouseJumping(1); } break; case EventType.MouseUp: if (GUIUtility.hotControl == id && (current.button == 0 || current.button == 2)) { GUIUtility.hotControl = 0; current.Use(); EditorGUIUtility.SetWantsMouseJumping(0); } break; case EventType.MouseDrag: if (GUIUtility.hotControl == id) { s_CurrentMousePosition += current.delta; float num = 1f + HandleUtility.CalcLineTranslation(s_StartMousePosition, s_CurrentMousePosition, position, direction) * 0.1f; num = Handles.SnapValue(num, snap); newScale = s_StartScale * num; GUI.changed = true; current.Use(); } break; case EventType.Repaint: { Color color = Color.white; if (id == GUIUtility.keyboardControl) { color = Handles.color; Handles.color = Handles.selectedColor; } //float num2 = size; //if (GUIUtility.hotControl == id) //{ // num2 = size * scale / s_StartScale; //} Handles.CubeCap(id, position + direction * length, rotation, HandleUtility.GetHandleSize(position) * size); Handles.DrawLine(position, position + direction * length); if (id == GUIUtility.keyboardControl) { Handles.color = color; } break; } case EventType.Layout: HandleUtility.AddControl(id, HandleUtility.DistanceToLine(position, position + direction * length)); HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(position + direction * length, size)); break; } delta = newScale - scale; return(scale != newScale); }
public void OnSceneGUI() { Undo.RecordObject(target, "Move Shape Points"); MegaShape shape = (MegaShape)target; float ksize = shape.KnotSize * 0.01f; float ringratio = 1.3f; float borderratio = 1.15f; float knotsize = ksize; //float ringsize = knotsize1.1f; float handlesize = knotsize * 0.75f; //float outdiscsize = ksize * 1.0f * 0.5f; Handles.matrix = shape.transform.localToWorldMatrix; bool recalc = false; Vector3 dragplane = Vector3.one; Vector3 camfwd = Camera.current.transform.forward; if (Mathf.Abs(camfwd.x) > Mathf.Abs(camfwd.y)) { if (Mathf.Abs(camfwd.x) > Mathf.Abs(camfwd.z)) { dragplane.x = 0.0f; } else { dragplane.z = 0.0f; } } else { if (Mathf.Abs(camfwd.y) > Mathf.Abs(camfwd.z)) { dragplane.y = 0.0f; } else { dragplane.z = 0.0f; } } //Debug.Log("Dragplane " + dragplane); Color nocol = new Color(0, 0, 0, 0); for (int s = 0; s < shape.splines.Count; s++) { for (int p = 0; p < shape.splines[s].knots.Count; p++) { Vector3 pp = shape.transform.TransformPoint(shape.splines[s].knots[p].p); Vector3 normal = Camera.current.transform.forward; if (shape.drawKnots) //&& recalc == false ) { pm = shape.splines[s].knots[p].p; Handles.color = Color.black; Handles.color = shape.VecCol; //Vector3 normal = (pp - Camera.current.transform.position).normalized; Handles.DrawSolidDisc(pp, normal, knotsize * borderratio); //ksize * 0.55f); if (p == selected) { Handles.color = Color.white; Handles.Label(pm, " Selected\n" + pm.ToString("0.000")); } else { Handles.color = shape.KnotCol; Handles.Label(pm, " " + p); } //if ( p == selected ) //shape.splines[s].knots[p].p = Handles.PositionHandle(pm, Quaternion.identity); //else //{ Handles.color = shape.KnotCol; Handles.DrawSolidDisc(pp, normal, knotsize); //shape.splines[s].knots[p].p = Handles.FreeMoveHandle(pm, Quaternion.identity, ksize, Vector3.zero, Handles.SphereCap); //CubeCap); Handles.color = nocol; //shape.VecCol; Vector3 newp = Handles.FreeMoveHandle(pm, Quaternion.identity, knotsize * ringratio, Vector3.zero, Handles.CircleCap); //SphereCap); //CubeCap); shape.splines[s].knots[p].p += Vector3.Scale(newp - pm, dragplane); //if ( shape.splines[s].knots[p].p != pm ) //selected = p; //} delta = shape.splines[s].knots[p].p - pm; shape.splines[s].knots[p].invec += delta; shape.splines[s].knots[p].outvec += delta; if (shape.splines[s].knots[p].p != pm) { selected = p; recalc = true; } pm = shape.transform.TransformPoint(shape.splines[s].knots[p].p); //Handles.CubeCap(0, pm, Quaternion.identity, shape.KnotSize); } if (shape.drawHandles) //&& recalc == false ) { Handles.color = shape.VecCol; pm = shape.transform.TransformPoint(shape.splines[s].knots[p].p); Vector3 ip = shape.transform.TransformPoint(shape.splines[s].knots[p].invec); Vector3 op = shape.transform.TransformPoint(shape.splines[s].knots[p].outvec); Handles.DrawLine(pm, shape.transform.TransformPoint(shape.splines[s].knots[p].invec)); Handles.DrawLine(pm, shape.transform.TransformPoint(shape.splines[s].knots[p].outvec)); //Handles.color = Color.black; //Vector3 normal = (op - Camera.current.transform.position).normalized; Handles.DrawSolidDisc(op, normal, handlesize * borderratio); //ksize * 0.55f * ringratio); //normal = Camera.current.transform.forward; //(ip - Camera.current.transform.position).normalized; Handles.DrawSolidDisc(ip, normal, handlesize * borderratio); //ksize * 0.55f * ringratio); Handles.color = shape.HandleCol; //Handles.DrawSolidDisc(op, normal, ksize * 0.5f * ringratio); //Handles.DrawSolidDisc(ip, normal, ksize * 0.5f * ringratio); Handles.DrawSolidDisc(op, normal, handlesize); Handles.DrawSolidDisc(ip, normal, handlesize); //shape.splines[s].knots[p].invec = Handles.PositionHandle(shape.splines[s].knots[p].invec, Quaternion.identity); //shape.hsize); //shape.splines[s].knots[p].outvec = Handles.PositionHandle(shape.splines[s].knots[p].outvec, Quaternion.identity); //shape.hsize); Vector3 invec = shape.splines[s].knots[p].invec; //if ( p == selected ) //invec = Handles.PositionHandle(shape.splines[s].knots[p].invec, Quaternion.identity); //shape.hsize); //else Handles.color = nocol; Vector3 newinvec = Handles.FreeMoveHandle(shape.splines[s].knots[p].invec, Quaternion.identity, handlesize * ringratio, Vector3.zero, Handles.CircleCap); //SphereCap); //CubeCap); invec += Vector3.Scale(newinvec - invec, dragplane); //Debug.Log("sel " + selected + " new " + invec.ToString("0.0000") + " old " + shape.splines[s].knots[p].invec.ToString("0.0000")); if (invec != shape.splines[s].knots[p].invec) { if (shape.lockhandles) { Vector3 d = invec - shape.splines[s].knots[p].invec; shape.splines[s].knots[p].outvec -= d; } shape.splines[s].knots[p].invec = invec; selected = p; recalc = true; } Vector3 outvec = shape.splines[s].knots[p].outvec; // = Handles.PositionHandle(shape.splines[s].knots[p].outvec, Quaternion.identity); //shape.hsize); //if ( p == selected ) //outvec = Handles.PositionHandle(shape.splines[s].knots[p].outvec, Quaternion.identity); //shape.hsize); //else Vector3 newoutvec = Handles.FreeMoveHandle(shape.splines[s].knots[p].outvec, Quaternion.identity, handlesize * ringratio, Vector3.zero, Handles.CircleCap); //SphereCap); //CubeCap); outvec += Vector3.Scale(newoutvec - outvec, dragplane); if (outvec != shape.splines[s].knots[p].outvec) { if (shape.lockhandles) { Vector3 d = outvec - shape.splines[s].knots[p].outvec; shape.splines[s].knots[p].invec -= d; } shape.splines[s].knots[p].outvec = outvec; selected = p; recalc = true; } Vector3 hp = shape.transform.TransformPoint(shape.splines[s].knots[p].invec); //Handles.CubeCap(0, hp, Quaternion.identity, shape.KnotSize); if (selected == p) { Handles.Label(hp, " " + p); } hp = shape.transform.TransformPoint(shape.splines[s].knots[p].outvec); //Handles.CubeCap(0, hp, Quaternion.identity, shape.KnotSize); if (selected == p) { Handles.Label(hp, " " + p); } } // Draw nearest point (use for adding knot) //CursorPos = Handles.PositionHandle(CursorPos, Quaternion.identity); #if false if (shape.drawKnots) { pm = shape.splines[s].knots[p].p; if (p == selected) { Handles.color = Color.white; Handles.Label(pm, " Selected\n" + pm.ToString("0.000")); } else { Handles.color = shape.KnotCol; Handles.Label(pm, " " + p); } //if ( p == selected ) shape.splines[s].knots[p].p = Handles.PositionHandle(pm, Quaternion.identity); //else //{ //shape.splines[s].knots[p].p = Handles.FreeMoveHandle(pm, Quaternion.identity, shape.KnotSize, Vector3.zero, Handles.CubeCap); //if ( shape.splines[s].knots[p].p != pm ) //selected = p; //} delta = shape.splines[s].knots[p].p - pm; shape.splines[s].knots[p].invec += delta; shape.splines[s].knots[p].outvec += delta; if (shape.splines[s].knots[p].p != pm) { selected = p; recalc = true; } pm = shape.transform.TransformPoint(shape.splines[s].knots[p].p); Handles.CubeCap(0, pm, Quaternion.identity, shape.KnotSize); } #endif } } if (recalc) { shape.CalcLength(10); shape.BuildMesh(); } Handles.matrix = Matrix4x4.identity; }
void OnSceneGUI() { //Draw Connection Vector3 connection = Target.ComputeConnectionInWorldSpace(); Handles.color = Color.magenta; Handles.SphereCap(0, connection, Quaternion.identity, 1 / 100f); Handles.Label(connection, "Connection"); //Draw Axes Quaternion rotation = Quaternion.identity; if (Application.isPlaying) { if (Target.transform.parent != null) { rotation = Target.transform.parent.rotation; } rotation *= new Quaternion(Target.RRX, Target.RRY, Target.RRZ, Target.RRW); } else { rotation = Target.transform.rotation; } if (Target.XMotion.State == JointState.Free) { Handles.color = new Color(1f, 0f, 0f, 0.2f); Vector3 scale = Vector3.zero; if (Target.transform.root != Target.transform) { scale = Target.transform.parent.lossyScale; } if (Target.Type == JointType.Prismatic) { Vector3 pivot = connection - Vector3.Scale(rotation * Quaternion.Euler(Target.AxisOrientation) * Target.GetCurrentValue(), scale); Vector3 A = pivot + Vector3.Scale(Target.XMotion.GetLowerLimit() * (rotation * Target.ComputeXAxis()), scale); Vector3 B = pivot + Vector3.Scale(Target.XMotion.GetUpperLimit() * (rotation * Target.ComputeXAxis()), scale); Handles.DrawLine(connection, A); Handles.CubeCap(0, A, rotation, 0.025f); Handles.DrawLine(connection, B); Handles.CubeCap(0, B, rotation, 0.025f); } else { float lowerLimit = Mathf.Rad2Deg * Target.XMotion.GetLowerLimit(); float upperLimit = Mathf.Rad2Deg * Target.XMotion.GetUpperLimit(); Handles.DrawSolidArc(connection, rotation * Target.ComputeXAxis(), Quaternion.AngleAxis(lowerLimit, rotation * Target.ComputeXAxis()) * rotation * Target.ComputeZAxis(), upperLimit - lowerLimit, 0.075f); } Handles.color = Color.red; } else { Handles.color = Color.grey; } Handles.ArrowCap(0, connection, rotation * Quaternion.LookRotation(Target.ComputeXAxis()), 0.1f); if (Target.YMotion.State == JointState.Free) { Handles.color = new Color(0f, 1f, 0f, 0.2f); Vector3 scale = Vector3.zero; if (Target.transform.root != Target.transform) { scale = Target.transform.parent.lossyScale; } if (Target.Type == JointType.Prismatic) { Vector3 pivot = connection - Vector3.Scale(rotation * Quaternion.Euler(Target.AxisOrientation) * Target.GetCurrentValue(), scale); Vector3 A = pivot + Vector3.Scale(Target.YMotion.GetLowerLimit() * (rotation * Target.ComputeYAxis()), scale); Vector3 B = pivot + Vector3.Scale(Target.YMotion.GetLowerLimit() * (rotation * Target.ComputeYAxis()), scale); Handles.DrawLine(connection, A); Handles.CubeCap(0, A, rotation, 0.025f); Handles.DrawLine(connection, B); Handles.CubeCap(0, B, rotation, 0.025f); } else { float lowerLimit = Mathf.Rad2Deg * Target.YMotion.GetLowerLimit(); float upperLimit = Mathf.Rad2Deg * Target.YMotion.GetUpperLimit(); Handles.DrawSolidArc(connection, rotation * Target.ComputeYAxis(), Quaternion.AngleAxis(lowerLimit, rotation * Target.ComputeYAxis()) * rotation * Target.ComputeXAxis(), upperLimit - lowerLimit, 0.075f); } Handles.color = Color.green; } else { Handles.color = Color.grey; } Handles.ArrowCap(0, connection, rotation * Quaternion.LookRotation(Target.ComputeYAxis()), 0.1f); if (Target.ZMotion.State == JointState.Free) { Handles.color = new Color(0f, 0f, 1f, 0.2f); Vector3 scale = Vector3.zero; if (Target.transform.root != Target.transform) { scale = Target.transform.parent.lossyScale; } if (Target.Type == JointType.Prismatic) { Vector3 pivot = connection - Vector3.Scale(rotation * Quaternion.Euler(Target.AxisOrientation) * Target.GetCurrentValue(), scale); Vector3 A = pivot + Vector3.Scale(Target.ZMotion.GetLowerLimit() * (rotation * Target.ComputeZAxis()), scale); Vector3 B = pivot + Vector3.Scale(Target.ZMotion.GetUpperLimit() * (rotation * Target.ComputeZAxis()), scale); Handles.DrawLine(connection, A); Handles.CubeCap(0, A, rotation, 0.025f); Handles.DrawLine(connection, B); Handles.CubeCap(0, B, rotation, 0.025f); } else { float lowerLimit = Mathf.Rad2Deg * Target.ZMotion.GetLowerLimit(); float upperLimit = Mathf.Rad2Deg * Target.ZMotion.GetUpperLimit(); Handles.DrawSolidArc(connection, rotation * Target.ComputeZAxis(), Quaternion.AngleAxis(lowerLimit, rotation * Target.ComputeZAxis()) * rotation * Target.ComputeYAxis(), upperLimit - lowerLimit, 0.075f); } Handles.color = Color.blue; } else { Handles.color = Color.grey; } Handles.ArrowCap(0, connection, rotation * Quaternion.LookRotation(Target.ComputeZAxis()), 0.1f); }
public System.Func <NPVoxISceneEditable, bool> DrawSceneTool(NPVoxToUnity npVoxToUnity, Transform transform, int tool) { if (Input == null) { return(null); } NPVoxModel model = ((NPVoxIModelFactory)Input).GetProduct() as NPVoxModel; if (!model) { return(null); } if (!(PreviousFrame is NPVoxIModelFactory)) { return(null); } if (SocketOffsets.Length < 4 || ControlPointOffsets.Length < 4) { ResetSceneTools(); } NPVoxToUnity sourceN2U = new NPVoxToUnity(((NPVoxIModelFactory)PreviousFrame).GetProduct(), npVoxToUnity.VoxeSize); NPVoxSocket sourceSocket1 = ((NPVoxIModelFactory)PreviousFrame).GetProduct().GetSocketByName(SocketName1); NPVoxSocket sourceSocket2 = ((NPVoxIModelFactory)PreviousFrame).GetProduct().GetSocketByName(SocketName2); NPVoxModel targetModel = model; if (TargetFrame is NPVoxIModelFactory) { targetModel = ((NPVoxIModelFactory)TargetFrame).GetProduct() as NPVoxModel; } NPVoxToUnity targetN2U = new NPVoxToUnity(targetModel, npVoxToUnity.VoxeSize); NPVoxSocket targetSocket1 = targetModel.GetSocketByName(SocketName1); NPVoxSocket targetSocket2 = targetModel.GetSocketByName(SocketName2); if (targetSocket1.IsInvalid()) { Debug.LogWarning("SocketName1 not found in targetModel"); return(null); } if (targetSocket2.IsInvalid()) { Debug.LogWarning("SocketName2 not found in targetModel"); return(null); } NPVoxSocket[] sockets = new NPVoxSocket[4]; sockets[INDEX_SOURCE_1] = sourceSocket1; sockets[INDEX_SOURCE_2] = sourceSocket2; sockets[INDEX_TARGET_1] = targetSocket1; sockets[INDEX_TARGET_2] = targetSocket2; NPVoxToUnity[] n2u = new NPVoxToUnity[4]; n2u[INDEX_SOURCE_1] = sourceN2U; n2u[INDEX_SOURCE_2] = sourceN2U; n2u[INDEX_TARGET_1] = targetN2U; n2u[INDEX_TARGET_2] = targetN2U; NPVoxToUnity n = n2u[currentEditedSocket]; Vector3 pos = n.ToUnityPosition(sockets[currentEditedSocket].Anchor); if (tool == 0) { if (Event.current.type == EventType.MouseDown) { currentEditedSocket = (currentEditedSocket + 1) % 4; } switch (currentEditedSocket) { case INDEX_TARGET_1: Handles.color = Color.green; break; case INDEX_TARGET_2: Handles.color = Color.green; break; case INDEX_SOURCE_1: Handles.color = Color.yellow; break; case INDEX_SOURCE_2: Handles.color = Color.yellow; break; } Handles.CubeCap(0, pos, Quaternion.identity, 0.5f); } // offset Vector3 offset = n.ToUnityDirection(SocketOffsets[currentEditedSocket]); if (tool == 1) { offset = n.ToSaveVoxDirection(Handles.PositionHandle(pos + offset, Quaternion.identity) - pos); if (offset != SocketOffsets[currentEditedSocket]) { return((NPVoxISceneEditable t) => { (t as NPVoxTrailGenerator).SocketOffsets[currentEditedSocket] = offset; return true; }); } } Vector3 controlOffset = n.ToUnityDirection(ControlPointOffsets[currentEditedSocket]); // Control Point if (tool == 2) { controlOffset = n.ToSaveVoxDirection(Handles.PositionHandle(pos + offset + controlOffset, Quaternion.identity) - pos - offset); if (controlOffset != ControlPointOffsets[currentEditedSocket]) { return((NPVoxISceneEditable t) => { (t as NPVoxTrailGenerator).ControlPointOffsets[currentEditedSocket] = controlOffset; return true; }); } } return(null); }
/// <summary> /// Draw the cool lines in the editor /// </summary> public void OnSceneGUI() { if (drawSolver == false) { return; } if (IK.ValidateChains() == false) { return; } if (IK.HR == null) { IK.AssignLimbs(); } Handles.color = new Color(0.6f, 1f, 0.5f, 1f); //we need a vibrant screaming color //right upperbody for (int i = 0; i < IK.rightUpperbody.joints.Count - 1; i++) { Handles.SphereCap(0, IK.rightUpperbody.joints[i].transform.position, Quaternion.identity, 0.03f); Handles.DrawLine(IK.rightUpperbody.joints[i].transform.position, IK.rightUpperbody.joints[i + 1].transform.position); } //left upperbody for (int i = 0; i < IK.leftUpperbody.joints.Count - 1; i++) { Handles.SphereCap(0, IK.leftUpperbody.joints[i].transform.position, Quaternion.identity, 0.03f); Handles.DrawLine(IK.leftUpperbody.joints[i].transform.position, IK.leftUpperbody.joints[i + 1].transform.position); } //right lowerbody for (int i = 0; i < IK.rightLeg.joints.Count - 1; i++) { Handles.SphereCap(0, IK.rightLeg.joints[i].transform.position, Quaternion.identity, 0.03f); Handles.DrawLine(IK.rightLeg.joints[i].transform.position, IK.rightLeg.joints[i + 1].transform.position); } //left lowerbody for (int i = 0; i < IK.leftLeg.joints.Count - 1; i++) { Handles.SphereCap(0, IK.leftLeg.joints[i].transform.position, Quaternion.identity, 0.03f); Handles.DrawLine(IK.leftLeg.joints[i].transform.position, IK.leftLeg.joints[i + 1].transform.position); } //spine if (IK.HR.head && IK.rightUpperbody.joints.Count >= 5 && !(IK.rightUpperbody.joints.Count <= 3)) { Handles.DrawLine(IK.HR.spine.spine2.position, IK.HR.head.position); } //draw end effectors if (IK.HR.head) { Handles.color = Color.Lerp(new Color(0.5f, 0.8f, 0.8f, 0.8f), new Color(1f, 0.1f, 0.1f), IK.head.weight); Handles.CubeCap(0, IK.HR.head.position, Quaternion.identity, 0.02f); } Handles.color = Color.Lerp(new Color(0.5f, 0.8f, 0.8f, 0.8f), new Color(1f, 0.1f, 0.1f), IK.rightUpperbody.weight); Handles.CubeCap(0, IK.rightUpperbody.GetEndEffector().position, Quaternion.identity, 0.025f); Handles.color = Color.Lerp(new Color(0.5f, 0.8f, 0.8f, 0.8f), new Color(1f, 0.1f, 0.1f), IK.leftUpperbody.weight); Handles.CubeCap(0, IK.leftUpperbody.GetEndEffector().position, Quaternion.identity, 0.025f); Handles.color = Color.Lerp(new Color(0.5f, 0.8f, 0.8f, 0.8f), new Color(1f, 0.1f, 0.1f), IK.rightLeg.weight); Handles.CubeCap(0, IK.rightLeg.GetEndEffector().position, Quaternion.identity, 0.025f); Handles.color = Color.Lerp(new Color(0.5f, 0.8f, 0.8f, 0.8f), new Color(1f, 0.1f, 0.1f), IK.leftLeg.weight); Handles.CubeCap(0, IK.leftLeg.GetEndEffector().position, Quaternion.identity, 0.025f); //draw targets with different colors Handles.color = Color.red; if (IK.rightUpperbody.weight > 0f) { Handles.DrawDottedLine(IK.rightUpperbody.GetEndEffector().position, IK.rightUpperbody.GetIKPosition(), 2f); } if (IK.leftUpperbody.weight > 0f) { Handles.DrawDottedLine(IK.leftUpperbody.GetEndEffector().position, IK.leftUpperbody.GetIKPosition(), 2f); } if (IK.rightLeg.weight > 0f) { Handles.DrawDottedLine(IK.rightLeg.GetEndEffector().position, IK.rightLeg.GetIKPosition(), 2f); } if (IK.leftLeg.weight > 0f) { Handles.DrawDottedLine(IK.leftLeg.GetEndEffector().position, IK.leftLeg.GetIKPosition(), 2f); } if (IK.head.target && IK.HR.head && IK.head.weight > 0f) { Handles.DrawDottedLine(IK.HR.head.position, IK.head.target.position, 2f); } }
protected virtual void OnSceneGUI() { if (target == null || serializedObject == null) { return; } var script = target as StereoRenderer; // draw handle for anchor object if (script.anchorTransform == null) { var anchorPos = script.anchorPos; var anchorRot = script.anchorRot; EditorGUI.BeginChangeCheck(); var newAnchorPos = Handles.PositionHandle(anchorPos, anchorRot); var anchorPosChanged = EditorGUI.EndChangeCheck(); EditorGUI.BeginChangeCheck(); var newAnchorRot = Handles.RotationHandle(anchorRot, anchorPos); var anchorRotChanged = EditorGUI.EndChangeCheck(); Handles.color = anchorColor; Handles.CubeCap(0, newAnchorPos, newAnchorRot, cubeSize); if (anchorPosChanged || anchorRotChanged) { Undo.RecordObject(target, "Stereo Anchor Pose Changed"); if (anchorPosChanged) { script.anchorPos = newAnchorPos; } if (anchorRotChanged) { script.anchorRot = newAnchorRot; } EditorUtility.SetDirty(target); } } else { Handles.color = anchorColor; Handles.CubeCap(0, script.anchorTransform.transform.position, script.anchorTransform.transform.rotation, cubeSize); } // draw handle for canvas origin object if (script.canvasOrigin == null) { var canvasOriginPos = script.canvasOriginPos; var canvasOriginRot = script.canvasOriginRot; EditorGUI.BeginChangeCheck(); var newOriginPos = Handles.PositionHandle(canvasOriginPos, canvasOriginRot); var originPosChanged = EditorGUI.EndChangeCheck(); EditorGUI.BeginChangeCheck(); var newOriginRot = Handles.RotationHandle(canvasOriginRot, canvasOriginPos); var originRotChanged = EditorGUI.EndChangeCheck(); Handles.color = originColor; Handles.CubeCap(0, newOriginPos, newOriginRot, cubeSize); if (originPosChanged || originRotChanged) { Undo.RecordObject(target, "Canvas Origin Pose Changed"); if (originPosChanged) { script.canvasOriginPos = newOriginPos; } if (originRotChanged) { script.canvasOriginRot = newOriginRot; } EditorUtility.SetDirty(target); } } else { Handles.color = originColor; Handles.CubeCap(0, script.canvasOrigin.transform.position, script.canvasOrigin.transform.rotation, cubeSize); } }
void OnSceneGUI() { int inSplineNodeSelectionCount = Selection.gameObjects.CountIf(go => go.GetComponent <InSplineNode>() != null); if (inSplineNodeSelectionCount == 1) { if (Selection.objects.Length == 1) { Handles.BeginGUI(); range = EditorGUI.Slider(new Rect(15, 10, 300, 18), "Range", range, 0.0f, maxRange); if (SplineNode.SplineController == null) { GUI.enabled = false; } if (GUI.Button(new Rect(15, 30, 200, 20), "Combine nodes in Range")) { CombineInRange(SplineNode, range); Repaint(); } if (GUI.Button(new Rect(15, 50, 200, 20), "Connect all nodes in Range")) { string message = "Connect nodes in range"; UndoAll(message); ConnectInRange(SplineNode, range); Repaint(); } GUI.enabled = true; Handles.EndGUI(); if (SplineNode.SplineController != null && Selection.activeGameObject != null) { Handles.color = Color.red; Handles.CubeCap(0, Selection.activeGameObject.transform.position, Quaternion.identity, 1.2f * 0.3f); for (int i = 0; i < SplineNode.SplineController.Nodes.Count; i++) { var node = SplineNode.SplineController.Nodes[i]; if (node == SplineNode || node == null) { continue; } if (SplineNode == null) { break; } if (Vector3.Distance(node.transform.position, SplineNode.transform.position) < range) { Handles.CubeCap(0, node.gameObject.transform.position, Quaternion.identity, 1.2f * 0.3f); } } Handles.color = Color.white; } var color = Color.gray; Handles.color = color; if (SplineNode != null) { //range = Handles.RadiusHandle(Quaternion.identity, SplineNode.transform.position, range); } } } else if (inSplineNodeSelectionCount == Selection.objects.Length) { if (Selection.activeGameObject != SplineNode.gameObject) { Handles.color = Color.red; if (Selection.activeGameObject != null) { Handles.CubeCap(0, Selection.activeGameObject.transform.position, Quaternion.identity, 0.2f); } Selection.gameObjects.ForEach(go => { var node = go.GetComponent <InSplineNode>(); if (node != null) { Handles.CubeCap(0, node.gameObject.transform.position, Quaternion.identity, 0.2f); } }); Handles.color = Color.white; GUI.enabled = true; Handles.BeginGUI(); if (GUI.Button(new Rect(15, 10, 200, 20), "Combine selected nodes")) { CombineSelectedNodes(); } Handles.EndGUI(); } } Handles.color = Color.white; if (SplineNode != null) { /*if (Selection.activeGameObject != SplineNode.gameObject) * { * * return; * }*/ //if (!Selection.Contains(SplineNode.gameObject)) // return; InSplineDrawer.OnSceneDraw(SplineNode.SplineController); } /* if (Event.current.type == EventType.Layout) * { * HandleUtility.AddDefaultControl(controlID); * }*/ if (GUI.changed && target != null) { EditorUtility.SetDirty(target); } }
/** * Draw a scale handle in 2d space. */ public static Vector2 ScaleHandle2d(int id, Vector2 position, Vector2 scale, int size) { Event e = Event.current; Vector2 mousePosition = e.mousePosition; int width = size / 4; Handles.color = HANDLE_COLOR_UP; Handles.DrawLine(position, position - Vector2.up * size * scale.y); Handles.CubeCap(0, ((Vector3)((position - Vector2.up * scale.y * size))) - Vector3.forward * 16, QuaternionUp, width / 3); Handles.color = HANDLE_COLOR_RIGHT; Handles.DrawLine(position, position + Vector2.right * size * scale.x); Handles.CubeCap(0, ((Vector3)((position + Vector2.right * scale.x * size))) - Vector3.forward * 16, Quaternion.Euler(Vector3.up * 90f), width / 3); Handles.color = HANDLE_COLOR_SCALE; Handles.CubeCap(0, ((Vector3)position) - Vector3.forward * 16, QuaternionUp, width / 2); // If a Tool already is engaged and it's not this one, bail. if (currentId >= 0 && currentId != id) { return(scale); } Rect handleRectUp = new Rect(position.x - width / 2, position.y - size - HANDLE_PADDING, width, size + HANDLE_PADDING); Rect handleRectRight = new Rect(position.x, position.y - width / 2, size + 8, width); Rect handleRectCenter = new Rect(position.x - width / 2, position.y - width / 2, width, width); if (currentId == id) { switch (e.type) { case EventType.MouseDrag: Vector2 diff = axisConstraint.Mask(mousePosition - initialMousePosition); diff.x += size; diff.y = -diff.y; // gui space Y is opposite-world diff.y += size; scale = diff / size; if (axisConstraint == HandleConstraint2d.None) { scale.x = Mathf.Min(scale.x, scale.y); scale.y = Mathf.Min(scale.x, scale.y); } break; case EventType.MouseUp: case EventType.Ignore: currentId = -1; break; } } else { if (e.type == EventType.MouseDown && e.button == 0 && e.modifiers != EventModifiers.Alt) { if (handleRectCenter.Contains(mousePosition)) { currentId = id; handleOffset = position - mousePosition; initialMousePosition = mousePosition; axisConstraint = new HandleConstraint2d(1, 1); } else if (handleRectRight.Contains(mousePosition)) { currentId = id; handleOffset = position - mousePosition; initialMousePosition = mousePosition; axisConstraint = new HandleConstraint2d(1, 0); } else if (handleRectUp.Contains(mousePosition)) { currentId = id; handleOffset = position - mousePosition; initialMousePosition = mousePosition; axisConstraint = new HandleConstraint2d(0, 1); } } } return(scale); }
void OnSceneGUI() { Handles.ArrowCap(0, Target.Position, UnityEngine.Quaternion.LookRotation(Target.Transform.up), 2); // Handle custom Tools if (Tools.current == Tool.Rotate || Tools.current == Tool.Scale || Tools.current == Tool.View) { customMoveTool = false; } else { Tools.current = Tool.None; customMoveTool = true; } if (IsActive) { bool hasLocalHandles = Target.Spline.Interpolation == CurvyInterpolation.Bezier; int controlID = GUIUtility.GetControlID(GetHashCode(), FocusType.Passive); if (customMoveTool) { UnityEngine.Vector3 delta = CurvyEditorUtility.PositionHandle(controlID, Tools.handlePosition, Tools.handleRotation, 1f, ConstrainXAxis, ConstrainYAxis, ConstrainZAxis) - Tools.handlePosition; if (GUI.changed) { UnityEngine.Transform[] transforms = Selection.transforms; for (int i = 0; i < transforms.Length; i++) { transforms[i].position += delta; } Target.Spline.Refresh(true, true, false); if (ConstraintSplineLength > 0 && Target.Spline.Length > ConstraintSplineLength) { for (int i = 0; i < transforms.Length; i++) { transforms[i].position -= delta; } Target.Spline.Refresh(true, true, false); } } } // Bezier-Handles if (hasLocalHandles) { Handles.color = UnityEngine.Color.grey; UnityEngine.Vector3 handleOut = Target.HandleOutPosition; UnityEngine.Vector3 handleIn = Target.HandleInPosition; Target.HandleOutPosition = CurvyEditorUtility.PositionHandle(GUIUtility.GetControlID(FocusType.Passive), Target.HandleOutPosition, Tools.handleRotation, 0.5f, ConstrainXAxis, ConstrainYAxis, ConstrainZAxis); Handles.CubeCap(0, Target.HandleOutPosition, UnityEngine.Quaternion.identity, HandleUtility.GetHandleSize(Target.HandleOutPosition) * 0.1f); Handles.DrawLine(Target.HandleOutPosition, Target.Position); Target.HandleInPosition = CurvyEditorUtility.PositionHandle(GUIUtility.GetControlID(FocusType.Passive), Target.HandleInPosition, Tools.handleRotation, 0.5f, ConstrainXAxis, ConstrainYAxis, ConstrainZAxis); Handles.CubeCap(0, Target.HandleInPosition, UnityEngine.Quaternion.identity, HandleUtility.GetHandleSize(Target.HandleInPosition) * 0.1f); Handles.DrawLine(Target.HandleInPosition, Target.Position); if (GUI.changed) { Target.Spline.RefreshImmediately(true, true, false); if (ConstraintSplineLength > 0 && Target.Spline.Length > ConstraintSplineLength) { Target.HandleOutPosition = handleOut; Target.HandleInPosition = handleIn; Target.Spline.RefreshImmediately(true, true, false); } } } // Window Handles.BeginGUI(); GUILayout.Window(GetInstanceID(), new Rect(10, 40, 150, 20), DoWin, Target.name); Handles.EndGUI(); // Shortcut-Keys if (CurvyPreferences.kNext.IsKeyDown(Event.current) && Target.NextControlPoint) { Selection.activeObject = Target.NextControlPoint; } else if (CurvyPreferences.kPrev.IsKeyDown(Event.current) && Target.PreviousControlPoint) { Selection.activeObject = Target.PreviousControlPoint; } else if (CurvyPreferences.kInsertBefore.IsKeyDown(Event.current)) { InsBefore(); } else if (CurvyPreferences.kInsertAfter.IsKeyDown(Event.current)) { InsAfter(); } else if (CurvyPreferences.kDelete.IsKeyDown(Event.current)) { Delete(); } else if (CurvyPreferences.kToggleFreeMove.IsKeyDown(Event.current)) { Target.FreeHandles = !Target.FreeHandles; } } }
public static NPVoxCoord VoxelPicker(NPVoxToUnity npVoxToUnity, NPVoxCoord previousSelectedCoord, int buttonNum, Transform transform) { if (npVoxToUnity == null) { return(NPVoxCoord.INVALID); } int controlID = GUIUtility.GetControlID(FocusType.Passive); EventType eventType = Event.current.GetTypeForControl(controlID); Vector3 voxelCenter = new Vector3(); NPVoxCoord impactCoord = NPVoxCoord.INVALID; // Vector3 offset = SceneView.currentDrawingSceneView.position; // Vector3 mp = Event.current.mousePosition - offset; float mouseScale = GetMouseScale(SceneView.currentDrawingSceneView.camera); Ray r = SceneView.currentDrawingSceneView.camera.ScreenPointToRay( new Vector3(Event.current.mousePosition.x * mouseScale, -Event.current.mousePosition.y * mouseScale + Camera.current.pixelHeight) ); NPVoxRayCastHit raycastHit = npVoxToUnity.Raycast(r, transform, 20); if (raycastHit.IsHit) { impactCoord = raycastHit.Coord; voxelCenter = npVoxToUnity.ToUnityPosition(impactCoord); // if (isMouseDown) { Handles.color = Color.yellow; Handles.CubeCap(controlID, voxelCenter, Quaternion.identity, npVoxToUnity.VoxeSize.x * 2.0f); // SceneView.currentDrawingSceneView.Repaint(); } } else { return(previousSelectedCoord); } switch (eventType) { case EventType.Layout: mouseStartPos = Event.current.mousePosition; // if (raycastHit.IsHit) { HandleUtility.AddControl( controlID, HandleUtility.DistanceToCircle(voxelCenter, npVoxToUnity.VoxeSize.x * 0.25f) ); } break; case EventType.MouseDown: if (HandleUtility.nearestControl == controlID && Event.current.button == buttonNum) { mouseStartPos = Event.current.mousePosition; GUIUtility.hotControl = controlID; Event.current.Use(); } break; case EventType.MouseUp: if (GUIUtility.hotControl == controlID) { GUI.changed = true; GUIUtility.hotControl = 0; Event.current.Use(); return(impactCoord); } break; case EventType.MouseDrag: if (GUIUtility.hotControl == controlID) { Event.current.Use(); } break; } return(previousSelectedCoord); }
private void OnSceneGUI() { if (map.nodes == null) { map.nodes = new List <NodeForEdit>(); } if (map.nodes.Count == 0) { AddNewNode("NewNode"); } float size = 5;// HandleUtility.GetHandleSize(Vector3.zero); float fSize = HandleUtility.GetHandleSize(Vector3.zero); f0.fontSize = (int)(20 * size / fSize); f0.fontSize = Mathf.Clamp(f0.fontSize, 5, 100); for (int i = 0; i < map.nodes.Count; i++) { if (map.nodes[i] == null || !map.nodes[i].hasInit) { continue; } NodeForEdit node = map.nodes[i]; Vector3 dpos = Map2World(node.pos, size); if (pickedNode != node) { f0.normal.textColor = Color.white; } else { f0.normal.textColor = Color.black; Handles.CubeCap(0, dpos, Quaternion.identity, size * 2); } Vector3 lPos = dpos + Vector3.left * size * .9f + Vector3.up * size * .9f; Handles.Label(lPos, node.name + "[" + node.id + "]", f0); if (Handles.Button(dpos, Quaternion.identity, size, size, Handles.RectangleCap) && pickedNode != node) { pickedNode = node; Repaint(); } foreach (var val in node.npcs) { lPos += Vector3.down * f0.fontSize * .02f * size; Handles.Label(lPos, val.name + "[" + val.id + "]", f0); } foreach (var val in node.items) { lPos += Vector3.down * f0.fontSize * .02f * size; Handles.Label(lPos, val.name + "[" + val.id + "]", f0); } if (node == pickedNode) { Handles.color = Color.cyan; } foreach (var e in Enum.GetValues(typeof(NodeForEdit.MoveDir))) { NodeForEdit.MoveDir key = (NodeForEdit.MoveDir)e; int did = (int)key; if (node.road[did]) { NodeForEdit dest = map.FindRoad(node, key); if (dest == null) { node.road[did] = false; SceneView.RepaintAll(); continue; } if (dest == pickedNode) { Handles.color = Color.yellow; } Vector3 p1 = Map2World(node.pos, size); Vector3 p2 = Map2World(dest.pos, size); Vector3 dp = (p2 - p1).normalized * size; p1 += dp; p2 -= dp; if (p1.x != p2.x && p1.y != p2.y) { p1 += dp * .5f; p2 -= dp * .5f; } float fx = p1.y < p2.y ? -1 : 1; fx = p1.y == p2.y ? 0 : fx; float fy = p1.x > p2.x ? -1 : 1; fy = p1.x == p2.x ? 0 : fy; Vector3 fix = new Vector3(fx, fy, 0) * size * .05f; if (p1.x != p2.x && p1.y != p2.y) { fix *= 0.7f; } p1 += fix; p2 += fix; Handles.DrawLine(p1, p2); // 画箭头部分 Vector3 dir = (p2 - p1).normalized; dir = Quaternion.Euler(0, 0, 90) * dir; p1 += dir * size; dir = (p2 - p1).normalized * size * .2f; p1 = p2 - dir; Handles.DrawLine(p1, p2); } } Handles.color = Color.white; } }
void DrawGizmoAxis(AXIS drawAxis, bool bLocal, float fLineLen, float fCapSize) { Transform selTrans = m_SelectedTransform.transform; Vector3 vecEuler = Vector3.zero; Vector3 vecDirect = Vector3.zero; // set color if (m_nActiveAxis != drawAxis || m_bActiveLocal != bLocal) { switch (drawAxis) { case AXIS.X: Handles.color = Color.red; break; case AXIS.Y: Handles.color = Color.green; break; case AXIS.Z: Handles.color = Color.blue; break; } } else { Handles.color = Color.white; } if (((GIZMO_TYPE)m_nGizmoTypeIndex) == GIZMO_TYPE.HAND) { Handles.color = new Color(Handles.color.r, Handles.color.g, Handles.color.b, m_fHandAlpha); } // axis color Gizmos.color = Handles.color; vecDirect = GetDirect(selTrans, drawAxis, bLocal); vecEuler = GetEuler(selTrans, drawAxis, bLocal); // draw line // Handles.DrawLine(GetPosition(selTrans), GetPosition(selTrans) + vecDirect * fLineLen); if (((GIZMO_TYPE)m_nGizmoTypeIndex) == GIZMO_TYPE.SCALE) { float scale = 1; if (m_bClick) { switch (drawAxis) { case AXIS.X: scale = selTrans.localScale.x / m_OldOriScale.x; break; case AXIS.Y: scale = selTrans.localScale.y / m_OldOriScale.y; break; case AXIS.Z: scale = selTrans.localScale.z / m_OldOriScale.z; break; } } Gizmos.DrawRay(GetPosition(selTrans), vecDirect * fLineLen * scale); } else { Gizmos.DrawRay(GetPosition(selTrans), vecDirect * fLineLen); } // draw cap switch (((GIZMO_TYPE)m_nGizmoTypeIndex)) { case GIZMO_TYPE.POSITION: Handles.ConeCap(0, GetPosition(selTrans) + vecDirect * fLineLen, Quaternion.Euler(vecEuler), fCapSize * 1.6f); break; case GIZMO_TYPE.ROTATION: Handles.CylinderCap(0, GetPosition(selTrans) + vecDirect * fLineLen, Quaternion.Euler(vecEuler), fCapSize * 2f); break; case GIZMO_TYPE.SCALE: Handles.CubeCap(0, GetPosition(selTrans) + vecDirect * fLineLen, Quaternion.Euler(vecEuler), fCapSize); break; } // // draw rot line // if (((GIZMO_TYPE)m_nGizmoTypeIndex) == GIZMO_TYPE.ROTATION) // { // if (m_bClick) // { // transform.position = GetPosition(selTrans); // transform.rotation = Quaternion.Euler(m_SaveRotate); // // switch (drawAxis) // { // case AXIS.X: Gizmos.color = Color.red; Gizmos.DrawLine(GetPosition(selTrans), selTrans.right * fLineLen * 1.3f); break; // case AXIS.Y: Gizmos.color = Color.green; Gizmos.DrawLine(GetPosition(selTrans), selTrans.up * fLineLen * 1.3f); break; // case AXIS.Z: Gizmos.color = Color.blue; Gizmos.DrawLine(GetPosition(selTrans), selTrans.forward * fLineLen * 1.3f); break; // } // if (m_nActiveAxis != drawAxis && m_bActiveLocal == bLocal) // { // Gizmos.color = Color.white; // switch (drawAxis) // { // case AXIS.X: Gizmos.DrawLine(transform.position, transform.right * fLineLen * 2); break; // case AXIS.Y: Gizmos.DrawLine(transform.position, transform.up * fLineLen * 2); break; // case AXIS.Z: Gizmos.DrawLine(transform.position, transform.forward * fLineLen * 2); break; // // case AXIS.X: Handles.DrawSolidArc(transform.position, transform.right, -transform.up, m_SaveRotate.z, fCapSize*10); break; // } // } // } // } }
/* * Draws the scene view helpers for IKSolverTrigonometric * */ public static void AddScene(IKSolverTrigonometric solver, Color color, bool modifiable) { if (Application.isPlaying && !solver.initiated) { return; } if (!Application.isPlaying && !solver.IsValid()) { return; } //float length = Vector3.Distance(solver.bone1.transform.position, solver.bone2.transform.position) + Vector3.Distance(solver.bone2.transform.position, solver.bone3.transform.position); //float size = length * 0.05f; Handles.color = color; GUI.color = color; Vector3 bendPosition = solver.bone2.transform.position; Vector3 endPosition = solver.bone3.transform.position; // Chain lines Handles.DrawLine(solver.bone1.transform.position, bendPosition); Handles.DrawLine(bendPosition, endPosition); // Joints Handles.SphereCap(0, solver.bone1.transform.position, Quaternion.identity, GetHandleSize(solver.bone1.transform.position)); Handles.SphereCap(0, bendPosition, Quaternion.identity, GetHandleSize(bendPosition)); Handles.SphereCap(0, endPosition, Quaternion.identity, GetHandleSize(endPosition)); if (Application.isPlaying && (solver.IKPositionWeight > 0 || solver.IKRotationWeight > 0)) { if (modifiable) { Handles.CubeCap(0, solver.IKPosition, solver.IKRotation, GetHandleSize(solver.IKPosition)); // Manipulating position and rotation switch (Tools.current) { case Tool.Move: if (solver.target == null) { solver.IKPosition = Handles.PositionHandle(solver.IKPosition, Quaternion.identity); } break; case Tool.Rotate: if (solver.target == null) { solver.IKRotation = Handles.RotationHandle(solver.IKRotation, solver.IKPosition); } break; } } // Target Handles.color = new Color(color.r, color.g, color.b, color.a * Mathf.Max(solver.IKPositionWeight, solver.IKRotationWeight)); Handles.DrawLine(endPosition, solver.IKPosition); } Handles.color = Color.white; GUI.color = Color.white; }
public static float DoAxis(int id, float scale, Vector3 position, Vector3 direction, Quaternion rotation, float size, float snap) { Event current = Event.current; switch (current.GetTypeForControl(id)) { case EventType.MouseDown: if (((HandleUtility.nearestControl == id) && (current.button == 0)) || ((GUIUtility.keyboardControl == id) && (current.button == 2))) { int num = id; GUIUtility.keyboardControl = num; GUIUtility.hotControl = num; s_CurrentMousePosition = s_StartMousePosition = current.mousePosition; s_StartScale = scale; current.Use(); EditorGUIUtility.SetWantsMouseJumping(1); } return(scale); case EventType.MouseUp: if ((GUIUtility.hotControl == id) && ((current.button == 0) || (current.button == 2))) { GUIUtility.hotControl = 0; current.Use(); EditorGUIUtility.SetWantsMouseJumping(0); } return(scale); case EventType.MouseMove: case EventType.KeyDown: case EventType.KeyUp: case EventType.ScrollWheel: return(scale); case EventType.MouseDrag: if (GUIUtility.hotControl == id) { s_CurrentMousePosition += current.delta; float val = 1f + (HandleUtility.CalcLineTranslation(s_StartMousePosition, s_CurrentMousePosition, position, direction) / size); val = Handles.SnapValue(val, snap); scale = s_StartScale * val; GUI.changed = true; current.Use(); } return(scale); case EventType.Repaint: { Color white = Color.white; if (id == GUIUtility.keyboardControl) { white = Handles.color; Handles.color = Handles.selectedColor; } float num3 = size; if (GUIUtility.hotControl == id) { num3 = (size * scale) / s_StartScale; } Handles.CubeCap(id, position + ((Vector3)((direction * num3) * s_ScaleDrawLength)), rotation, size * 0.1f); Handles.DrawLine(position, position + ((Vector3)(direction * ((num3 * s_ScaleDrawLength) - (size * 0.05f))))); if (id == GUIUtility.keyboardControl) { Handles.color = white; } return(scale); } case EventType.Layout: HandleUtility.AddControl(id, HandleUtility.DistanceToLine(position, position + ((Vector3)(direction * size)))); HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(position + ((Vector3)(direction * size)), size * 0.2f)); return(scale); } return(scale); }
void OnSceneGUI() { Rigidbody[] rigidbodies = script.transform.GetComponentsInChildren <Rigidbody>(); if (rigidbodies.Length == 0) { return; } Collider[] colliders = script.transform.GetComponentsInChildren <Collider>(); if (script.selectedRigidbody == null) { script.selectedRigidbody = rigidbodies[0]; } if (script.selectedCollider == null && colliders.Length > 0) { script.selectedCollider = colliders[0]; } Rigidbody symmetricRigidbody = script.symmetry && script.selectedRigidbody != null?SymmetryTools.GetSymmetric(script.selectedRigidbody, rigidbodies, script.transform) : null; Collider symmetricCollider = script.symmetry && script.selectedCollider != null?SymmetryTools.GetSymmetric(script.selectedCollider, colliders, script.transform) : null; Joint joint = script.selectedRigidbody != null?script.selectedRigidbody.GetComponent <Joint>() : null; Joint symmetricJoint = joint != null && symmetricRigidbody != null?symmetricRigidbody.GetComponent <Joint>() : null; // Selected Transform selected = script.mode == RootMotion.Dynamics.RagdollEditor.Mode.Colliders? (script.selectedCollider != null? script.selectedCollider.transform: null): (script.selectedRigidbody != null? script.selectedRigidbody.transform: null); if (selected != null) { Handles.BeginGUI(); GUILayout.BeginVertical(new GUIContent("Ragdoll Editor", string.Empty), "Window", GUILayout.Width(200), GUILayout.Height(20)); GUILayout.BeginHorizontal(); GUILayout.Label(selected.name); if (GUILayout.Button("Select GameObject", EditorStyles.miniButton)) { Selection.activeGameObject = selected.gameObject; } GUILayout.EndHorizontal(); GUILayout.Space(10); //GUILayout.BeginVertical("Box"); GUILayout.BeginHorizontal(); GUILayout.Label("Edit Mode", GUILayout.Width(86)); script.mode = (RagdollEditor.Mode)EditorGUILayout.EnumPopup(string.Empty, script.mode, GUILayout.Width(100)); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Symmetry", GUILayout.Width(86)); script.symmetry = GUILayout.Toggle(script.symmetry, string.Empty); GUILayout.EndHorizontal(); GUILayout.Space(10); // COLLIDERS if (script.mode == RagdollEditor.Mode.Colliders && selected != null) { if (script.selectedCollider is CapsuleCollider) { var capsule = script.selectedCollider as CapsuleCollider; var capsuleS = symmetricCollider != null?symmetricCollider.transform.GetComponent <CapsuleCollider>() : null; if (GUILayout.Button("Convert To Box Collider")) { ColliderTools.ConvertToBoxCollider(capsule); script.selectedCollider = selected.GetComponent <Collider>(); if (capsuleS != null) { ColliderTools.ConvertToBoxCollider(capsuleS); } return; } if (GUILayout.Button("Convert To Sphere Collider")) { ColliderTools.ConvertToSphereCollider(capsule); script.selectedCollider = selected.GetComponent <Collider>(); if (capsuleS != null) { ColliderTools.ConvertToSphereCollider(capsuleS); } return; } string capsuleDir = capsule.direction == 0? "X": (capsule.direction == 1? "Y": "Z"); if (GUILayout.Button("Direction: " + capsuleDir)) { if (capsuleS == null) { Undo.RecordObject(capsule, "Change Capsule Direction"); } else { Undo.RecordObjects(new Object[2] { capsule, capsuleS }, "Change Capsule Direction"); } capsule.direction++; if (capsule.direction > 2) { capsule.direction = 0; } if (capsuleS != null) { capsuleS.direction = capsule.direction; } } } else if (script.selectedCollider is BoxCollider) { var box = script.selectedCollider as BoxCollider; var boxS = symmetricCollider != null?symmetricCollider.transform.GetComponent <BoxCollider>() : null; if (GUILayout.Button("Convert To Capsule Collider")) { ColliderTools.ConvertToCapsuleCollider(box); script.selectedCollider = selected.GetComponent <Collider>(); if (boxS != null) { ColliderTools.ConvertToCapsuleCollider(boxS); } return; } if (GUILayout.Button("Convert To Sphere Collider")) { ColliderTools.ConvertToSphereCollider(box); script.selectedCollider = selected.GetComponent <Collider>(); if (boxS != null) { ColliderTools.ConvertToSphereCollider(boxS); } return; } if (GUILayout.Button("Rotate Collider")) { if (boxS == null) { Undo.RecordObject(box, "Rotate Collider"); } else { Undo.RecordObjects(new Object[2] { box, boxS }, "Rotate Collider"); } box.size = new Vector3(box.size.y, box.size.z, box.size.x); if (boxS != null) { boxS.size = box.size; } } } else if (script.selectedCollider is SphereCollider) { var sphere = script.selectedCollider as SphereCollider; var sphereS = symmetricCollider != null?symmetricCollider.transform.GetComponent <SphereCollider>() : null; if (GUILayout.Button("Convert To Capsule Collider")) { ColliderTools.ConvertToCapsuleCollider(sphere); script.selectedCollider = selected.GetComponent <Collider>(); if (sphereS != null) { ColliderTools.ConvertToCapsuleCollider(sphereS); } return; } if (GUILayout.Button("Convert To Box Collider")) { ColliderTools.ConvertToBoxCollider(sphere); script.selectedCollider = selected.GetComponent <Collider>(); if (sphereS != null) { ColliderTools.ConvertToBoxCollider(sphereS); } return; } } } // JOINTS if (script.mode == RagdollEditor.Mode.Joints) { if (joint != null && (joint is CharacterJoint || joint is ConfigurableJoint)) { GUILayout.BeginHorizontal(); GUILayout.Label("Connected Body"); var lastConnectedBody = joint.connectedBody; var newConnectedBody = (Rigidbody)EditorGUILayout.ObjectField(joint.connectedBody, typeof(Rigidbody), true); if (newConnectedBody != lastConnectedBody) { Undo.RecordObject(joint, "Changing Joint ConnectedBody"); joint.connectedBody = newConnectedBody; } GUILayout.EndHorizontal(); if (joint is CharacterJoint) { var j = joint as CharacterJoint; var sJ = symmetricJoint != null && symmetricJoint is CharacterJoint? symmetricJoint as CharacterJoint: null; if (GUILayout.Button("Convert to Configurable")) { JointConverter.CharacterToConfigurable(j); if (sJ != null) { JointConverter.CharacterToConfigurable(sJ); } } if (GUILayout.Button("Switch Yellow/Green")) { JointTools.SwitchXY(ref j); if (sJ != null) { JointTools.SwitchXY(ref sJ); } } if (GUILayout.Button("Switch Yellow/Blue")) { JointTools.SwitchXZ(ref j); if (sJ != null) { JointTools.SwitchXZ(ref sJ); } } if (GUILayout.Button("Switch Green/Blue")) { JointTools.SwitchYZ(ref j); if (sJ != null) { JointTools.SwitchYZ(ref sJ); } } if (GUILayout.Button("Invert Yellow")) { JointTools.InvertAxis(ref joint); if (sJ != null) { JointTools.InvertAxis(ref symmetricJoint); } } } if (joint is ConfigurableJoint) { var j = joint as ConfigurableJoint; var sJ = symmetricJoint != null && symmetricJoint is ConfigurableJoint? symmetricJoint as ConfigurableJoint: null; if (GUILayout.Button("Switch Yellow/Green")) { JointTools.SwitchXY(ref j); if (sJ != null) { JointTools.SwitchXY(ref sJ); } } if (GUILayout.Button("Switch Yellow/Blue")) { JointTools.SwitchXZ(ref j); if (sJ != null) { JointTools.SwitchXZ(ref sJ); } } if (GUILayout.Button("Switch Green/Blue")) { JointTools.SwitchYZ(ref j); if (sJ != null) { JointTools.SwitchYZ(ref sJ); } } if (GUILayout.Button("Invert Yellow")) { JointTools.InvertAxis(ref joint); if (sJ != null) { JointTools.InvertAxis(ref symmetricJoint); } } } } } GUILayout.EndVertical(); //GUILayout.EndArea(); Handles.EndGUI(); if (script.mode == RagdollEditor.Mode.Joints && joint != null) { if (joint is CharacterJoint) { var j = joint as CharacterJoint; SoftJointLimit lowTwistLimit = j.lowTwistLimit; SoftJointLimit highTwistLimit = j.highTwistLimit; SoftJointLimit swing1Limit = j.swing1Limit; SoftJointLimit swing2Limit = j.swing2Limit; CharacterJointInspector.DrawJoint(j); if (symmetricJoint != null && symmetricJoint is CharacterJoint) { var sJ = symmetricJoint as CharacterJoint; CharacterJointInspector.DrawJoint(sJ, false, 0.5f); // Low Twist if (lowTwistLimit.limit != j.lowTwistLimit.limit) { Undo.RecordObject(sJ, "Change Joint Limits"); Vector3 lowXAxisWorld = JointTools.GetLowXAxisWorld(j); Vector3 lowXAxisWorldS = JointTools.GetLowXAxisWorld(sJ); Vector3 lowXAxisWorldMirror = SymmetryTools.Mirror(lowXAxisWorld, script.transform); bool low = Vector3.Dot(lowXAxisWorldMirror, lowXAxisWorldS) < 0f; JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Primary, sJ, script.transform); float delta = j.lowTwistLimit.limit - lowTwistLimit.limit; JointTools.ApplyXDeltaToJointLimit(ref sJ, delta, sJointAxis, low); } // High Twist if (highTwistLimit.limit != j.highTwistLimit.limit) { Undo.RecordObject(sJ, "Change Joint Limits"); Vector3 highXAxisWorld = JointTools.GetHighXAxisWorld(j); Vector3 highXAxisWorldS = JointTools.GetHighXAxisWorld(sJ); Vector3 highXAxisWorldMirror = SymmetryTools.Mirror(highXAxisWorld, script.transform); bool low = Vector3.Dot(highXAxisWorldMirror, highXAxisWorldS) > 0f; JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Primary, sJ, script.transform); float delta = j.highTwistLimit.limit - highTwistLimit.limit; JointTools.ApplyXDeltaToJointLimit(ref sJ, -delta, sJointAxis, low); } // Swing 1 if (swing1Limit.limit != j.swing1Limit.limit) { Undo.RecordObject(sJ, "Change Joint Limits"); JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Secondary, sJ, script.transform); float delta = j.swing1Limit.limit - swing1Limit.limit; JointTools.ApplyDeltaToJointLimit(ref sJ, delta, sJointAxis); } // Swing 2 if (swing2Limit.limit != j.swing2Limit.limit) { Undo.RecordObject(sJ, "Change Joint Limits"); JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Tertiary, sJ, script.transform); float delta = j.swing2Limit.limit - swing2Limit.limit; JointTools.ApplyDeltaToJointLimit(ref sJ, delta, sJointAxis); } } } else if (joint is ConfigurableJoint) { var j = joint as ConfigurableJoint; SoftJointLimit lowAngularXLimit = j.lowAngularXLimit; SoftJointLimit highAngularXLimit = j.highAngularXLimit; SoftJointLimit angularYLimit = j.angularYLimit; SoftJointLimit angularZLimit = j.angularZLimit; ConfigurableJointInspector.DrawJoint(j); if (symmetricJoint != null && symmetricJoint is ConfigurableJoint) { var sJ = symmetricJoint as ConfigurableJoint; ConfigurableJointInspector.DrawJoint(sJ, false, 0.5f); // Low X if (lowAngularXLimit.limit != j.lowAngularXLimit.limit) { Undo.RecordObject(sJ, "Change Joint Limits"); Vector3 lowXAxisWorld = JointTools.GetLowXAxisWorld(j); Vector3 lowXAxisWorldS = JointTools.GetLowXAxisWorld(sJ); Vector3 lowXAxisWorldMirror = SymmetryTools.Mirror(lowXAxisWorld, script.transform); bool low = Vector3.Dot(lowXAxisWorldMirror, lowXAxisWorldS) < 0f; JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Primary, sJ, script.transform); float delta = j.lowAngularXLimit.limit - lowAngularXLimit.limit; JointTools.ApplyXDeltaToJointLimit(ref sJ, delta, sJointAxis, low); } // High X if (highAngularXLimit.limit != j.highAngularXLimit.limit) { Undo.RecordObject(sJ, "Change Joint Limits"); Vector3 highXAxisWorld = JointTools.GetHighXAxisWorld(j); Vector3 highXAxisWorldS = JointTools.GetHighXAxisWorld(sJ); Vector3 highXAxisWorldMirror = SymmetryTools.Mirror(highXAxisWorld, script.transform); bool low = Vector3.Dot(highXAxisWorldMirror, highXAxisWorldS) > 0f; JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Primary, sJ, script.transform); float delta = j.highAngularXLimit.limit - highAngularXLimit.limit; JointTools.ApplyXDeltaToJointLimit(ref sJ, -delta, sJointAxis, low); } // Y if (angularYLimit.limit != j.angularYLimit.limit) { Undo.RecordObject(sJ, "Change Joint Limits"); JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Secondary, sJ, script.transform); float delta = j.angularYLimit.limit - angularYLimit.limit; JointTools.ApplyDeltaToJointLimit(ref sJ, delta, sJointAxis); } // Z if (angularZLimit.limit != j.angularZLimit.limit) { Undo.RecordObject(sJ, "Change Joint Limits"); JointAxis sJointAxis = JointTools.GetSymmetricJointAxis(j, JointAxis.Tertiary, sJ, script.transform); float delta = j.angularZLimit.limit - angularZLimit.limit; JointTools.ApplyDeltaToJointLimit(ref sJ, delta, sJointAxis); } } } } } if (!Application.isPlaying) { foreach (Collider c in colliders) { c.enabled = script.mode == RagdollEditor.Mode.Colliders; } } // HANDLES Color color = new Color(0.2f, 0.9f, 0.5f); Handles.color = color; if (Event.current.type == EventType.mouseUp) { isDragging = false; } if (Event.current.type == EventType.mouseDown) { isDragging = false; } if (script.mode == RagdollEditor.Mode.Colliders) { // Select/move scale colliders for (int i = 0; i < colliders.Length; i++) { if (colliders[i] == script.selectedCollider) { // Moving and scaling selected colliders switch (Tools.current) { case Tool.Move: Vector3 oldPosition = ColliderTools.GetColliderCenterWorld(colliders[i]); Vector3 newPosition = Handles.PositionHandle(oldPosition, colliders[i].transform.rotation); if (newPosition != oldPosition) { if (!isDragging) { Undo.RecordObjects(SymmetryTools.GetColliderPair(colliders[i], symmetricCollider), "Move Colliders"); isDragging = true; } ColliderTools.SetColliderCenterWorld(colliders[i], symmetricCollider, newPosition, script.transform); } break; case Tool.Scale: Vector3 position = ColliderTools.GetColliderCenterWorld(colliders[i]); Vector3 oldSize = ColliderTools.GetColliderSize(colliders[i]); Vector3 oldSizeS = ColliderTools.GetColliderSize(symmetricCollider); Vector3 newSize = Handles.ScaleHandle(oldSize, position, colliders[i].transform.rotation, HandleUtility.GetHandleSize(position)); if (newSize != oldSize) { if (!isDragging) { Undo.RecordObjects(SymmetryTools.GetColliderPair(colliders[i], symmetricCollider), "Scale Colliders"); isDragging = true; } ColliderTools.SetColliderSize(colliders[i], symmetricCollider, newSize, oldSize, oldSizeS, script.transform); } Handles.color = color; break; } // Dot on selected collider if (Tools.current != Tool.Scale) { Handles.color = new Color(0.8f, 0.8f, 0.8f); Vector3 center = ColliderTools.GetColliderCenterWorld(colliders[i]); float size = GetHandleSize(center); Handles.CubeCap(0, center, colliders[i].transform.rotation, size); Handles.color = color; } } else { // Selecting colliders Vector3 center = ColliderTools.GetColliderCenterWorld(colliders[i]); float size = GetHandleSize(center); if (Handles.Button(center, Quaternion.identity, size * 0.5f, size * 0.5f, Handles.DotCap)) { Undo.RecordObject(script, "Change RagdollEditor Selection"); script.selectedCollider = colliders[i]; } } } } else { // Select joints for (int i = 0; i < rigidbodies.Length; i++) { if (rigidbodies[i] == script.selectedRigidbody) { // Dots on selected joints Handles.color = new Color(0.8f, 0.8f, 0.8f); Vector3 center = rigidbodies[i].transform.position; float size = GetHandleSize(center); Handles.CubeCap(0, center, rigidbodies[i].transform.rotation, size); Handles.color = color; } else { // Selecting joints Vector3 center = rigidbodies[i].transform.position; float size = GetHandleSize(center); if (Handles.Button(center, Quaternion.identity, size * 0.5f, size * 0.5f, Handles.DotCap)) { Undo.RecordObject(script, "Change RagdollEditor Selection"); script.selectedRigidbody = rigidbodies[i]; } } } } Handles.color = Color.white; }
private void DrawSpawnPoints(int i) { if (spawnPointsInstance.spawnGroups[i] != null) { Handles.color = spawnPointsInstance.spawnGroups[i].handleColor; for (int p = 0; p < spawnPointsInstance.spawnGroups[i].spawnPoints.Count; p++) { if (spawnPointsInstance.handleMode == 1) { if (spawnPointsInstance.spawnGroups[i].showHandles) { if (_spawnFoldouts[i]) { if (!Application.isPlaying) { spawnPointsInstance.spawnGroups[i].spawnPoints[p] = Handles.DoPositionHandle(spawnPointsInstance.spawnGroups[i].spawnPoints[p], Quaternion.identity); } } Handles.Label(spawnPointsInstance.spawnGroups[i].spawnPoints[p] + Vector3.right * .25f, spawnPointsInstance.spawnGroups[i].name + "(" + p.ToString() + ")"); if (spawnPointsInstance.spawnGroups[i].handleShape == 0) { Handles.SphereCap(i, spawnPointsInstance.spawnGroups[i].spawnPoints[p], Quaternion.identity, .5f); } if (spawnPointsInstance.spawnGroups[i].handleShape == 1) { Handles.CubeCap(i, spawnPointsInstance.spawnGroups[i].spawnPoints[p], Quaternion.identity, .5f); } if (spawnPointsInstance.spawnGroups[i].handleShape == 2) { Handles.ConeCap(i, spawnPointsInstance.spawnGroups[i].spawnPoints[p] + Vector3.up * .25f, Quaternion.Euler(90, 0, 0), .5f); } if (spawnPointsInstance.spawnGroups[i].handleShape == 3) { Handles.CubeCap(i, spawnPointsInstance.spawnGroups[i].spawnPoints[p], Quaternion.Euler(0, 0, 45), .5f); } } } else { if (_spawnFoldouts[i]) { if (!Application.isPlaying) { spawnPointsInstance.spawnGroups[i].spawnPoints[p] = Handles.DoPositionHandle(spawnPointsInstance.spawnGroups[i].spawnPoints[p], Quaternion.identity); } } Handles.Label(spawnPointsInstance.spawnGroups[i].spawnPoints[p] + Vector3.right * .25f, spawnPointsInstance.spawnGroups[i].name + "(" + p.ToString() + ")"); if (spawnPointsInstance.spawnGroups[i].handleShape == 0) { Handles.SphereCap(i, spawnPointsInstance.spawnGroups[i].spawnPoints[p], Quaternion.identity, .5f); } if (spawnPointsInstance.spawnGroups[i].handleShape == 1) { Handles.CubeCap(i, spawnPointsInstance.spawnGroups[i].spawnPoints[p], Quaternion.identity, .5f); } if (spawnPointsInstance.spawnGroups[i].handleShape == 2) { Handles.ConeCap(i, spawnPointsInstance.spawnGroups[i].spawnPoints[p] + Vector3.up * .25f, Quaternion.Euler(90, 0, 0), .5f); } if (spawnPointsInstance.spawnGroups[i].handleShape == 3) { Handles.CubeCap(i, spawnPointsInstance.spawnGroups[i].spawnPoints[p], Quaternion.Euler(0, 0, 45), .5f); } } } } HandleUtility.Repaint(); }
public static float DoAxis(int id, float scale, Vector3 position, Vector3 direction, Quaternion rotation, float size, bool snapping, float snap, CSGHandles.InitFunction initFunction, CSGHandles.InitFunction shutdownFunction) { var evt = Event.current; switch (evt.GetTypeForControl(id)) { case EventType.Layout: { HandleUtility.AddControl(id, HandleUtility.DistanceToLine(position, position + direction * size)); HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(position + direction * size, size * .2f)); break; } case EventType.MouseDown: { if (CSGHandles.disabled) { break; } if (((HandleUtility.nearestControl == id && evt.button == 0) || (GUIUtility.keyboardControl == id && evt.button == 2)) && GUIUtility.hotControl == 0) { if (initFunction != null) { initFunction(); } GUIUtility.hotControl = GUIUtility.keyboardControl = id; s_CurrentMousePosition = s_StartMousePosition = evt.mousePosition; s_StartScale = scale; evt.Use(); EditorGUIUtility.SetWantsMouseJumping(1); } break; } case EventType.MouseDrag: { if (GUIUtility.hotControl == id) { s_CurrentMousePosition += evt.delta; float dist = 1 + HandleUtility.CalcLineTranslation(s_StartMousePosition, s_CurrentMousePosition, position, direction) / size; dist = SnapValue(dist, snap, snapping); scale = s_StartScale * dist; GUI.changed = true; evt.Use(); } break; } case EventType.MouseUp: { if (GUIUtility.hotControl == id && (evt.button == 0 || evt.button == 2)) { GUIUtility.hotControl = 0; evt.Use(); if (shutdownFunction != null) { shutdownFunction(); } EditorGUIUtility.SetWantsMouseJumping(0); } break; } case EventType.Repaint: { var originalColor = Handles.color; if (id == GUIUtility.keyboardControl) { Handles.color = Handles.selectedColor; } else if (CSGHandles.disabled) { Handles.color = Color.Lerp(originalColor, Handles.secondaryColor, 0.75f); } float s = size; if (GUIUtility.hotControl == id) { s = size * scale / s_StartScale; } #if UNITY_5_6_OR_NEWER Handles.ConeHandleCap(id, position + direction * s * s_ScaleDrawLength, rotation, size * .1f, EventType.Repaint); #else Handles.CubeCap(id, position + direction * s * s_ScaleDrawLength, rotation, size * .1f); #endif Handles.DrawLine(position, position + direction * (s * s_ScaleDrawLength - size * .05f)); Handles.color = originalColor; break; } } return(scale); }
public static float DoAxis(int id, float scale, Vector3 position, Vector3 direction, Quaternion rotation, float size, float snap) { Event current = Event.current; switch (current.GetTypeForControl(id)) { case EventType.MouseDown: if ((HandleUtility.nearestControl == id && current.button == 0) || (GUIUtility.keyboardControl == id && current.button == 2)) { GUIUtility.keyboardControl = id; GUIUtility.hotControl = id; SliderScale.s_CurrentMousePosition = (SliderScale.s_StartMousePosition = current.mousePosition); SliderScale.s_StartScale = scale; current.Use(); EditorGUIUtility.SetWantsMouseJumping(1); } break; case EventType.MouseUp: if (GUIUtility.hotControl == id && (current.button == 0 || current.button == 2)) { GUIUtility.hotControl = 0; current.Use(); EditorGUIUtility.SetWantsMouseJumping(0); } break; case EventType.MouseDrag: if (GUIUtility.hotControl == id) { SliderScale.s_CurrentMousePosition += current.delta; float num = 1f + HandleUtility.CalcLineTranslation(SliderScale.s_StartMousePosition, SliderScale.s_CurrentMousePosition, position, direction) / size; num = Handles.SnapValue(num, snap); scale = SliderScale.s_StartScale * num; GUI.changed = true; current.Use(); } break; case EventType.Repaint: { Color color = Color.white; if (id == GUIUtility.keyboardControl) { color = Handles.color; Handles.color = Handles.selectedColor; } float num2 = size; if (GUIUtility.hotControl == id) { num2 = size * scale / SliderScale.s_StartScale; } Handles.CubeCap(id, position + direction * num2 * SliderScale.s_ScaleDrawLength, rotation, size * 0.1f); Handles.DrawLine(position, position + direction * (num2 * SliderScale.s_ScaleDrawLength - size * 0.05f)); if (id == GUIUtility.keyboardControl) { Handles.color = color; } break; } case EventType.Layout: HandleUtility.AddControl(id, HandleUtility.DistanceToLine(position, position + direction * size)); HandleUtility.AddControl(id, HandleUtility.DistanceToCircle(position + direction * size, size * 0.2f)); break; } return(scale); }
void OnSceneGUI() { if (!target.enabled) { return; } if (target.debugShowActiveJointGizmo && m_jointSelected) { Handles.color = Color.white; Handles.RectangleCap(-1, m_jointSelected.position, Camera.current ? Camera.current.transform.rotation : m_jointSelected.rotation, 0.05f); } if (!target.debugShowConstraintsGizmos || target.constraints == null) { return; } foreach (var constraint in target.constraints) { var sourcePos = constraint.sourceJoint.position; if (constraint.usePositionConstraint) { try { var pc = constraint.positionConstraint; //var weightedTargetPos = RigMeister2000.ConstraintWeightedTarget.GetWeightedPosition(pc.weightedTargetJoints); //var sourceToTarget = weightedTargetPos - sourcePos; if (pc.weightedTargetJoints.Length > 1) { foreach (var wtj in pc.weightedTargetJoints) { Handles.color = Color.cyan; Handles.DrawLine(sourcePos, wtj.joint.position); Handles.color = Color.magenta; Handles.CubeCap(-1, wtj.joint.position, Quaternion.identity, 0.025f); } } Handles.color = Color.cyan; Handles.CubeCap(-1, sourcePos, Quaternion.identity, 0.025f); } catch (System.Exception) {} } if (constraint.useOrientationConstraint) { try { var oc = constraint.orientationConstraint; var weightedTargetOri = RigMeister2000.ConstraintWeightedTarget.GetWeightedOrientation(oc.weightedTargetJoints, true); foreach (var wtj in oc.weightedTargetJoints) { Handles.color = Color.cyan; Handles.DrawLine(sourcePos, wtj.joint.position); Handles.color = Color.magenta; Handles.SphereCap(-1, wtj.joint.position, wtj.joint.rotation, 0.025f); Handles.ArrowCap(-1, wtj.joint.position, wtj.joint.rotation, 0.1f); } Handles.color = Color.cyan; Handles.SphereCap(-1, sourcePos, weightedTargetOri, 0.025f); Handles.ArrowCap(-1, sourcePos, weightedTargetOri, 0.1f); } catch (System.Exception) { } } if (constraint.useLookAtConstraint) { try { var lac = constraint.lookAtConstraint; var weightedTargetPos = RigMeister2000.ConstraintWeightedTarget.GetWeightedPosition(lac.weightedTargetJoints); var sourceToTarget = weightedTargetPos - sourcePos; var sourceTargetOri = Quaternion.LookRotation(sourceToTarget); Handles.color = ms_axisColor[(int)lac.sourceLookAtAxis]; Handles.ConeCap(-1, sourcePos + sourceToTarget.normalized * 0.080f, sourceTargetOri, 0.0125f); Handles.ArrowCap(-1, sourcePos, sourceTargetOri, 0.1f); Handles.color = ms_axisColor[(int)lac.upSourceAxis]; if (lac.upWorld) { Handles.ArrowCap(-1, sourcePos, Quaternion.LookRotation(Vector3.up), 0.1f); } else { var sourceToUp = lac.upJoint.position - sourcePos; Handles.ArrowCap(-1, sourcePos, Quaternion.LookRotation(sourceToUp), 0.1f); } } catch (System.Exception) {} } } }
void ShowGrid() { if (grid && !Application.isPlaying) { if (Selection.activeTransform == transform) { bool is3D = SceneView.currentDrawingSceneView == null || !SceneView.currentDrawingSceneView.in2DMode; float size = 0.1F * ((moveX + moveY + moveZ) / 3); const float alphaFactor = 1.25F; float alpha = alphaFactor / 2; for (int y = -gridSize; y <= gridSize; y++) { for (int x = -gridSize; x <= gridSize; x++) { if (alpha.Round(0.1) > 0) { // X Squares Handles.lighting = false; Handles.color = new Color(0.1F, 0.25F, 0.75F, alpha); Vector3 offset = new Vector3(x * moveX, y * moveY, 0); Vector3 position = transform.position + offset; position.x = position.x.Round(moveX); position.y = position.y.Round(moveY); position.z = position.z.Round(moveZ); if (showCubes) { if (SceneView.currentDrawingSceneView != null) { if (SceneView.currentDrawingSceneView.camera.WorldPointInView(position)) { Handles.CubeCap(0, position, Quaternion.identity, size); } } else { Handles.CubeCap(0, position, Quaternion.identity, size); } } // X Lines if (showLines) { Handles.color = new Color(0.1F, 0.25F, 0.75F, alpha / 2); if (x == gridSize) { Handles.DrawLine(new Vector3(transform.position.x - offset.x, position.y, position.z), position); } if (y == gridSize) { Handles.DrawLine(new Vector3(position.x, transform.position.y - offset.y, position.z), position); } } if (!is3D) { alpha = 1.5F; } if (is3D || (!is3D && y == 0)) { // Y Squares Handles.color = new Color(0.75F, 0.35F, 0.1F, alpha); offset = new Vector3(x * moveX, 0, y * moveZ); position = transform.position + offset; position.x = position.x.Round(moveX); position.y = position.y.Round(moveY); position.z = position.z.Round(moveZ); if (showCubes) { if (SceneView.currentDrawingSceneView != null) { if (SceneView.currentDrawingSceneView.camera.WorldPointInView(position)) { Handles.CubeCap(0, position, Quaternion.identity, size); } } else { Handles.CubeCap(0, position, Quaternion.identity, size); } } // Y Lines if (showLines) { Handles.color = new Color(0.75F, 0.35F, 0.1F, alpha / 2); if (x == gridSize) { Handles.DrawLine(new Vector3(transform.position.x - offset.x, position.y, position.z), position); } if (y == gridSize) { Handles.DrawLine(new Vector3(position.x, position.y, transform.position.z - offset.z), position); } } } if (is3D || (!is3D && x == 0)) { // Z Squares Handles.color = new Color(0.75F, 0, 0.25F, alpha); offset = new Vector3(0, y * moveY, x * moveZ); position = transform.position + offset; position.x = position.x.Round(moveX); position.y = position.y.Round(moveY); position.z = position.z.Round(moveZ); if (showCubes) { if (SceneView.currentDrawingSceneView != null) { if (SceneView.currentDrawingSceneView.camera.WorldPointInView(position)) { Handles.CubeCap(0, position, Quaternion.identity, size); } } else { Handles.CubeCap(0, position, Quaternion.identity, size); } } // Z Lines if (showLines) { Handles.color = new Color(0.75F, 0, 0.25F, alpha / 2); if (y == gridSize) { Handles.DrawLine(new Vector3(position.x, transform.position.y - offset.y, position.z), position); } if (x == gridSize) { Handles.DrawLine(new Vector3(position.x, position.y, transform.position.z - offset.z), position); } } } } } } SceneView.RepaintAll(); } } }
void UpdateVertexEditing() { var guiEvent = Event.current.type; var mouseRay = Utils.GetSceneViewMouseRay(); var vertex = -1; editObject.ppMesh.GetNearestPoint(mouseRay, out vertex, true); if (vertex != -1) { var p0 = HandleUtility.WorldToGUIPoint(editObject.ppMesh.GetVertexByIndexWorld(vertex)); var p1 = Event.current.mousePosition; var distance = (p0 - p1).sqrMagnitude; if (distance > 30 * 30) { vertex = -1; } } var hoverPoint = guiEvent != EventType.mouseDrag; var handleSelected = GUIUtility.hotControl != 0; if (handleSelected) { editCommand.Reset(); } if (editCommand.IsSet(EditCommand.CommandType.Clear)) { vertexSelection.Clear(); } else if (editCommand.IsSet(EditCommand.CommandType.Add)) { vertexSelection.Add(editCommand.Vertex); } else if (editCommand.IsSet(EditCommand.CommandType.Remove)) { vertexSelection.Remove(editCommand.Vertex); } editCommand.Reset(); if (!Event.current.alt) { if (vertex != -1) { if (guiEvent == EventType.mouseDown) { painting = true; } else if (guiEvent == EventType.mouseUp || guiEvent == EventType.mouseMove) { painting = false; } // adding if (Event.current.shift) { if (painting) { editCommand.Command |= EditCommand.CommandType.Add; editCommand.Vertex = vertex; } } // removing else if (Event.current.control) { if (painting) { editCommand.Command |= EditCommand.CommandType.Remove; editCommand.Vertex = vertex; } } else { if (guiEvent == EventType.mouseDown) { editCommand.Command |= EditCommand.CommandType.Clear; editCommand.Vertex = -1; } if (painting) { editCommand.Command |= EditCommand.CommandType.Add; editCommand.Vertex = vertex; } } } else { if (guiEvent == EventType.mouseDown) { if (!Event.current.shift) { editCommand.Command |= EditCommand.CommandType.Clear; } editCommand.Vertex = -1; multiselectStart = Event.current.mousePosition; multiselecting = true; } } } else { painting = false; multiselecting = false; } if (guiEvent == EventType.mouseUp) { OnMultiselectFinished(); } if (handleSelected) { multiselecting = false; painting = false; } var handleSize = HandleUtility.GetHandleSize(editObject.transform.position) * 0.1f; foreach (var vert in vertexSelection) { Handles.color = handlesColorSelected; Handles.CubeCap(1, editObject.ppMesh.GetVertexByIndexWorld(vert), Quaternion.identity, handleSize); } if (!handleSelected) { if (guiEvent == EventType.mouseUp) { var array = new int[vertexSelection.Count]; vertexSelection.CopyTo(array); oldDragPos = editObject.ppMesh.GetAveragePos(array); editObject.ppMesh.StartUpdateVerticesDelta(vertexSelection, true); if (Tools.pivotRotation == PivotRotation.Local) { if (vertexSelection.Count > 0) { handlesRotation = editObject.ppMesh.GetLocalRotation(vertexSelection); } } else { handlesRotation = Quaternion.identity; } } } if (guiEvent == EventType.mouseUp) { editObject.ppMesh.SaveUndo(); RefreshToolbar(); } var newPos = Handles.PositionHandle(oldDragPos, handlesRotation); if (guiEvent == EventType.mouseDrag && handleSelected) { if (grid.Snap) { newPos = grid.FindClosestGridPointXZ(newPos); } var diff = editObject.ppMesh.Transform.InverseTransformPoint(newPos) - editObject.ppMesh.Transform.InverseTransformPoint(oldDragPos); editObject.ppMesh.UpdateVerticesDelta(diff); editObject.UpdateMesh(); } oldDragPos = newPos; if (!handleSelected && vertex != -1 && hoverPoint && !vertexSelection.Contains(vertex)) { Handles.color = handlesColorHovered; Handles.CubeCap(1, editObject.ppMesh.GetVertexByIndexWorld(vertex), Quaternion.identity, handleSize); } }
//Plane3d dPlane = new Plane3d(); public void OnSceneGUI() { if (spriteDeformerEditor.selectedPoints.Count <= 0) { return; } // dPlane = new Plane3d(spriteDeformerEditor.spriteDeformer.transform.position, spriteDeformerEditor.spriteDeformer.transform.rotation); CurrentTool nextTool = CurrentTool.NONE; float newHandleSize = HandleUtility.GetHandleSize(pos2Dto3D(pivot)); Vector2 newPivotHandle = pivot - oriantDirUp * newHandleSize / 3f; Vector2 newOriantHandle = pivot + oriantDir * newHandleSize * 1.5f; float newScaleStandartDistance = newHandleSize * 1.3f; Vector2 newScaleVerticalHandle = pivot + oriantDirUp * newScaleStandartDistance; Vector2 newScaleHorizontalHandle = pivot + oriantDir * newScaleStandartDistance; Vector2 newRotateHandle = pivot + oriantDirUp * newHandleSize * 1.5f; if (spriteDeformerEditor.currentTool == CurrentTool.NONE) { if (Vector3.Distance(Event.current.mousePosition, pos2DtoScreen(pivot)) < 7f) { nextTool = CurrentTool.MOVE_POINTS; } else { Vector2 l1Screen = pos2DtoScreen(pivot); Vector2 l2Screen = pos2DtoScreen(pivot + oriantDir * newHandleSize); Vector2 l2UpScreen = pos2DtoScreen(pivot + oriantDirUp * newHandleSize); float d = Vector2.Distance(Line.ClosestPointOnSegment(l1Screen, l2Screen, Event.current.mousePosition), Event.current.mousePosition); float dUP = Vector2.Distance(Line.ClosestPointOnSegment(l1Screen, l2UpScreen, Event.current.mousePosition), Event.current.mousePosition); if (Mathf.Min(d, dUP) < 6f) { nextTool = d < dUP ? CurrentTool.MOVE_RIGHT : CurrentTool.MOVE_UP; } else if (Vector2.Distance(pos2DtoScreen(newPivotHandle), Event.current.mousePosition) < 6) { nextTool = CurrentTool.MOVE_PIVOT; } else if (Vector2.Distance(pos2DtoScreen(newScaleHorizontalHandle), Event.current.mousePosition) < 6) { nextTool = CurrentTool.SCALE_HORIZONTAL; calculateLocalPositions(); } else if (Vector2.Distance(pos2DtoScreen(newScaleVerticalHandle), Event.current.mousePosition) < 6) { nextTool = CurrentTool.SCALE_VERTICAL; calculateLocalPositions(); } else if (Vector2.Distance(pos2DtoScreen(newOriantHandle), Event.current.mousePosition) < 6) { nextTool = CurrentTool.ORIANT; } else if (Vector2.Distance(pos2DtoScreen(newRotateHandle), Event.current.mousePosition) < 6) { nextTool = CurrentTool.ROTATE; calculateLocalPositions(); } } pivotDeltaClick = mouse2Dpos - pivot; } if (Event.current.type == EventType.mouseDown && nextTool != CurrentTool.NONE) { spriteDeformerEditor.currentTool = nextTool; } if (spriteDeformerEditor.currentTool == CurrentTool.MOVE_POINTS) { Vector2 newPos = mouse2Dpos - pivotDeltaClick; movePoints(pivot, newPos); pivot = newPos; } if (spriteDeformerEditor.currentTool == CurrentTool.MOVE_RIGHT || spriteDeformerEditor.currentTool == CurrentTool.MOVE_UP) { Vector2 cDir = spriteDeformerEditor.currentTool == CurrentTool.MOVE_RIGHT ? oriantDir : oriantDirUp; Vector2 newPivotPos = Line3d.closestPointInLine(mouse2Dpos - pivotDeltaClick, pivot, pivot + cDir); movePoints(pivot, newPivotPos); pivot = newPivotPos; } if (spriteDeformerEditor.currentTool == CurrentTool.MOVE_PIVOT) { pivot = mouse2Dpos - pivotDeltaClick; } if (spriteDeformerEditor.currentTool == CurrentTool.SCALE_HORIZONTAL || spriteDeformerEditor.currentTool == CurrentTool.SCALE_VERTICAL) { Vector2 lineStart = pivot; Vector2 line = spriteDeformerEditor.currentTool == CurrentTool.SCALE_HORIZONTAL ? oriantDir : oriantDirUp; float t = Vector2.Dot(mouse2Dpos - lineStart, line); if (spriteDeformerEditor.currentTool == CurrentTool.SCALE_HORIZONTAL) { newScaleHorizontalHandle = lineStart + line * t; setPointsFromPointsInPivotLocal(new Vector2(t / newScaleStandartDistance, 1f)); } else { newScaleVerticalHandle = lineStart + line * t; setPointsFromPointsInPivotLocal(new Vector2(1f, t / newScaleStandartDistance)); } } if (spriteDeformerEditor.currentTool == CurrentTool.ORIANT) { Vector2 mlp = mouse2Dpos; oriant = Mathf.Atan2(mlp.y - pivot.y, mlp.x - pivot.x); } if (spriteDeformerEditor.currentTool == CurrentTool.ROTATE) { calculateLocalPositions(); Vector2 mlp = mouse2Dpos; float a = Mathf.Atan2(mlp.y - pivot.y, mlp.x - pivot.x) - Mathf.PI / 2f; setPointsFromPointsInPivotLocal(new Vector2(1f, 1f), a - oriant); oriant = a; } Color overColor = spriteDeformerEditor.colorSets[ColorSet.DEFORMER_TOOL].over; Color standartColor = spriteDeformerEditor.colorSets[ColorSet.DEFORMER_TOOL].standart; Handles.color = nextTool == CurrentTool.MOVE_RIGHT ? overColor : standartColor; List <CurrentTool> candraw = new List <CurrentTool>() { CurrentTool.NONE, CurrentTool.ORIANT, CurrentTool.MOVE_PIVOT, CurrentTool.MOVE_RIGHT, CurrentTool.ROTATE }; if (candraw.Contains(spriteDeformerEditor.currentTool)) { Handles.ArrowCap(15, pos2Dto3D(pivot), spriteDeformerEditor.spriteDeformer.transform.rotation * Quaternion.Euler(0 - oriant * Mathf.Rad2Deg, 90, 0), newHandleSize); } Handles.color = nextTool == CurrentTool.MOVE_UP ? overColor : standartColor; candraw = new List <CurrentTool>() { CurrentTool.NONE, CurrentTool.ORIANT, CurrentTool.MOVE_PIVOT, CurrentTool.MOVE_UP, CurrentTool.ROTATE }; if (candraw.Contains(spriteDeformerEditor.currentTool)) { Handles.ArrowCap(15, pos2Dto3D(pivot), spriteDeformerEditor.spriteDeformer.transform.rotation * Quaternion.Euler(-90 - oriant * Mathf.Rad2Deg, 90, 0), newHandleSize); } Handles.color = nextTool == CurrentTool.MOVE_POINTS ? overColor : standartColor; Handles.CylinderCap(15, pos2Dto3D(pivot), spriteDeformerEditor.spriteDeformer.transform.rotation, newHandleSize / 5f); candraw = new List <CurrentTool>() { CurrentTool.NONE, CurrentTool.ORIANT, CurrentTool.MOVE_PIVOT, CurrentTool.MOVE_PIVOT }; Handles.color = nextTool == CurrentTool.MOVE_PIVOT ? overColor : standartColor; if (candraw.Contains(spriteDeformerEditor.currentTool)) { Handles.SphereCap(0, pos2Dto3D(newPivotHandle), Quaternion.identity, newHandleSize / 10f); } Handles.color = nextTool == CurrentTool.SCALE_HORIZONTAL ? overColor : standartColor; candraw = new List <CurrentTool>() { CurrentTool.NONE, CurrentTool.ORIANT, CurrentTool.MOVE_PIVOT, CurrentTool.SCALE_HORIZONTAL }; if (candraw.Contains(spriteDeformerEditor.currentTool)) { Handles.CubeCap(0, pos2Dto3D(newScaleHorizontalHandle), spriteDeformerEditor.spriteDeformer.transform.rotation * Quaternion.Euler(0, 0, oriant * Mathf.Rad2Deg), newHandleSize / 7f); } Handles.color = nextTool == CurrentTool.SCALE_VERTICAL ? overColor : standartColor; candraw = new List <CurrentTool>() { CurrentTool.NONE, CurrentTool.ORIANT, CurrentTool.MOVE_PIVOT, CurrentTool.SCALE_VERTICAL }; if (candraw.Contains(spriteDeformerEditor.currentTool)) { Handles.CubeCap(0, pos2Dto3D(newScaleVerticalHandle), spriteDeformerEditor.spriteDeformer.transform.rotation * Quaternion.Euler(0, 0, oriant * Mathf.Rad2Deg), newHandleSize / 7f); } Handles.color = nextTool == CurrentTool.ORIANT ? overColor : standartColor; candraw = new List <CurrentTool>() { CurrentTool.NONE, CurrentTool.ORIANT, CurrentTool.MOVE_PIVOT, CurrentTool.MOVE_PIVOT }; if (candraw.Contains(spriteDeformerEditor.currentTool)) { Handles.ConeCap(0, pos2Dto3D(newOriantHandle), Quaternion.LookRotation(pos2Dto3D(newOriantHandle) - pos2Dto3D(pivot)), newHandleSize / 6f); } Handles.color = nextTool == CurrentTool.ROTATE ? overColor : standartColor; candraw = new List <CurrentTool>() { CurrentTool.NONE, CurrentTool.ORIANT, CurrentTool.MOVE_PIVOT, CurrentTool.MOVE_PIVOT, CurrentTool.ROTATE }; if (candraw.Contains(spriteDeformerEditor.currentTool)) { Handles.ConeCap(0, pos2Dto3D(newRotateHandle), Quaternion.LookRotation(pos2Dto3D(newOriantHandle) - pos2Dto3D(pivot)), newHandleSize / 6f); } }
void OnSceneGUI() { var e = Event.current; var controlId = GUIUtility.GetControlID(FocusType.Passive); var terrain = (VoxelTerrain)target; if (e.type == EventType.KeyUp) { if (e.keyCode == KeyCode.LeftAlt) { leftAltDown = false; } } if (leftAltDown && (e.type == EventType.MouseDown || e.type == EventType.MouseUp)) { e.Use(); return; } if (leftAltDown && e.type == EventType.MouseDrag) { var view = SceneView.currentDrawingSceneView; var cam = view.camera; //Debug.Log("Dragging!: " + cam.transform.position + ", " + view.pivot); //cam.transform.RotateAround(view.pivot, Vector3.up, 1.00f); //view.pivot += Vector3.left; //view.rotation *= Quaternion.AngleAxis(1.0f, Vector3.up); //SceneView.lastActiveSceneView.camera. e.Use(); return; } if (e.type == EventType.KeyDown) { var newAlignment = PlaneAlignment.None; var useEvent = false; var index = 0; if (e.keyCode == KeyCode.LeftAlt) { leftAltDown = true; return; } foreach (var planeNormal in planeNormals) { if (index >= Row1Keys.Count) { return; } if (e.keyCode == Row1Keys[index++]) { newAlignment = planeNormal.Key; } } if (newAlignment != PlaneAlignment.None) { createPlane = true; alignment = newAlignment; EditorUtility.SetDirty(terrain); useEvent = true; } index = 0; foreach (var blockType in terrain.BlockTypes) { if (index >= Row2Keys.Count) { return; } if (e.keyCode == Row2Keys[index]) { selectedBlockType = (ushort)index; useEvent = true; } index++; } index = 0; foreach (var meshShape in meshShapeTypes) { if (index >= Row3Keys.Count) { return; } if (e.keyCode == Row3Keys[index++]) { selectedMeshShape = meshShape; useEvent = true; } } index = 0; foreach (var rotation in rotationTypes) { if (index >= Row4Keys.Count) { return; } if (e.keyCode == Row4Keys[index++]) { selectedRotation = rotation; useEvent = true; } } if (e.keyCode == KeyCode.Space) { useEvent = true; var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); RaycastHit rayHit; if (Physics.Raycast(ray, out rayHit)) { var cursorPosition = rayHit.point - rayHit.normal * 0.5f; tileCursorPosition = new Vector3(Mathf.Round(cursorPosition.x), Mathf.Round(cursorPosition.y), Mathf.Round(cursorPosition.z)); } } if (useEvent) { GUIUtility.hotControl = controlId; EditorUtility.SetDirty(terrain); e.Use(); } } CreatePlanes(terrain); if ((e.type == EventType.MouseDown || e.type == EventType.MouseDrag) && e.button == 0) { if (paintBlockType || paintShape) { GUIUtility.hotControl = controlId; var x = (int)tileCursorPosition.x; var y = (int)tileCursorPosition.y; var z = (int)tileCursorPosition.z; if (paintMode == PaintModeType.Single) { PaintAtPoint(terrain, x, y, z); SaveAllDataDirty(terrain); } else if (paintMode == PaintModeType.Rectangle && e.type == EventType.MouseDown) { mouseDownTileCursorPosition = tileCursorPosition; } EditorUtility.SetDirty(terrain); } if (e.type == EventType.MouseDown) { e.Use(); } } if (e.type == EventType.MouseUp && e.button == 0) { if (mouseDownTileCursorPosition.HasValue && paintMode == PaintModeType.Rectangle) { var startX = (int)Mathf.Min(tileCursorPosition.x, mouseDownTileCursorPosition.Value.x); var startY = (int)Mathf.Min(tileCursorPosition.y, mouseDownTileCursorPosition.Value.y); var startZ = (int)Mathf.Min(tileCursorPosition.z, mouseDownTileCursorPosition.Value.z); var endX = (int)Mathf.Max(tileCursorPosition.x, mouseDownTileCursorPosition.Value.x); var endY = (int)Mathf.Max(tileCursorPosition.y, mouseDownTileCursorPosition.Value.y); var endZ = (int)Mathf.Max(tileCursorPosition.z, mouseDownTileCursorPosition.Value.z); for (var z = startZ; z <= endZ; z++) { for (var y = startY; y <= endY; y++) { for (var x = startX; x <= endX; x++) { PaintAtPoint(terrain, x, y, z); } } } SaveAllDataDirty(terrain); EditorUtility.SetDirty(terrain); mouseDownTileCursorPosition = null; } } if (e.type == EventType.MouseMove || e.type == EventType.MouseDrag) { float rayDistance; var ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); if (plane.Raycast(ray, out rayDistance)) { cursorPosition = ray.GetPoint(rayDistance); var newCursor = new Vector3(Mathf.Round(cursorPosition.x), Mathf.Round(cursorPosition.y), Mathf.Round(cursorPosition.z)); if (alignment == PlaneAlignment.X) { tileCursorPosition = new Vector3(newCursor.x, tileCursorPosition.y, tileCursorPosition.z); } else if (alignment == PlaneAlignment.Y) { tileCursorPosition = new Vector3(tileCursorPosition.x, newCursor.y, tileCursorPosition.z); } else if (alignment == PlaneAlignment.Z) { tileCursorPosition = new Vector3(tileCursorPosition.x, tileCursorPosition.y, newCursor.z); } else { tileCursorPosition = newCursor; } SceneView.RepaintAll(); } } Handles.color = new Color(0.35f, 0.4f, 0.8f, 0.5f); Handles.CubeCap(0, tileCursorPosition, Quaternion.identity, 1.0f); if (mouseDownTileCursorPosition.HasValue) { Handles.color = new Color(0.4f, 0.8f, 0.35f, 0.5f); Handles.CubeCap(0, mouseDownTileCursorPosition.Value, Quaternion.identity, 1.0f); } var xColour = (alignment == PlaneAlignment.XY || alignment == PlaneAlignment.XZ || alignment == PlaneAlignment.X) ? Color.red : new Color(1, 1, 1, 0.5f); var yColour = (alignment == PlaneAlignment.YZ || alignment == PlaneAlignment.XY || alignment == PlaneAlignment.Y) ? Color.green : new Color(1, 1, 1, 0.5f); var zColour = (alignment == PlaneAlignment.XZ || alignment == PlaneAlignment.YZ || alignment == PlaneAlignment.Z) ? Color.blue : new Color(1, 1, 1, 0.5f); Handles.color = xColour; Handles.DrawLine(tileCursorPosition + Vector3.left * 100, tileCursorPosition + Vector3.right * 100); Handles.color = yColour; Handles.DrawLine(tileCursorPosition + Vector3.up * 100, tileCursorPosition + Vector3.down * 100); Handles.color = zColour; Handles.DrawLine(tileCursorPosition + Vector3.forward * 100, tileCursorPosition + Vector3.back * 100); var screenPos = Camera.current.WorldToScreenPoint(tileCursorPosition); Handles.BeginGUI(); GUI.Label(new Rect(screenPos.x, Screen.height - screenPos.y, 100, 40), string.Format("({0}, {1}, {2})", tileCursorPosition.x, tileCursorPosition.y, tileCursorPosition.z)); Handles.EndGUI(); }
public void OnSceneGUI() { // Set Targer MapEditor t = (MapEditor)target; if (t == null) { return; } // Chunk Handle EditorGUI.BeginChangeCheck(); Vector3 chunkPos = Handles.PositionHandle(new Vector3(t.chunk.x, 1, t.chunk.z), Quaternion.identity); if (EditorGUI.EndChangeCheck()) { bool change = false; if (t.chunk.x != (int)chunkPos.x) { t.chunk.x = (int)chunkPos.x; change = true; } if (t.chunk.z != (int)chunkPos.z) { t.chunk.z = (int)chunkPos.z; change = true; } if (change) { t.UpdateChunk(); } } // Edit mode if (!drag) { Ray ray = HandleUtility.GUIPointToWorldRay(Event.current.mousePosition); RaycastHit hit = new RaycastHit(); if (Physics.Raycast(ray, out hit, 1000.0f)) { Color color = new Color(0, 0, 1, 0.5f); Handles.color = color; dragGUIPos = t.GetBlockPositionFromWorldPoint(hit.point); Handles.CubeCap(0, dragGUIPos, Quaternion.identity, 1f); if ((Event.current.type == EventType.MouseDown && Event.current.button == 0)) { drag = true; dragGUIPos = t.SelectCell(hit.point); mousePos.x = Event.current.mousePosition.x; mousePos.y = Event.current.mousePosition.y; dragValue.y = dragGUIPos.y; Event.current.type = EventType.used; Cursor.lockState = CursorLockMode.Confined; } } } else { //Handles Color color = new Color(0, 0, 1, 0.5f); Handles.color = color; Handles.CubeCap(0, dragGUIPos, Quaternion.identity, 1f); // GUI Handles.BeginGUI(); Vector2 guiPoint = HandleUtility.WorldToGUIPoint(dragGUIPos); Rect r = new Rect(guiPoint.x - 50, guiPoint.y - 50, 100, 100); dragValue.x = GUI.HorizontalSlider(r, dragValue.x, 0.0F, 10.0F); dragValue.y = GUI.VerticalSlider(r, dragValue.y, 0.0F, 10.0F); Handles.EndGUI(); // Drag if ((Event.current.type == EventType.MouseDrag && Event.current.button == 0)) { float deltaX = (Event.current.mousePosition.x - mousePos.x) * 0.02f; float deltaY = (Event.current.mousePosition.y - mousePos.y) * 0.02f; dragValue.x += deltaX; dragValue.y -= deltaY; dragValue = t.EditCell(dragValue); mousePos.x = Event.current.mousePosition.x; mousePos.y = Event.current.mousePosition.y; } // Stop if ((Event.current.type == EventType.MouseUp && Event.current.button == 0)) { drag = false; Event.current.type = EventType.used; Cursor.lockState = CursorLockMode.None; } } if ((Event.current.type == EventType.MouseUp && Event.current.button == 0)) { drag = false; Cursor.lockState = CursorLockMode.None; } if ((Event.current.type == EventType.MouseMove)) { SceneView.RepaintAll(); } }
private void DrawLinks() { if (linkTool_UnlinkMode) { foreach (List <LinkCacheEntry> cache in linkCache.Values) { foreach (LinkCacheEntry n in cache) { if (selLinkIdx == n.idx1) { Handles.color = Color.red; } else { Handles.color = col[n.data]; } if (selLinkIdx < 0 || selLinkIdx == n.idx1) { Handles.DrawLine(mapnav.grid[n.idx1].position, mapnav.grid[n.idx2].position); float baseSize = HandleUtility.GetHandleSize(mapnav.grid[n.idx1].position); if (Handles.Button(mapnav.grid[n.idx1].position, Quaternion.identity, baseSize * 0.2f, baseSize * 0.1f, DrawNodeLinkButton)) { if (selLinkIdx == n.idx1) { selLinkIdx = -1; } else { selLinkIdx = n.idx1; } SceneView.RepaintAll(); } Handles.color = col[n.data]; if (selLinkIdx == n.idx1) { if (Handles.Button(mapnav.grid[n.idx2].position, Quaternion.identity, baseSize * 0.2f, baseSize * 0.1f, DrawNodeLinkButton)) { if (!unlinkSelection.Contains(n)) { unlinkSelection.Add(n); } selLinkIdx = -1; Repaint(); SceneView.RepaintAll(); } } else { Handles.CubeCap(0, mapnav.grid[n.idx2].position, Quaternion.identity, baseSize * 0.1f); } } } } } else { foreach (List <LinkCacheEntry> cache in linkCache.Values) { foreach (LinkCacheEntry n in cache) { Handles.color = col[n.data]; Handles.DrawLine(mapnav.grid[n.idx1].position, mapnav.grid[n.idx2].position); float baseSize = HandleUtility.GetHandleSize(mapnav.grid[n.idx1].position); Handles.CubeCap(0, mapnav.grid[n.idx1].position, Quaternion.identity, baseSize * 0.1f); Handles.CubeCap(0, mapnav.grid[n.idx2].position, Quaternion.identity, baseSize * 0.1f); } } } }