Example #1
0
    internal static KDNode Build(List <Triangle> pTriangles, int pDepth, Axis pPreviousAxis)
    {
        KDNode node = new KDNode();

        node.Triangles = pTriangles;

        float tris_count = node.Triangles.Count;

        if (tris_count == 0)
        {
            return(node);
        }

        node.Box = new Bounds(node.Triangles[0].Box.center, node.Triangles[0].Box.size);

        if (tris_count == 1 || pDepth >= MaxDepth)
        {
            node.InitEmptyLeaf();

            return(node);
        }

        Vector3 mid_point = Vector3.zero;

        for (int i = 1; i < tris_count; ++i)
        {
            node.Box.Encapsulate(node.Triangles[i].Box);
        }

        for (int i = 0; i < tris_count; ++i)
        {
            mid_point += node.Triangles[0].GetMidPoint() * (1 / tris_count);
        }

        node.MidPoint = mid_point;

        Axis long_axis = node.GetLongestAxis(pPreviousAxis);

        node.SelectionAxis = long_axis;

        List <Triangle> left_triangles  = new List <Triangle>();
        List <Triangle> right_triangles = new List <Triangle>();

        bool should_split = node.DivideLeftRightTriangles(ref left_triangles, ref right_triangles);

        if (should_split)
        {
            node.Left  = Build(left_triangles, pDepth + 1, long_axis);
            node.Right = Build(right_triangles, pDepth + 1, long_axis);
        }
        else
        {
            node.InitEmptyLeaf();
        }

        return(node);
    }