Exemplo n.º 1
0
    /// <summary>Cut mesh along bisector line and keep only the half containing the center point.</summary>
    public static TempMesh Cut(Mesh mesh, Line bisector, Vector2 center)
    {
        var      initialArraySize = 256;
        TempMesh tempMesh         = new TempMesh(initialArraySize);
        TempMesh trashMesh        = new TempMesh(initialArraySize);
        var      intersect        = new Intersections();

        var addedPairs    = new List <Vector3>(initialArraySize);
        var ogVertices    = new List <Vector3>(initialArraySize);
        var ogNormals     = new List <Vector3>(initialArraySize);
        var ogUvs         = new List <Vector2>(initialArraySize);
        var ogTriangles   = new List <int>(initialArraySize * 3);
        var intersectPair = new Vector3[2];

        var tempTriangle = new Vector3[3];

        // Let's always fill the vertices array so that we can access it even if the mesh didn't intersect
        mesh.GetVertices(ogVertices);
        mesh.GetTriangles(ogTriangles, 0);
        mesh.GetNormals(ogNormals);
        mesh.GetUVs(0, ogUvs);

        tempMesh.Clear();
        trashMesh.Clear();

        for (int i = 0; i < ogVertices.Count; ++i)
        {
            var test = bisector.isLeft(ogVertices[i]);
            // Debug.Log(test);
            if (test)
            {
                tempMesh.AddVertex(ogVertices, ogNormals, ogUvs, i);
            }
            else
            {
                trashMesh.AddVertex(ogVertices, ogNormals, ogUvs, i);
            }
        }

        Plane slice = bisector.GetPlane();

        // 3. Separate triangles and cut those that intersect the plane
        for (int i = 0; i < ogTriangles.Count; i += 3)
        {
            if (intersect.TrianglePlaneIntersect(ogVertices, ogUvs, ogTriangles, i, ref slice, tempMesh, trashMesh, intersectPair))
            {
                addedPairs.AddRange(intersectPair);
            }
        }

        if (addedPairs.Count > 0)
        {
            //FillBoundaryGeneral(addedPairs);
            MeshTools.FillBoundaryFace(tempMesh, addedPairs, ref tempTriangle);
            return(tempMesh);
        }
        else
        {
            throw new UnityException("Error: if added pairs is empty, we should have returned false earlier");
        }

        return(tempMesh);
    }