/*
    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License version 2 
    as published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


    Copyright (C) 2006  Thierry Berger-Perrin <tbptbp@gmail.com>
*/

#include "specifics.h"
#include "kdlib.h"
#include "kdlib_internal.h"
#include <limits> // std::numeric_limits

namespace kdlib {
    namespace cst {
        extern const float32_t 
            inf_plus    = std::numeric_limits<float>::infinity(),
            inf_minus   = -inf_plus;
    }
}

#include "kdlib_writer.h"
bool_t kdlib_compile(const triangle_t * __restrict const t,
                     const int num_tri, kdtree::descriptor_t &descriptor,
                     aabb_t &bbox)
{
    kdlib::compiler_t *c = new kdlib::compiler_t();
    c->injection(t, num_tri);
    SAH::heuristic_t sah;
    std::memset(&sah, 0, sizeof(sah));
    sah.complex_heuristic_threshold = 2048;
    sah.cost_intersection = 100;
    sah.cost_traversal = 200;
    sah.depth_max = 63;
    sah.leaf_count_max = -1;
    sah.leaf_count_min = 1;
    sah.microscopic_cell_ratio = 0;
    sah.tweaks.bits = 0;
    sah.version.use_kdlib = 1;

    c->compile(sah);
    kdlib::writer_t writer;
    writer.init(*c);
    writer.write(&c->root);
    bbox = c->state.scene_bbox;
    c->dispose();
    delete c;
    descriptor.root = writer.dst;
    descriptor.ids = writer.ids;
    descriptor.id_n = writer.num_ids;
    descriptor.node_n = writer.num_nodes;
    descriptor.tri_n = num_tri;

    return true;
}
