forked from Unity-Technologies/UnityCsReference
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHandleUtility.cs
More file actions
2145 lines (1836 loc) · 90.3 KB
/
Copy pathHandleUtility.cs
File metadata and controls
2145 lines (1836 loc) · 90.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Unity C# reference source
// Copyright (c) Unity Technologies. For terms of use, see
// https://unity3d.com/legal/licenses/Unity_Reference_Only_License
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.Profiling;
using UnityEngine;
using UnityEngine.Internal;
using UnityEngine.Rendering;
using UnityEngine.Scripting;
using UnityEditor.SceneManagement;
using UnityObject = UnityEngine.Object;
using System.Linq;
using Unity.Collections;
using Unity.Collections.LowLevel.Unsafe;
using UnityEngine.Bindings;
namespace UnityEditor
{
public enum RenderPickingType
{
RenderFromIgnoreSet,
RenderFromFilterSet
}
public readonly struct RenderPickingArgs
{
public int pickingIndex { get; }
public RenderPickingType renderPickingType { get; }
public IReadOnlyCollection<GameObject> renderObjectSet { get; }
internal RenderPickingArgs(int pickingIndex, RenderPickingType renderPickingType, HashSet<GameObject> renderObjectSet)
{
this.pickingIndex = pickingIndex;
this.renderPickingType = renderPickingType;
this.renderObjectSet = renderObjectSet;
}
public bool RenderObjectSetContains(GameObject go)
=> renderObjectSet != null && ((HashSet<GameObject>)renderObjectSet).Contains(go);
public bool NeedToRenderForPicking(GameObject go)
{
var contained = RenderObjectSetContains(go);
return renderPickingType == RenderPickingType.RenderFromFilterSet ? contained : !contained;
}
}
public readonly struct RenderPickingResult
{
public int renderedPickingIndexCount { get; }
public HandleUtility.ResolvePickingCallback resolver { get; }
public HandleUtility.ResolvePickingWithWorldPositionCallback resolverWithWorldPos { get; }
public static readonly RenderPickingResult NoOperation = default;
public RenderPickingResult(int renderedPickingIndexCount, HandleUtility.ResolvePickingCallback resolver)
{
if (renderedPickingIndexCount < 0)
throw new ArgumentOutOfRangeException(nameof(renderedPickingIndexCount), $"The value ({renderedPickingIndexCount}) must not be negative");
if (resolver == null)
throw new ArgumentNullException(nameof(resolver));
this.renderedPickingIndexCount = renderedPickingIndexCount;
this.resolver = resolver;
this.resolverWithWorldPos = null;
}
public RenderPickingResult(int renderedPickingIndexCount, HandleUtility.ResolvePickingWithWorldPositionCallback resolver)
{
if (renderedPickingIndexCount < 0)
throw new ArgumentOutOfRangeException(nameof(renderedPickingIndexCount), $"The value ({renderedPickingIndexCount}) must not be negative");
if (resolver == null)
throw new ArgumentNullException(nameof(resolver));
this.renderedPickingIndexCount = renderedPickingIndexCount;
this.resolverWithWorldPos = resolver;
this.resolver = null;
}
}
// Helper functions for Scene View style 3D GUI
public sealed partial class HandleUtility
{
// Helper function for doing arrows.
public static float CalcLineTranslation(Vector2 src, Vector2 dest, Vector3 srcPosition, Vector3 constraintDir)
{
// Apply handle matrix
srcPosition = Handles.matrix.MultiplyPoint(srcPosition);
constraintDir = Handles.matrix.MultiplyVector(constraintDir);
// The constrained direction is facing towards the camera, THATS BAD when the handle is close to the camera
// The srcPosition goes through to the other side of the camera
float invert = 1.0F;
Vector3 cameraForward = Camera.current == null ? Vector3.forward : Camera.current.transform.forward;
if (Vector3.Dot(constraintDir, cameraForward) < 0.0F)
invert = -1.0F;
// Ok - Get the parametrization of the line
// p1 = src position, p2 = p1 + ConstraintDir.
// we then parametrise the perpendicular position of dest into the line (p1-p2)
Vector3 cd = constraintDir;
cd.y = -cd.y;
Camera cam = Camera.current;
// if camera is null, then we are drawing in OnGUI, where y-coordinate goes top-to-bottom
Vector2 p1 = cam == null
? Vector2.Scale(srcPosition, new Vector2(1f, -1f))
: EditorGUIUtility.PixelsToPoints(cam.WorldToScreenPoint(srcPosition));
Vector2 p2 = cam == null
? Vector2.Scale(srcPosition + constraintDir * invert, new Vector2(1f, -1f))
: EditorGUIUtility.PixelsToPoints(cam.WorldToScreenPoint(srcPosition + constraintDir * invert));
Vector2 p3 = dest;
Vector2 p4 = src;
if (p1 == p2)
return 0;
p3.y = -p3.y;
p4.y = -p4.y;
float t0 = GetParametrization(p4, p1, p2);
float t1 = GetParametrization(p3, p1, p2);
float output = (t1 - t0) * invert;
return output;
}
internal static float GetParametrization(Vector2 x0, Vector2 x1, Vector2 x2)
{
return -(Vector2.Dot(x1 - x0, x2 - x1) / (x2 - x1).sqrMagnitude);
}
// This limits the "shoot off into infinity" factor when the cursor ray and constraint are near parallel.
// Increase this value to more conservatively restrict movement, lower to allow more extreme values.
// Ex, with a camera roughly 30 degrees to the handle a value of .1 restricts translation to ~1500m, whereas a
// value of .01 will allow closer to 50000 units of movement.
const float k_MinRayConstraintDot = .05f;
// constraintOrigin and constraintDir are expected to be in Handle space (ie, origin and direction are
// pre-multiplied by the Handles.matrix)
internal static bool CalcPositionOnConstraint(Camera camera, Vector2 guiPosition, Vector3 constraintOrigin, Vector3 constraintDir, out Vector3 position)
{
if (CalcParamOnConstraint(camera, guiPosition, constraintOrigin, constraintDir, out float pointOnLineParam))
{
position = constraintOrigin + constraintDir * pointOnLineParam;
return true;
}
position = Vector3.zero;
return false;
}
internal static bool CalcParamOnConstraint(Camera camera, Vector2 guiPosition, Vector3 constraintOrigin, Vector3 constraintDir, out float parameterization)
{
Vector3 constraintToCameraTangent = Vector3.Cross(constraintDir, camera.transform.position - constraintOrigin);
Vector3 constraintPlaneNormal = Vector3.Cross(constraintDir, constraintToCameraTangent);
Plane plane = new Plane(constraintPlaneNormal, constraintOrigin);
var ray = GUIPointToWorldRay(guiPosition);
if (Vector3.Dot(ray.direction, plane.normal) > k_MinRayConstraintDot && plane.Raycast(ray, out float distance))
{
var pointOnPlane = ray.GetPoint(distance);
parameterization = PointOnLineParameter(pointOnPlane, constraintOrigin, constraintDir);
return !float.IsInfinity(parameterization);
}
parameterization = 0f;
return false;
}
// Returns the parameter for the projection of the /point/ on the given line
public static float PointOnLineParameter(Vector3 point, Vector3 linePoint, Vector3 lineDirection)
{
return (Vector3.Dot(lineDirection, (point - linePoint))) / lineDirection.sqrMagnitude;
}
// Project /point/ onto a line.
public static Vector3 ProjectPointLine(Vector3 point, Vector3 lineStart, Vector3 lineEnd)
{
Vector3 relativePoint = point - lineStart;
Vector3 lineDirection = lineEnd - lineStart;
float length = lineDirection.magnitude;
Vector3 normalizedLineDirection = lineDirection;
if (length > .000001f)
normalizedLineDirection /= length;
float dot = Vector3.Dot(normalizedLineDirection, relativePoint);
dot = Mathf.Clamp(dot, 0.0F, length);
return lineStart + normalizedLineDirection * dot;
}
// Calculate distance between a point and a line.
public static float DistancePointLine(Vector3 point, Vector3 lineStart, Vector3 lineEnd)
{
return Vector3.Magnitude(ProjectPointLine(point, lineStart, lineEnd) - point);
}
// Get standard acceleration for dragging values (RO).
public static float acceleration { get { return NumericFieldDraggerUtility.Acceleration(Event.current.shift, Event.current.alt); } }
// Get nice mouse delta to use for dragging a float value (RO).
public static float niceMouseDelta { get { return NumericFieldDraggerUtility.NiceDelta(Event.current.delta, acceleration); } }
// Get nice mouse delta to use for zooming (RO).
public static float niceMouseDeltaZoom
{
get
{
Vector2 d = -Event.current.delta;
// Decide which direction the mouse delta goes.
// Problem is that when the user zooms horizontal and vertical, it can jitter back and forth.
// So we only update from which axis we pick the sign if x and y
// movement is not very close to each other
if (Mathf.Abs(Mathf.Abs(d.x) - Mathf.Abs(d.y)) / Mathf.Max(Mathf.Abs(d.x), Mathf.Abs(d.y)) > .1f)
{
if (Mathf.Abs(d.x) > Mathf.Abs(d.y))
s_UseYSignZoom = false;
else
s_UseYSignZoom = true;
}
if (s_UseYSignZoom)
return Mathf.Sign(d.y) * d.magnitude * acceleration;
return Mathf.Sign(d.x) * d.magnitude * acceleration;
}
}
static bool s_UseYSignZoom;
// Pixel distance from mouse pointer to line.
public static float DistanceToLine(Vector3 p1, Vector3 p2)
{
p1 = WorldToGUIPoint(p1);
p2 = WorldToGUIPoint(p2);
Vector2 point = Event.current.mousePosition;
return DistanceToLineInternal(point, p1, p2);
}
internal static float DistanceToLineInternal(Vector3 point, Vector3 p1, Vector3 p2)
{
float retval = DistancePointLine(point, p1, p2);
if (retval < 0)
retval = 0.0f;
return retval;
}
// Pixel distance from mouse pointer to camera facing circle.
public static float DistanceToCircle(Vector3 position, float radius)
{
Vector2 screenCenter = WorldToGUIPoint(position);
Camera cam = Camera.current;
if (cam)
{
var screenEdge = WorldToGUIPoint(position + cam.transform.right * radius);
radius = (screenCenter - screenEdge).magnitude;
}
float dist = (screenCenter - Event.current.mousePosition).magnitude;
if (dist < radius)
return 0;
return dist - radius;
}
// Pixel distance from mouse pointer to camera facing circle.
public static float DistanceToCircle(CameraProjectionCache projection, Vector3 position, float radius)
{
Vector2 screenCenter = projection.WorldToGUIPoint(position);
Camera cam = Camera.current;
if (cam)
{
var screenEdge = projection.WorldToGUIPoint(position + cam.transform.right * radius);
radius = (screenCenter - screenEdge).magnitude;
}
float dist = (screenCenter - Event.current.mousePosition).magnitude;
if (dist < radius)
return 0;
return dist - radius;
}
// Pixel distance from mouse pointer to cone projection on screen
static ProfilerMarker s_DistanceToConeMarker = new ProfilerMarker("Handles.DistanceToCone");
static readonly Vector3[] s_DistanceToConePoints = new Vector3[7];
public static float DistanceToCone(Vector3 position, Quaternion rotation, float size)
{
using (s_DistanceToConeMarker.Auto())
{
// our handles cone mesh is along Z axis:
// base at Z=-0.5 with radius 0.4, and apex at Z=0.7
var baseZ = -0.5f * size;
var apexZ = 0.7f * size;
var baseR = 0.4f * size;
// approximate the cone with a six-sided base
var baseR60x = baseR * 0.5f; // cos 60
var baseR60y = baseR * 0.866f; // sin 60
var mat = Matrix4x4.TRS(position, rotation, Vector3.one);
s_DistanceToConePoints[0] = mat.MultiplyPoint(new Vector3(0, 0, apexZ));
s_DistanceToConePoints[1] = mat.MultiplyPoint(new Vector3(+baseR, 0, baseZ));
s_DistanceToConePoints[2] = mat.MultiplyPoint(new Vector3(-baseR, 0, baseZ));
s_DistanceToConePoints[3] = mat.MultiplyPoint(new Vector3(+baseR60x, +baseR60y, baseZ));
s_DistanceToConePoints[4] = mat.MultiplyPoint(new Vector3(-baseR60x, +baseR60y, baseZ));
s_DistanceToConePoints[5] = mat.MultiplyPoint(new Vector3(+baseR60x, -baseR60y, baseZ));
s_DistanceToConePoints[6] = mat.MultiplyPoint(new Vector3(-baseR60x, -baseR60y, baseZ));
return DistanceToPointCloudConvexHull(s_DistanceToConePoints);
}
}
// Pixel distance from mouse pointer to cube projection on screen
static ProfilerMarker s_DistanceToCubeMarker = new ProfilerMarker("Handles.DistanceToCube");
static readonly Vector3[] s_DistanceToCubePoints = new Vector3[8];
public static float DistanceToCube(Vector3 position, Quaternion rotation, float size)
{
using (s_DistanceToCubeMarker.Auto())
{
var s = size * 0.5f;
var mat = Matrix4x4.TRS(position, rotation, Vector3.one);
s_DistanceToCubePoints[0] = mat.MultiplyPoint(new Vector3(+s, +s, +s));
s_DistanceToCubePoints[1] = mat.MultiplyPoint(new Vector3(-s, +s, +s));
s_DistanceToCubePoints[2] = mat.MultiplyPoint(new Vector3(+s, -s, +s));
s_DistanceToCubePoints[3] = mat.MultiplyPoint(new Vector3(-s, -s, +s));
s_DistanceToCubePoints[4] = mat.MultiplyPoint(new Vector3(+s, +s, -s));
s_DistanceToCubePoints[5] = mat.MultiplyPoint(new Vector3(-s, +s, -s));
s_DistanceToCubePoints[6] = mat.MultiplyPoint(new Vector3(+s, -s, -s));
s_DistanceToCubePoints[7] = mat.MultiplyPoint(new Vector3(-s, -s, -s));
return DistanceToPointCloudConvexHull(s_DistanceToCubePoints);
}
}
// Pixel distance from mouse pointer to a rectangle on screen
static Vector3[] s_Points = { Vector3.zero, Vector3.zero, Vector3.zero, Vector3.zero, Vector3.zero };
public static float DistanceToRectangle(Vector3 position, Quaternion rotation, float size)
{
return DistanceToRectangleInternal(position, rotation, new Vector2(size, size));
}
// Pixel distance from mouse pointer to a rectangle on screen.
// The method is stable in pixel space but fails when one or more corners of the rectangle is behind the camera.
internal static float DistanceToRectangleInternal(Vector3 position, Quaternion rotation, Vector2 size)
{
Vector3 sideways = rotation * new Vector3(size.x, 0, 0);
Vector3 up = rotation * new Vector3(0, size.y, 0);
s_Points[0] = WorldToGUIPoint(position + sideways + up);
s_Points[1] = WorldToGUIPoint(position + sideways - up);
s_Points[2] = WorldToGUIPoint(position - sideways - up);
s_Points[3] = WorldToGUIPoint(position - sideways + up);
s_Points[4] = s_Points[0];
Vector2 pos = Event.current.mousePosition;
bool oddNodes = false;
int j = 4;
for (int i = 0; i < 5; i++)
{
if ((s_Points[i].y > pos.y) != (s_Points[j].y > pos.y))
{
if (pos.x < (s_Points[j].x - s_Points[i].x) * (pos.y - s_Points[i].y) / (s_Points[j].y - s_Points[i].y) + s_Points[i].x)
{
oddNodes = !oddNodes;
}
}
j = i;
}
if (!oddNodes)
{
// Distance to closest edge (not so fast)
float closestDist = -1f;
j = 1;
for (int i = 0; i < 4; i++)
{
var dist = DistancePointToLineSegment(pos, s_Points[i], s_Points[j++]);
if (dist < closestDist || closestDist < 0)
closestDist = dist;
}
return closestDist;
}
return 0;
}
// Pixel distance from mouse pointer to a rectangle on screen.
// Tests if mouse ray intersects the rectangle performed in world space first,
// then the distance between nearest point on the rectangle and mouse position calculated in pixel space.
// This method is more stable than DistanceToRectangleInternal for cases when one or more corners of the rectangle is behind the camera.
// But at the same time it is less stable than DistanceToRectangleInternal in pixel space when the rectangle plane is parallel to cameras forward direction.
internal static float DistanceToRectangleInternalWorldSpace(Vector3 position, Quaternion rotation, Vector2 size)
{
Quaternion invRotation = Quaternion.Inverse(rotation);
Ray ray = GUIPointToWorldRay(Event.current.mousePosition);
ray.origin = invRotation * (ray.origin - position);
ray.direction = invRotation * ray.direction;
Plane plane = new Plane(Vector3.forward, Vector3.zero);
float enter;
if (plane.Raycast(ray, out enter))
{
Vector3 hitPoint = ray.GetPoint(enter);
Vector3 d = new Vector3(
Mathf.Max(Mathf.Abs(hitPoint.x) - size.x, 0.0f) * Mathf.Sign(hitPoint.x),
Mathf.Max(Mathf.Abs(hitPoint.y) - size.y, 0.0f) * Mathf.Sign(hitPoint.y),
0.0f);
Vector3 nearestPoint = hitPoint - d;
hitPoint = rotation * hitPoint + position;
nearestPoint = rotation * nearestPoint + position;
return Vector2.Distance(WorldToGUIPoint(hitPoint), WorldToGUIPoint(nearestPoint));
}
return float.PositiveInfinity;
}
internal static float DistanceToDiamond(Vector3 position, Quaternion rotation, float size)
{
return DistanceToDiamondInternal(position, rotation, size, Event.current.mousePosition);
}
internal static float DistanceToDiamondInternal(Vector3 position, Quaternion rotation, float size, Vector2 mousePosition)
{
Vector3 sideways = rotation * new Vector3(size, 0, 0);
Vector3 up = rotation * new Vector3(0, size, 0);
s_Points[0] = WorldToGUIPoint(position + sideways);
s_Points[1] = WorldToGUIPoint(position - up);
s_Points[2] = WorldToGUIPoint(position - sideways);
s_Points[3] = WorldToGUIPoint(position + up);
s_Points[4] = s_Points[0];
Vector2 pos = mousePosition;
bool oddNodes = false;
int j = 4;
for (int i = 0; i < 5; i++)
{
if ((s_Points[i].y > pos.y) != (s_Points[j].y > pos.y))
{
if (pos.x < (s_Points[j].x - s_Points[i].x) * (pos.y - s_Points[i].y) / (s_Points[j].y - s_Points[i].y) + s_Points[i].x)
{
oddNodes = !oddNodes;
}
}
j = i;
}
if (!oddNodes)
{
// Distance to closest edge (not so fast)
float dist, closestDist = -1f;
j = 1;
for (int i = 0; i < 4; i++)
{
dist = DistancePointToLineSegment(pos, s_Points[i], s_Points[j++]);
if (dist < closestDist || closestDist < 0)
closestDist = dist;
}
return closestDist;
}
return 0;
}
// Distance from a point /p/ in 2d to a line defined by two s_Points /a/ and /b/
public static float DistancePointToLine(Vector2 p, Vector2 a, Vector2 b)
{
return Mathf.Abs((b.x - a.x) * (a.y - p.y) - (a.x - p.x) * (b.y - a.y)) / (b - a).magnitude;
}
// Distance from a point /p/ in 2d to a line segment defined by two s_Points /a/ and /b/
public static float DistancePointToLineSegment(Vector2 p, Vector2 a, Vector2 b)
{
float l2 = (b - a).sqrMagnitude; // i.e. |b-a|^2 - avoid a sqrt
if (l2 == 0.0)
return (p - a).magnitude; // a == b case
float t = Vector2.Dot(p - a, b - a) / l2;
if (t < 0.0)
return (p - a).magnitude; // Beyond the 'a' end of the segment
if (t > 1.0)
return (p - b).magnitude; // Beyond the 'b' end of the segment
Vector2 projection = a + t * (b - a); // Projection falls on the segment
return (p - projection).magnitude;
}
// Pixel distance from mouse pointer to a 3D disc.
public static float DistanceToDisc(Vector3 center, Vector3 normal, float radius)
{
Vector3 tangent = Vector3.Cross(normal, Vector3.up);
if (tangent.sqrMagnitude < .001f)
tangent = Vector3.Cross(normal, Vector3.right);
return DistanceToArc(center, normal, tangent, 360, radius);
}
// Get the nearest 3D point.
public static Vector3 ClosestPointToDisc(Vector3 center, Vector3 normal, float radius)
{
Vector3 tangent = Vector3.Cross(normal, Vector3.up);
if (tangent.sqrMagnitude < .001f)
tangent = Vector3.Cross(normal, Vector3.right);
return ClosestPointToArc(center, normal, tangent, 360, radius);
}
static Vector3[] m_ArcPointsBuffer = new Vector3[60];
// Pixel distance from mouse pointer to a 3D section of a disc.
public static float DistanceToArc(Vector3 center, Vector3 normal, Vector3 from, float angle, float radius)
{
Handles.SetDiscSectionPoints(m_ArcPointsBuffer, center, normal, from, angle, radius);
return DistanceToPolyLine(m_ArcPointsBuffer, false, out _);
}
// Get the nearest 3D point.
public static Vector3 ClosestPointToArc(Vector3 center, Vector3 normal, Vector3 from, float angle, float radius)
{
Handles.SetDiscSectionPoints(m_ArcPointsBuffer, center, normal, from, angle, radius);
return ClosestPointToPolyLine(m_ArcPointsBuffer);
}
// Pixel distance from mouse pointer to a polyline.
public static float DistanceToPolyLine(params Vector3[] points)
{
Matrix4x4 handleMatrix = Handles.matrix;
CameraProjectionCache cam = new CameraProjectionCache(Camera.current);
Vector2 mouse = Event.current.mousePosition;
Vector2 p1 = cam.WorldToGUIPoint(handleMatrix.MultiplyPoint3x4(points[0]));
Vector2 p2 = cam.WorldToGUIPoint(handleMatrix.MultiplyPoint3x4(points[1]));
float dist = DistanceToLineInternal(mouse, p1, p2);
for (int i = 2; i < points.Length; i++)
{
p1 = p2;
p2 = cam.WorldToGUIPoint(handleMatrix.MultiplyPoint3x4(points[i]));
float d = DistanceToLineInternal(mouse, p1, p2);
if (d < dist)
dist = d;
}
return dist;
}
// Pixel distance from mouse pointer to a polyline.
internal static float DistanceToPolyLine(Vector3[] points, bool loop, out int index)
{
Matrix4x4 handleMatrix = Handles.matrix;
CameraProjectionCache cam = new CameraProjectionCache(Camera.current);
Vector2 mouse = Event.current.mousePosition;
Vector2 p1 = cam.WorldToGUIPoint(handleMatrix.MultiplyPoint3x4(points[0]));
Vector2 p2 = cam.WorldToGUIPoint(handleMatrix.MultiplyPoint3x4(points[1]));
float dist = DistanceToLineInternal(mouse, p1, p2);
index = 0;
for (int i = 2, c = points.Length; i < (loop ? c + 1 : c); i++)
{
p1 = p2;
p2 = cam.WorldToGUIPoint(handleMatrix.MultiplyPoint3x4(points[i % c]));
float d = DistanceToLineInternal(mouse, p1, p2);
if (d < dist)
{
index = i - 1;
dist = d;
}
}
return dist;
}
// Get the nearest 3D point.
public static Vector3 ClosestPointToPolyLine(params Vector3[] vertices)
{
float dist = DistanceToLine(vertices[0], vertices[1]);
int nearest = 0;// Which segment we're closest to
for (int i = 2; i < vertices.Length; i++)
{
float d = DistanceToLine(vertices[i - 1], vertices[i]);
if (d < dist)
{
dist = d;
nearest = i - 1;
}
}
Vector3 lineStart = vertices[nearest];
Vector3 lineEnd = vertices[nearest + 1];
Vector2 relativePoint = Event.current.mousePosition - WorldToGUIPoint(lineStart);
Vector2 lineDirection = WorldToGUIPoint(lineEnd) - WorldToGUIPoint(lineStart);
float length = lineDirection.magnitude;
float dot = Vector3.Dot(lineDirection, relativePoint);
if (length > .000001f)
dot /= length * length;
dot = Mathf.Clamp01(dot);
return Vector3.Lerp(lineStart, lineEnd, dot);
}
static float CalcPointSide(Vector2 l0, Vector2 l1, Vector2 point)
{
return (l1.y - l0.y) * (point.x - l0.x) - (l1.x - l0.x) * (point.y - l0.y);
}
static float DistancePointToConvexHull(Vector2 p, List<Vector2> hull)
{
var distance = float.PositiveInfinity;
if (hull == null || hull.Count == 0)
return distance;
var inside = hull.Count > 1;
var sideSign = 0;
for (var i = 0; i < hull.Count; ++i)
{
// get the line segment
var j = i == 0 ? hull.Count - 1 : i - 1;
var pt1 = hull[i];
var pt2 = hull[j];
// for point to be inside the hull, "side"
// signs must be the same for all edges.
var thisSide = CalcPointSide(pt1, pt2, p);
var thisSideSign = thisSide >= 0 ? 1 : -1;
if (sideSign == 0)
sideSign = thisSideSign;
else if (thisSideSign != sideSign)
inside = false;
// get minimum distance to each segment
var thisDistance = DistancePointToLineSegment(p, pt1, pt2);
distance = Mathf.Min(distance, thisDistance);
}
if (inside)
distance = 0;
return distance;
}
static void RemoveInsidePoints(int countLimit, Vector2 pt, List<Vector2> hull)
{
while (hull.Count >= countLimit && CalcPointSide(hull[hull.Count - 2], hull[hull.Count - 1], pt) <= 0)
hull.RemoveAt(hull.Count - 1);
}
// Note: .z components of input points are ignored; result is a 2D hull on .xy
static void CalcConvexHull2D(Vector3[] points, List<Vector2> outHull)
{
outHull.Clear();
if (points == null || points.Length == 0)
return;
var needCapacity = points.Length + 1;
if (outHull.Capacity < needCapacity)
outHull.Capacity = needCapacity;
if (points.Length == 1)
{
outHull.Add(points[0]);
return;
}
// Andrew's monotone chain algorithm:
// First sort the input points
Array.Sort(points, (a, b) =>
{
var ca = a.x.CompareTo(b.x);
return ca != 0 ? ca : a.y.CompareTo(b.y);
});
// Build lower hull
for (int i = 0; i < points.Length; ++i)
{
Vector2 pt = points[i];
RemoveInsidePoints(2, pt, outHull);
outHull.Add(pt);
}
// Build upper hull
for (int i = points.Length - 2, j = outHull.Count + 1; i >= 0; --i)
{
Vector2 pt = points[i];
RemoveInsidePoints(j, pt, outHull);
outHull.Add(pt);
}
// Remove last point (it's the same as the first one)
outHull.RemoveAt(outHull.Count - 1);
}
// Note: modifies input points array
static void CalcPointCloudConvexHull(Vector3[] points, List<Vector2> outHull)
{
outHull.Clear();
if (points == null || points.Length == 0)
return;
// project point cloud into 2D GUI space
var handleMatrix = Handles.matrix;
var cam = new CameraProjectionCache(Camera.current);
for (var i = 0; i < points.Length; ++i)
points[i] = cam.WorldToGUIPoint(handleMatrix.MultiplyPoint3x4(points[i]));
// calculate 2D convex hull
CalcConvexHull2D(points, outHull);
}
// Note: input array contents are modified
static readonly List<Vector2> s_PointCloudConvexHull = new List<Vector2>();
static float DistanceToPointCloudConvexHull(params Vector3[] points)
{
if (points == null || points.Length == 0 || Camera.current == null)
return float.PositiveInfinity;
var mousePos = Event.current.mousePosition;
CalcPointCloudConvexHull(points, s_PointCloudConvexHull);
return DistancePointToConvexHull(mousePos, s_PointCloudConvexHull);
}
// Record a distance measurement from a handle.
public static void AddControl(int controlId, float distance)
{
if (distance < s_CustomPickDistance && distance > kPickDistance)
distance = kPickDistance;
if (distance <= s_NearestDistance)
{
s_NearestDistance = distance;
s_NearestControl = controlId;
}
}
// Add the ID for a default control. This will be picked if nothing else is
public static void AddDefaultControl(int controlId)
{
AddControl(controlId, kPickDistance);
}
static int s_PreviousNearestControl;
static int s_NearestControl;
static float s_NearestDistance;
static Camera s_PreviousCamera;
internal const float kPickDistance = 5.0f;
internal static float s_CustomPickDistance = kPickDistance;
public static int nearestControl { get { return s_NearestDistance <= kPickDistance ? s_NearestControl : 0; } set { s_NearestControl = value; } }
[RequiredByNativeCode]
internal static void BeginHandles()
{
Handles.Init();
switch (Event.current.type)
{
case EventType.Layout:
s_NearestControl = 0;
s_NearestDistance = kPickDistance;
break;
}
Handles.lighting = true;
Handles.color = Color.white;
Handles.zTest = CompareFunction.Always;
s_CustomPickDistance = kPickDistance;
if (null != Camera.current)
{
s_PreviousCamera = Camera.current;
}
Handles.Internal_SetCurrentCamera(null);
EditorGUI.s_DelayedTextEditor.BeginGUI();
}
[RequiredByNativeCode]
internal static void EndHandles()
{
if (s_PreviousNearestControl != s_NearestControl
&& s_NearestControl != 0
&& Event.current.type != EventType.Layout)
{
s_PreviousNearestControl = s_NearestControl;
Repaint();
}
if (null != s_PreviousCamera)
{
Handles.Internal_SetCurrentCamera(s_PreviousCamera);
s_PreviousCamera = null;
}
// Give the delayed text editor a chance to notice that it lost focus.
EditorGUI.s_DelayedTextEditor.EndGUI(Event.current.type);
}
const float k_KHandleSize = 80.0f;
// Get world space size of a manipulator handle at given position.
public static float GetHandleSize(Vector3 position)
{
Camera cam = Camera.current;
position = Handles.matrix.MultiplyPoint(position);
if (cam)
{
Transform tr = cam.transform;
Vector3 camPos = tr.position;
float distance = Vector3.Dot(position - camPos, tr.TransformDirection(new Vector3(0, 0, 1)));
Vector3 screenPos = cam.WorldToScreenPoint(camPos + tr.TransformDirection(new Vector3(0, 0, distance)));
Vector3 screenPos2 = cam.WorldToScreenPoint(camPos + tr.TransformDirection(new Vector3(1, 0, distance)));
float screenDist = (screenPos - screenPos2).magnitude;
return (k_KHandleSize / Mathf.Max(screenDist, 0.0001f)) * EditorGUIUtility.pixelsPerPoint;
}
return 20.0f;
}
static float renderingViewHeight
{
get { return Camera.current == null ? Screen.height : Camera.current.pixelHeight; }
}
// Convert world space point to a 2D GUI position.
public static Vector2 WorldToGUIPoint(Vector3 world)
{
return WorldToGUIPointWithDepth(world);
}
// Convert world space point to a 2D GUI position.
public static Vector3 WorldToGUIPointWithDepth(Vector3 world)
{
return WorldToGUIPointWithDepth(Camera.current, world);
}
// Convert world space point to a 2D GUI position.
// Use this version in critical loops.
public static Vector3 WorldToGUIPointWithDepth(Camera camera, Vector3 world)
{
world = Handles.matrix.MultiplyPoint(world);
if (camera)
{
Vector3 pos = camera.WorldToScreenPoint(world);
pos.y = camera.pixelHeight - pos.y;
Vector2 points = EditorGUIUtility.PixelsToPoints(pos);
return new Vector3(points.x, points.y, pos.z);
}
return world;
}
public static Vector2 GUIPointToScreenPixelCoordinate(Vector2 guiPoint)
{
var unclippedPosition = GUIClip.Unclip(guiPoint);
var screenPixelPos = EditorGUIUtility.PointsToPixels(unclippedPosition);
screenPixelPos.y = renderingViewHeight - screenPixelPos.y;
return screenPixelPos;
}
// Convert 2D GUI position to a world space ray.
public static Ray GUIPointToWorldRay(Vector2 position)
{
return GUIPointToWorldRayPrecise(position);
}
private static Ray GUIPointToWorldRayPrecise(Vector2 position, float startZ = float.NegativeInfinity)
{
Camera camera = Camera.current;
if (!camera && SceneView.lastActiveSceneView != null)
camera = SceneView.lastActiveSceneView.camera;
if (!camera)
{
Debug.LogError("Unable to convert GUI point to world ray if a camera has not been set up!");
return new Ray(Vector3.zero, Vector3.forward);
}
if (float.IsNegativeInfinity(startZ))
startZ = camera.nearClipPlane;
Vector2 screenPixelPos = GUIPointToScreenPixelCoordinate(position);
Rect viewport = camera.pixelRect;
Matrix4x4 camToWorld = camera.cameraToWorldMatrix;
Matrix4x4 camToClip = camera.projectionMatrix;
Matrix4x4 clipToCam = camToClip.inverse;
// calculate ray origin and direction in world space
Vector3 rayOriginWorldSpace;
Vector3 rayDirectionWorldSpace;
// first construct an arbitrary point that is on the ray through this screen pixel (remap screen pixel point to clip space [-1, 1])
Vector3 rayPointClipSpace = new Vector3(
(screenPixelPos.x - viewport.x) * 2.0f / viewport.width - 1.0f,
(screenPixelPos.y - viewport.y) * 2.0f / viewport.height - 1.0f,
0.95f
);
// and convert that point to camera space
Vector3 rayPointCameraSpace = clipToCam.MultiplyPoint(rayPointClipSpace);
if (camera.orthographic)
{
// ray direction is always 'camera forward' in orthographic mode
Vector3 rayDirectionCameraSpace = new Vector3(0.0f, 0.0f, -1.0f);
rayDirectionWorldSpace = camToWorld.MultiplyVector(rayDirectionCameraSpace);
rayDirectionWorldSpace.Normalize();
// in camera space, the ray origin has the same XY coordinates as ANY point on the ray
// so we just need to override the Z coordinate to startZ to get the correct starting point
// (assuming camToWorld is a pure rotation/offset, with no scale)
Vector3 rayOriginCameraSpace = rayPointCameraSpace;
// The camera/projection matrices follow OpenGL convention: positive Z is towards the viewer.
// So negate it to get into Unity convention.
rayOriginCameraSpace.z = -startZ;
// move it to world space
rayOriginWorldSpace = camToWorld.MultiplyPoint(rayOriginCameraSpace);
}
else
{
// in projective mode, the ray passes through the origin in camera space
// so the ray direction is just (ray point - origin) == (ray point)
Vector3 rayDirectionCameraSpace = rayPointCameraSpace;
rayDirectionCameraSpace.Normalize();
rayDirectionWorldSpace = camToWorld.MultiplyVector(rayDirectionCameraSpace);
// calculate the correct startZ offset from the camera by moving a distance along the ray direction
// this assumes camToWorld is a pure rotation/offset, with no scale, so we can use rayDirection.z to calculate how far we need to move
Vector3 cameraPositionWorldSpace = camToWorld.MultiplyPoint(Vector3.zero);
// The camera/projection matrices follow OpenGL convention: positive Z is towards the viewer.
// So negate it to get into Unity convention.
Vector3 originOffsetWorldSpace = rayDirectionWorldSpace * -startZ / rayDirectionCameraSpace.z;
rayOriginWorldSpace = cameraPositionWorldSpace + originOffsetWorldSpace;
}
return new Ray(rayOriginWorldSpace, rayDirectionWorldSpace);
}
// Figure out a rectangle to display a 2D GUI element in 3D space.
public static Rect WorldPointToSizedRect(Vector3 position, GUIContent content, GUIStyle style)
{
Vector2 screenpos = WorldToGUIPoint(position);
Vector2 size = style.CalcSize(content);
Rect rect = new Rect(screenpos.x, screenpos.y, size.x, size.y);
switch (style.alignment)
{
case TextAnchor.UpperCenter:
rect.x -= rect.width * 0.5f;
break;
case TextAnchor.UpperRight:
rect.x -= rect.width;
break;
case TextAnchor.MiddleLeft:
rect.y -= rect.height * 0.5f;
break;
case TextAnchor.MiddleCenter:
rect.x -= rect.width * 0.5f;
rect.y -= rect.height * 0.5f;
break;
case TextAnchor.MiddleRight:
rect.x -= rect.width;
rect.y -= rect.height * 0.5f;
break;
case TextAnchor.LowerLeft:
rect.y -= rect.height;
break;
case TextAnchor.LowerCenter:
rect.x -= rect.width * 0.5f;
rect.y -= rect.height;
break;
case TextAnchor.LowerRight:
rect.x -= rect.width;
rect.y -= rect.height;
break;
}
return style.padding.Add(rect);
}
// Pick game object in specified rectangle
public static GameObject[] PickRectObjects(Rect rect)
{
return PickRectObjects(rect, true);
}
// *undocumented*
public static GameObject[] PickRectObjects(Rect rect, bool selectPrefabRootsOnly)
{
Camera cam = Camera.current;
rect = EditorGUIUtility.PointsToPixels(rect);
rect.x /= cam.pixelWidth;
rect.width /= cam.pixelWidth;
rect.y /= cam.pixelHeight;
rect.height /= cam.pixelHeight;
bool allowGizmos = SceneView.lastActiveSceneView == null || SceneView.lastActiveSceneView.drawGizmos;
return Internal_PickRectObjects(cam, rect, selectPrefabRootsOnly, allowGizmos);
}
public static bool FindNearestVertex(Vector2 guiPoint, out Vector3 vertex, out GameObject gameObject)
{
return FindNearestVertex(guiPoint, null, ignoreRaySnapObjects, out vertex, out gameObject);
}
public static bool FindNearestVertex(Vector2 guiPoint, Transform[] objectsToSearch, out Vector3 vertex, out GameObject gameObject)
{
return FindNearestVertex(guiPoint, objectsToSearch, ignoreRaySnapObjects, out vertex, out gameObject);
}