public static unsafe void GetFaceSidePlanes(ref NativeBuffer <ClipPlane> output, NativePlane facePlane, int faceIndex, RigidTransform transform, NativeHull hull) { NativeHalfEdge *start = hull.GetEdgePtr(hull.GetFacePtr(faceIndex)->Edge); NativeHalfEdge *current = start; do { NativeHalfEdge *twin = hull.GetEdgePtr(current->Twin); float3 P = math.transform(transform, hull.GetVertex(current->Origin)); float3 Q = math.transform(transform, hull.GetVertex(twin->Origin)); ClipPlane clipPlane = default; clipPlane.edgeId = twin->Twin; //edge ID. clipPlane.plane.Normal = math.normalize(math.cross(Q - P, facePlane.Normal)); clipPlane.plane.Offset = math.dot(clipPlane.plane.Normal, P); output.Add(clipPlane); current = hull.GetEdgePtr(current->Next); }while (current != start); }
/// <summary> /// Perform the Sutherland-Hodgman polygon clipping. Since all side planes are pointing outwards the points that are *behind* the plane are kept. /// </summary> public static void Clip(ClipPlane clipPlane, ref NativeBuffer <ClipVertex> input, ref NativeBuffer <ClipVertex> output) { //Debug.Assert(output.IsCreated && output.Length == 0); Debug.Assert(input.IsCreated && input.Length != 0); ClipVertex vertex1 = input[input.Length - 1]; float distance1 = clipPlane.plane.Distance(vertex1.position); for (int i = 0; i < input.Length; ++i) { ClipVertex vertex2 = input[i]; float distance2 = clipPlane.plane.Distance(vertex2.position); if (distance1 <= 0 && distance2 <= 0) { // Both vertices are behind or lying on the plane -> keep vertex2 output.Add(vertex2); } else if (distance1 <= 0 && distance2 > 0) { // vertex1 is behind the plane, vertex2 is in front -> intersection point float fraction = distance1 / (distance1 - distance2); float3 position = vertex1.position + fraction * (vertex2.position - vertex1.position); // Keep intersection point ClipVertex vertex; vertex.position = position; vertex.featurePair.InEdge1 = -1; vertex.featurePair.InEdge2 = vertex1.featurePair.OutEdge2; vertex.featurePair.OutEdge1 = (sbyte)clipPlane.edgeId; vertex.featurePair.OutEdge2 = -1; vertex.plane = clipPlane.plane; vertex.hull2local = position; output.Add(vertex); } else if (distance2 <= 0 && distance1 > 0) { // vertex2 is behind of the plane, vertex1 is in front -> intersection point float fraction = distance1 / (distance1 - distance2); float3 position = vertex1.position + fraction * (vertex2.position - vertex1.position); // Keep intersection point ClipVertex vertex; vertex.position = position; vertex.featurePair.InEdge1 = (sbyte)clipPlane.edgeId; vertex.featurePair.OutEdge1 = -1; vertex.featurePair.InEdge2 = -1; vertex.featurePair.OutEdge2 = vertex1.featurePair.OutEdge2; vertex.plane = clipPlane.plane; vertex.hull2local = position; output.Add(vertex); // Keep vertex2 as well output.Add(vertex2); } // Keep vertex2 as starting vertex for next edge vertex1 = vertex2; distance1 = distance2; } }