source: OniSplit/Akira/PolygonUtils.cs@ 1126

Last change on this file since 1126 was 1114, checked in by iritscen, 5 years ago

Adding OniSplit source code (v0.9.99.0). Many thanks to Neo for all his work over the years.

File size: 2.5 KB
Line 
1using System;
2using System.Collections.Generic;
3
4namespace Oni.Akira
5{
6 internal class PolygonUtils
7 {
8 public static List<Vector3> ClipToPlane(List<Vector3> points, Plane plane)
9 {
10 var signs = new int[points.Count];
11 var negativeCount = 0;
12 var positiveCount = 0;
13 var start = 0;
14
15 for (int i = 0; i < points.Count; i++)
16 {
17 signs[i] = RelativePosition(points[i], plane);
18
19 if (signs[i] >= 0)
20 positiveCount++;
21
22 if (signs[i] <= 0)
23 negativeCount++;
24 }
25
26 if (negativeCount == points.Count)
27 return null;
28
29 if (positiveCount == points.Count)
30 return points;
31
32 var newPoints = new List<Vector3>();
33
34 for (int i = 0; i < points.Count; i++)
35 {
36 int i0 = (i + start) % points.Count;
37 int i1 = (i + start + 1) % points.Count;
38
39 int s0 = signs[i0];
40 int s1 = signs[i1];
41
42 if (s0 >= 0)
43 {
44 newPoints.Add(points[i0]);
45
46 if (s0 > 0 && s1 < 0)
47 newPoints.Add(Intersect(points[i0], points[i1], plane));
48 }
49 else
50 {
51 if (s0 < 0 && s1 > 0)
52 newPoints.Add(Intersect(points[i1], points[i0], plane));
53 }
54 }
55
56 return newPoints;
57 }
58
59 private static Vector3 Intersect(Vector3 p0, Vector3 p1, Plane plane)
60 {
61 Vector3 dir = p1 - p0;
62
63 float dND = plane.DotNormal(dir);
64
65 if (Math.Abs(dND) < 1e-05f)
66 throw new InvalidOperationException();
67
68 float distance = (-plane.D - plane.DotNormal(p0)) / dND;
69
70 if (distance < 0.0f)
71 {
72 if (distance < -1e-05f)
73 throw new InvalidOperationException();
74
75 return p0;
76 }
77 else
78 {
79 return p0 + dir * distance;
80 }
81 }
82
83 private static int RelativePosition(Vector3 point, Plane plane)
84 {
85 float pos = plane.DotCoordinate(point);
86
87 if (pos < -1e-05f)
88 return -1;
89 else if (pos > 1e-05f)
90 return 1;
91 else
92 return 0;
93 }
94 }
95}
Note: See TracBrowser for help on using the repository browser.