<commit_before>#include "tensor3.hpp"
#include "matrix.hpp"

// Include standard headers
#include <stdint.h> // uint32_t etc.

namespace linear_algebra
{
    // `class Tensor3` uses the same coordinate order as MATLAB,
    // to make testing easier. So: y, x, z.
    // y = 0 is the uppermost slice
    // x = 0 is the leftmost slice.
    // z = 0 is the front slice.

    Tensor3::Tensor3(uint32_t height, uint32_t width, uint32_t depth)
    {
        // constructor.
        this->width = width;
        this->height = height;
        this->depth = depth;
        this->array_of_arrays_of_arrays = new float**[this->height];

        for (uint32_t y = 0; y < this->height; y++)
        {
            this->array_of_arrays_of_arrays[y] = new float*[this->width];

            for (uint32_t x = 0; x < this->width; x++)
            {
                this->array_of_arrays_of_arrays[y][x] = new float[this->depth];
            }
        }

        this->next_x_to_populate = 0;
        this->next_y_to_populate = 0;
        this->next_z_to_populate = 0;
        this->is_fully_populated = false;

        if (this->width == this->height && this->height == this->depth)
        {
            this->is_cube = true;
        }
        else
        {
            this->is_cube = false;
        }
    }

    Tensor3::Tensor3(Tensor3& old_tensor3)
    {
        // copy constructor.
        this->width = old_tensor3.width;
        this->height = old_tensor3.height;
        this->depth = old_tensor3.depth;
        this->array_of_arrays_of_arrays = new float**[this->height];

        for (uint32_t y = 0; y < this->height; y++)
        {
            this->array_of_arrays_of_arrays[y] = new float*[this->width];

            for (uint32_t x = 0; x < this->width; x++)
            {
                this->array_of_arrays_of_arrays[y][x] = new float[this->depth];
            }
        }

        this->next_x_to_populate = 0;
        this->next_y_to_populate = 0;
        this->next_z_to_populate = 0;
        this->is_fully_populated = false;

        if (this->width == this->height && this->height == this->depth)
        {
            this->is_cube = true;
        }
        else
        {
            this->is_cube = false;
        }
    }

    Tensor3::Tensor3(Matrix& old_matrix)
    {
        // constructor.

        this->width = old_matrix.width;
        this->height = old_matrix.height;
        this->depth = 1;
        this->array_of_arrays_of_arrays = new float**[this->height];

        for (uint32_t y = 0; y < this->height; y++)
        {
            this->array_of_arrays_of_arrays[y] = new float*[this->width];

            for (uint32_t x = 0; x < this->width; x++)
            {
                this->array_of_arrays_of_arrays[y][x] = new float[this->depth];
            }
        }

        this->next_x_to_populate = 0;
        this->next_y_to_populate = 0;
        this->next_z_to_populate = 0;
        this->is_fully_populated = false;

        this->is_cube = false;
    }

    Tensor3::~Tensor3()
    {
    }

    void Tensor3::operator<<(const float rhs)
    {
        if (this->is_fully_populated)
        {
            // Array is already fully populated. Nothing to do.
            return;
        }

        // First, get the slice.
        float** my_array_of_arrays = this->array_of_arrays_of_arrays[this->next_y_to_populate];
        float* my_array = my_array_of_arrays[this->next_x_to_populate];

        // Then store the value.
        my_array[this->next_z_to_populate] = rhs;

        if (++this->next_x_to_populate >= this->width)
        {
            this->next_x_to_populate = 0;

            if (++this->next_y_to_populate >= this->height)
            {
                this->next_y_to_populate = 0;

                if (++this->next_z_to_populate >= this->depth)
                {
                    this->is_fully_populated = true;
                }
            }
        }
    }

    void Tensor3::operator<<(const std::vector<float>& rhs)
    {
        uint32_t rhs_i = 0;

        if (this->is_fully_populated && rhs_i < rhs.size())
        {
            // Array is already fully populated. Nothing to do.
            return;
        }

        // First, get the slice.
        float** my_array_of_arrays = this->array_of_arrays_of_arrays[this->next_y_to_populate];
        float* my_array = my_array_of_arrays[this->next_x_to_populate];

        // Then store the value.
        my_array[this->next_z_to_populate] = rhs.at(rhs_i++);

        if (++this->next_x_to_populate >= this->width)
        {
            this->next_x_to_populate = 0;

            if (++this->next_y_to_populate >= this->height)
            {
                this->next_y_to_populate = 0;

                if (++this->next_z_to_populate >= this->depth)
                {
                    this->is_fully_populated = true;
                }
            }
        }
    }

}
<commit_msg>Bugfix: `void Tensor3::operator<<(const std::vector<float>& rhs)`.<commit_after>#include "tensor3.hpp"
#include "matrix.hpp"

// Include standard headers
#include <stdint.h> // uint32_t etc.

namespace linear_algebra
{
    // `class Tensor3` uses the same coordinate order as MATLAB,
    // to make testing easier. So: y, x, z.
    // y = 0 is the uppermost slice
    // x = 0 is the leftmost slice.
    // z = 0 is the front slice.

    Tensor3::Tensor3(uint32_t height, uint32_t width, uint32_t depth)
    {
        // constructor.
        this->width = width;
        this->height = height;
        this->depth = depth;
        this->array_of_arrays_of_arrays = new float**[this->height];

        for (uint32_t y = 0; y < this->height; y++)
        {
            this->array_of_arrays_of_arrays[y] = new float*[this->width];

            for (uint32_t x = 0; x < this->width; x++)
            {
                this->array_of_arrays_of_arrays[y][x] = new float[this->depth];
            }
        }

        this->next_x_to_populate = 0;
        this->next_y_to_populate = 0;
        this->next_z_to_populate = 0;
        this->is_fully_populated = false;

        if (this->width == this->height && this->height == this->depth)
        {
            this->is_cube = true;
        }
        else
        {
            this->is_cube = false;
        }
    }

    Tensor3::Tensor3(Tensor3& old_tensor3)
    {
        // copy constructor.
        this->width = old_tensor3.width;
        this->height = old_tensor3.height;
        this->depth = old_tensor3.depth;
        this->array_of_arrays_of_arrays = new float**[this->height];

        for (uint32_t y = 0; y < this->height; y++)
        {
            this->array_of_arrays_of_arrays[y] = new float*[this->width];

            for (uint32_t x = 0; x < this->width; x++)
            {
                this->array_of_arrays_of_arrays[y][x] = new float[this->depth];
            }
        }

        this->next_x_to_populate = 0;
        this->next_y_to_populate = 0;
        this->next_z_to_populate = 0;
        this->is_fully_populated = false;

        if (this->width == this->height && this->height == this->depth)
        {
            this->is_cube = true;
        }
        else
        {
            this->is_cube = false;
        }
    }

    Tensor3::Tensor3(Matrix& old_matrix)
    {
        // constructor.

        this->width = old_matrix.width;
        this->height = old_matrix.height;
        this->depth = 1;
        this->array_of_arrays_of_arrays = new float**[this->height];

        for (uint32_t y = 0; y < this->height; y++)
        {
            this->array_of_arrays_of_arrays[y] = new float*[this->width];

            for (uint32_t x = 0; x < this->width; x++)
            {
                this->array_of_arrays_of_arrays[y][x] = new float[this->depth];
            }
        }

        this->next_x_to_populate = 0;
        this->next_y_to_populate = 0;
        this->next_z_to_populate = 0;
        this->is_fully_populated = false;

        this->is_cube = false;
    }

    Tensor3::~Tensor3()
    {
    }

    void Tensor3::operator<<(const float rhs)
    {
        if (this->is_fully_populated)
        {
            // Array is already fully populated. Nothing to do.
            return;
        }

        // First, get the slice.
        float** my_array_of_arrays = this->array_of_arrays_of_arrays[this->next_y_to_populate];
        float* my_array = my_array_of_arrays[this->next_x_to_populate];

        // Then store the value.
        my_array[this->next_z_to_populate] = rhs;

        if (++this->next_x_to_populate >= this->width)
        {
            this->next_x_to_populate = 0;

            if (++this->next_y_to_populate >= this->height)
            {
                this->next_y_to_populate = 0;

                if (++this->next_z_to_populate >= this->depth)
                {
                    this->is_fully_populated = true;
                }
            }
        }
    }

    void Tensor3::operator<<(const std::vector<float>& rhs)
    {
        uint32_t rhs_i = 0;

        while (!this->is_fully_populated && rhs_i < rhs.size())
        {
            // First, get the slice.
            float** my_array_of_arrays = this->array_of_arrays_of_arrays[this->next_y_to_populate];
            float* my_array = my_array_of_arrays[this->next_x_to_populate];

            // Then store the value.
            my_array[this->next_z_to_populate] = rhs.at(rhs_i++);

            if (++this->next_x_to_populate >= this->width)
            {
                this->next_x_to_populate = 0;

                if (++this->next_y_to_populate >= this->height)
                {
                    this->next_y_to_populate = 0;

                    if (++this->next_z_to_populate >= this->depth)
                    {
                        this->is_fully_populated = true;
                    }
                }
            }
        }
    }
}
<|endoftext|>


<commit_before><commit_msg>Split unnecessarily long source code line into several lines.<commit_after><|endoftext|>


<commit_before><commit_msg>Cleaning up `ShaderStruct` code.<commit_after><|endoftext|>


<commit_before>/*
 * Copyright (C) 2015 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include <bits/stdc++.h>

std::string correctUppers(const std::string& str) {
    // a single-character delimiters between sentences
    static const char delimiters[] = {'.', '?', '!'};
    int size = str.size();
    std::string result;
    bool new_sentence = false;
    result.push_back(toupper(str[0]));
    for (size_t pos = 1; pos < size; pos++) {
        for (int i = 0; i < 3; i++) {
            if (str[pos] == delimiters[i]) {
                new_sentence = true;
            }
        }
        if (islower(str[pos]) && new_sentence) {
            result.push_back(toupper(str[pos]));
            new_sentence = false;
        } else {
            result.push_back(str[pos]);
        }
    }
    return result;
}

std::string clearBorders(const std::string& str) {
    int size = str.size();
    std::string result;
    int begin = 0;
    while (!isalnum(str[begin])) {
        begin++;
    }
    int end = size - 1;
    while (isspace(str[end])) {
        end--;
    }
    for (size_t i = begin; i <= end; i++) {
        result.push_back(str[i]);
    }
    return result;
}

std::string deleteExtraSpaces(const std::string& str) {
    size_t size = str.size();
    std::string result;
    int spaces = 0;
    for (size_t pos = 0; pos < size; pos++) {
        if (isspace(str[pos])) {
            spaces++;
            if (spaces == 1) {
                result.push_back(str[pos]);
            }
        } else {
            spaces = 0;
            result.push_back(str[pos]);
        }
    }
    return result;
}

std::string correct(const std::string& str) {
    std::string value = clearBorders(str);
    return deleteExtraSpaces(value);
}

int main() {
    std::string str;
    std::getline(std::cin, str);
    std::cout << correct(str) << std::endl;
    return 0;
}
<commit_msg>Clear types<commit_after>/*
 * Copyright (C) 2015 Pavel Dolgov
 *
 * See the LICENSE file for terms of use.
 */

#include <bits/stdc++.h>

std::string correctUppers(const std::string& str) {
    // a single-character delimiters between sentences
    static const char delimiters[] = {'.', '?', '!'};
    size_t size = str.size();
    std::string result;
    bool new_sentence = false;
    result.push_back(toupper(str[0]));
    for (size_t pos = 1; pos < size; pos++) {
        for (int i = 0; i < 3; i++) {
            if (str[pos] == delimiters[i]) {
                new_sentence = true;
            }
        }
        if (islower(str[pos]) && new_sentence) {
            result.push_back(toupper(str[pos]));
            new_sentence = false;
        } else {
            result.push_back(str[pos]);
        }
    }
    return result;
}

std::string clearBorders(const std::string& str) {
    size_t size = str.size();
    std::string result;
    size_t begin = 0;
    while ((begin < size) && !isalnum(str[begin])) {
        begin++;
    }
    size_t end = size - 1;
    while ((end >= 0) && isspace(str[end])) {
        end--;
    }
    for (size_t i = begin; i <= end; i++) {
        result.push_back(str[i]);
    }
    return result;
}

std::string deleteExtraSpaces(const std::string& str) {
    size_t size = str.size();
    std::string result;
    int spaces = 0;
    for (size_t pos = 0; pos < size; pos++) {
        if (isspace(str[pos])) {
            spaces++;
            if (spaces == 1) {
                result.push_back(str[pos]);
            }
        } else {
            spaces = 0;
            result.push_back(str[pos]);
        }
    }
    return result;
}

std::string correct(const std::string& str) {
    std::string value = clearBorders(str);
    return deleteExtraSpaces(value);
}

int main() {
    std::string str;
    std::getline(std::cin, str);
    std::cout << correct(str) << std::endl;
    return 0;
}
<|endoftext|>


<commit_before>#include "FAST/Tests/catch.hpp"
#include "TubeSegmentationAndCenterlineExtraction.hpp"
#include "FAST/Importers/ImageFileImporter.hpp"
#include "FAST/Visualization/SliceRenderer/SliceRenderer.hpp"
#include "FAST/Visualization/LineRenderer/LineRenderer.hpp"
#include "FAST/Algorithms/SurfaceExtraction/SurfaceExtraction.hpp"
#include "FAST/Visualization/MeshRenderer/MeshRenderer.hpp"
#include "FAST/Visualization/SimpleWindow.hpp"
#include "FAST/Algorithms/ImageCropper/ImageCropper.hpp"

namespace fast {

/*
TEST_CASE("TSF", "[tsf]") {
    ImageFileImporter::pointer importer = ImageFileImporter::New();
    importer->setFilename("/home/smistad/Dropbox/Programmering/Tube-Segmentation-Framework/tests/data/synthetic/dataset_1/noisy.mhd");

    TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New();
    tubeExtraction->setInputConnection(importer->getOutputPort());
    tubeExtraction->extractBrightTubes();
    tubeExtraction->setMinimumRadius(0.5);
    tubeExtraction->setMaximumRadius(8);
    tubeExtraction->setSensitivity(0.99);

    SliceRenderer::pointer renderer = SliceRenderer::New();
    renderer->setInputConnection(tubeExtraction->getTDFOutputPort());

    LineRenderer::pointer lineRenderer = LineRenderer::New();
    lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort());
    lineRenderer->setDefaultDrawOnTop(true);

    SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New();
    surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort());

    MeshRenderer::pointer meshRenderer = MeshRenderer::New();
    meshRenderer->addInputConnection(surfaceExtraction->getOutputPort());

    SimpleWindow::pointer window = SimpleWindow::New();
    window->addRenderer(renderer);
    window->addRenderer(meshRenderer);
    window->addRenderer(lineRenderer);
    window->start();
}
*/

TEST_CASE("TSF Airway", "[tsf][airway]") {
    //Report::setReportMethod(Report::COUT);
    ImageFileImporter::pointer importer = ImageFileImporter::New();
    importer->setFilename(std::string(FAST_TEST_DATA_DIR) + "CT-Thorax.mhd");

    ImageCropper::pointer cropper = ImageCropper::New();
    cropper->setOffset(Vector3ui(56, 119, 155));
    cropper->setSize(Vector3ui(400, 232, 509));
    cropper->setInputConnection(importer->getOutputPort());

    TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New();
    tubeExtraction->setInputConnection(cropper->getOutputPort());
    tubeExtraction->extractDarkTubes();
    tubeExtraction->setMinimumIntensity(-1024);
    tubeExtraction->setMaximumIntensity(100);
    tubeExtraction->setMinimumRadius(0.5);
    tubeExtraction->setMaximumRadius(50);
    tubeExtraction->setSensitivity(0.8);

    SliceRenderer::pointer renderer = SliceRenderer::New();
    renderer->setInputConnection(importer->getOutputPort());

    LineRenderer::pointer lineRenderer = LineRenderer::New();
    lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort());
    lineRenderer->setDefaultDrawOnTop(true);

    SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New();
    surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort());

    MeshRenderer::pointer meshRenderer = MeshRenderer::New();
    meshRenderer->addInputConnection(surfaceExtraction->getOutputPort());

    SimpleWindow::pointer window = SimpleWindow::New();
    window->addRenderer(renderer);
    window->addRenderer(meshRenderer);
    window->addRenderer(lineRenderer);
    window->start();
}

}
<commit_msg>added visual tag to test<commit_after>#include "FAST/Tests/catch.hpp"
#include "TubeSegmentationAndCenterlineExtraction.hpp"
#include "FAST/Importers/ImageFileImporter.hpp"
#include "FAST/Visualization/SliceRenderer/SliceRenderer.hpp"
#include "FAST/Visualization/LineRenderer/LineRenderer.hpp"
#include "FAST/Algorithms/SurfaceExtraction/SurfaceExtraction.hpp"
#include "FAST/Visualization/MeshRenderer/MeshRenderer.hpp"
#include "FAST/Visualization/SimpleWindow.hpp"
#include "FAST/Algorithms/ImageCropper/ImageCropper.hpp"

namespace fast {

/*
TEST_CASE("TSF", "[tsf]") {
    ImageFileImporter::pointer importer = ImageFileImporter::New();
    importer->setFilename("/home/smistad/Dropbox/Programmering/Tube-Segmentation-Framework/tests/data/synthetic/dataset_1/noisy.mhd");

    TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New();
    tubeExtraction->setInputConnection(importer->getOutputPort());
    tubeExtraction->extractBrightTubes();
    tubeExtraction->setMinimumRadius(0.5);
    tubeExtraction->setMaximumRadius(8);
    tubeExtraction->setSensitivity(0.99);

    SliceRenderer::pointer renderer = SliceRenderer::New();
    renderer->setInputConnection(tubeExtraction->getTDFOutputPort());

    LineRenderer::pointer lineRenderer = LineRenderer::New();
    lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort());
    lineRenderer->setDefaultDrawOnTop(true);

    SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New();
    surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort());

    MeshRenderer::pointer meshRenderer = MeshRenderer::New();
    meshRenderer->addInputConnection(surfaceExtraction->getOutputPort());

    SimpleWindow::pointer window = SimpleWindow::New();
    window->addRenderer(renderer);
    window->addRenderer(meshRenderer);
    window->addRenderer(lineRenderer);
    window->start();
}
*/

TEST_CASE("TSF Airway", "[tsf][airway][visual]") {
    //Report::setReportMethod(Report::COUT);
    ImageFileImporter::pointer importer = ImageFileImporter::New();
    importer->setFilename(std::string(FAST_TEST_DATA_DIR) + "CT-Thorax.mhd");

    ImageCropper::pointer cropper = ImageCropper::New();
    cropper->setOffset(Vector3ui(56, 119, 155));
    cropper->setSize(Vector3ui(400, 232, 509));
    cropper->setInputConnection(importer->getOutputPort());

    TubeSegmentationAndCenterlineExtraction::pointer tubeExtraction = TubeSegmentationAndCenterlineExtraction::New();
    tubeExtraction->setInputConnection(cropper->getOutputPort());
    tubeExtraction->extractDarkTubes();
    tubeExtraction->setMinimumIntensity(-1024);
    tubeExtraction->setMaximumIntensity(100);
    tubeExtraction->setMinimumRadius(0.5);
    tubeExtraction->setMaximumRadius(50);
    tubeExtraction->setSensitivity(0.8);

    SliceRenderer::pointer renderer = SliceRenderer::New();
    renderer->setInputConnection(importer->getOutputPort());

    LineRenderer::pointer lineRenderer = LineRenderer::New();
    lineRenderer->addInputConnection(tubeExtraction->getCenterlineOutputPort());
    lineRenderer->setDefaultDrawOnTop(true);

    SurfaceExtraction::pointer surfaceExtraction = SurfaceExtraction::New();
    surfaceExtraction->setInputConnection(tubeExtraction->getSegmentationOutputPort());

    MeshRenderer::pointer meshRenderer = MeshRenderer::New();
    meshRenderer->addInputConnection(surfaceExtraction->getOutputPort());

    SimpleWindow::pointer window = SimpleWindow::New();
    window->addRenderer(renderer);
    window->addRenderer(meshRenderer);
    window->addRenderer(lineRenderer);
    window->start();
}

}
<|endoftext|>


<commit_before>#include "ExtendedKalmanFilter4d.h"

bool ExtendedKalmanFilter4d::useCamTop = false;

ExtendedKalmanFilter4d::ExtendedKalmanFilter4d(const Eigen::Vector4d& state, const Eigen::Matrix2d& processNoiseStdSingleDimension, const Eigen::Matrix2d& measurementNoiseStd, const Eigen::Matrix2d& initialStateStdSingleDimension, const CameraMatrix& camMat, const CameraMatrixTop& camMatTop, const naoth::CameraInfo& camInfo, const naoth::CameraInfoTop& camInfoTop):
    camMat(&camMat),
    camMatTop(&camMatTop),
    camInfo(&camInfo),
    camInfoTop(&camInfoTop),
    x(state)
{
    Eigen::Matrix2d q;
    q = processNoiseStdSingleDimension.cwiseProduct(processNoiseStdSingleDimension);

    // covariance matrix of process noise (values taken from old kalman filter)
    Q << q, Eigen::Matrix2d::Zero(), Eigen::Matrix2d::Zero(), q;

    Eigen::Matrix2d r;
    r = measurementNoiseStd.cwiseProduct(measurementNoiseStd);

    // covariance matrix of measurement noise (values taken from old kalman filter)
    R << r;

    // inital covariance matrix of current state (values taken from old kalman filter)
    //double p = 62500;
    Eigen::Matrix2d p;
    p = initialStateStdSingleDimension.cwiseProduct(initialStateStdSingleDimension);
    P << p, Eigen::Matrix2d::Zero(), Eigen::Matrix2d::Zero(), p;

    P_pre = P;  // covariance matrix of predicted state
    P_corr = P; // covariance matrix of corrected state

    x_pre = x;
    x_corr = x;
}

ExtendedKalmanFilter4d::~ExtendedKalmanFilter4d()
{

}

void ExtendedKalmanFilter4d::prediction(const Eigen::Vector2d& /*u*/, double dt)
{
    // adapt state transition matrix
    F << 1, dt, 0, 0,
         0,  1, 0, 0,
         0,  0, 1, dt,
         0,  0, 0, 1;

    F = Eigen::Matrix4d::Identity();

    // adapt control matrix to dt
    B << dt*dt/2, 0,
         dt     , 0,
         0      , dt*dt/2,
         0      , dt;

    // predict
    x_pre = F * x /*+ B * u*/;
    P_pre = F * P * F.transpose() + Q;

    x = x_pre;
    P = P_pre;
}

void ExtendedKalmanFilter4d::update(const Eigen::Vector2d& z)
{
    Eigen::Vector2d predicted_measurement;

    predicted_measurement = getStateInMeasurementSpace();

    // approximate H with central differential quotient

    bool in_front_of_plane = true;
    double h = 0.0001;
    Vector2d dx1, dx2, dy1, dy2;

    if(useCamTop) {
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMatTop, *camInfoTop, Vector3d(x(0)-h, x(2), ball_height), dx1);
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMatTop, *camInfoTop, Vector3d(x(0)+h, x(2), ball_height), dx2);
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMatTop, *camInfoTop, Vector3d(x(0), x(2)-h, ball_height), dy1);
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMatTop, *camInfoTop, Vector3d(x(0), x(2)+h, ball_height), dy2);

        dx1 = CameraGeometry::angleToPointInImage(*camMatTop,*camInfoTop,dx1.x,dx1.y);
        dx2 = CameraGeometry::angleToPointInImage(*camMatTop,*camInfoTop,dx2.x,dx2.y);
        dy1 = CameraGeometry::angleToPointInImage(*camMatTop,*camInfoTop,dy1.x,dy1.y);
        dy2 = CameraGeometry::angleToPointInImage(*camMatTop,*camInfoTop,dy2.x,dy2.y);
    } else {
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMat, *camInfo, Vector3d(x(0)-h, x(2), ball_height), dx1);
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMat, *camInfo, Vector3d(x(0)+h, x(2), ball_height), dx2);
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMat, *camInfo, Vector3d(x(0), x(2)-h, ball_height), dy1);
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMat, *camInfo, Vector3d(x(0), x(2)+h, ball_height), dy2);

        dx1 = CameraGeometry::angleToPointInImage(*camMat,*camInfo,dx1.x,dx1.y);
        dx2 = CameraGeometry::angleToPointInImage(*camMat,*camInfo,dx2.x,dx2.y);
        dy1 = CameraGeometry::angleToPointInImage(*camMat,*camInfo,dy1.x,dy1.y);
        dy2 = CameraGeometry::angleToPointInImage(*camMat,*camInfo,dy2.x,dy2.y);
    }

    Vector2d dx = (dx2-dx1)/(2*h);
    Vector2d dy = (dy2-dy1)/(2*h);

    Eigen::Matrix<double,2,4> H_approx;
    H_approx << dx.x, 0, dy.x, 0,
                dx.y, 0, dy.y, 0;

    // use approximation
    H = H_approx;

    Eigen::Matrix2d temp1 = H * P_pre * H.transpose() + R;

    K = P_pre * H.transpose() * temp1.inverse();

    // just for debugging - begin
    x_pre = x;
    P_pre = P;
    // just for debugging - end

    x_corr = x_pre + K * (z - predicted_measurement);

    P_corr = (Eigen::Matrix4d::Identity()-K*H)*P_pre;

    x = x_corr;
    P = P_corr;
}

Eigen::Vector2d ExtendedKalmanFilter4d::createMeasurementVector(const BallPercept& bp)
{
    Vector2d angles;
    Eigen::Vector2d z;

    angles = CameraGeometry::angleToPointInImage(*camMat,*camInfo,bp.centerInImage.x,bp.centerInImage.y);

    z << angles.x, angles.y;

    useCamTop = false;

    return z;
}

Eigen::Vector2d ExtendedKalmanFilter4d::createMeasurementVector(const BallPerceptTop& bp)
{
    Vector2d angles;
    Eigen::Vector2d z;

    angles = CameraGeometry::angleToPointInImage(*camMatTop,*camInfoTop,bp.centerInImage.x,bp.centerInImage.y);

    z << angles.x, angles.y;

    useCamTop = true;

    return z;
}

//--- setter ---//

void ExtendedKalmanFilter4d::setState(Eigen::Vector4d& state)
{
    x = state;
}

void ExtendedKalmanFilter4d::setCovarianceOfProcessNoise(const Eigen::Matrix2d& q){
    Q << q, Eigen::Matrix2d::Zero(), Eigen::Matrix2d::Zero(), q;
}

void ExtendedKalmanFilter4d::setCovarianceOfMeasurementNoise(const Eigen::Matrix2d& r){
    R << r;
}

//--- getter ---//

const Eigen::Vector4d& ExtendedKalmanFilter4d::getState() const
{
    return x;
}

const Eigen::Matrix4d& ExtendedKalmanFilter4d::getProcessCovariance() const
{
    return P;
}

const Eigen::Matrix2d& ExtendedKalmanFilter4d::getMeasurementCovariance() const
{
    return R;
}

Eigen::Vector2d ExtendedKalmanFilter4d::getStateInMeasurementSpace() const
{
    bool in_front_of_plane;
    Vector3d point(x(0), x(2), ball_height);
    Vector2d pointInImage;

    Vector2d angles;

    if(useCamTop){
        in_front_of_plane = CameraGeometry::relativePointToImage(*camMatTop, *camInfoTop, point, pointInImage);
        angles            = CameraGeometry::angleToPointInImage(*camMatTop,*camInfoTop,pointInImage.x,pointInImage.y);
    }
    else {
        in_front_of_plane = CameraGeometry::relativePointToImage(*camMat, *camInfo, point, pointInImage);
        angles            = CameraGeometry::angleToPointInImage(*camMat,*camInfo,pointInImage.x,pointInImage.y);
    }

    Eigen::Vector2d z;

    if(in_front_of_plane)
        z << angles.x, angles.y;// angle horizontal, angle vertical
    else
        z << std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity();

    return z;
}
<commit_msg>use acceleration and deceleration again<commit_after>#include "ExtendedKalmanFilter4d.h"

bool ExtendedKalmanFilter4d::useCamTop = false;

ExtendedKalmanFilter4d::ExtendedKalmanFilter4d(const Eigen::Vector4d& state, const Eigen::Matrix2d& processNoiseStdSingleDimension, const Eigen::Matrix2d& measurementNoiseStd, const Eigen::Matrix2d& initialStateStdSingleDimension, const CameraMatrix& camMat, const CameraMatrixTop& camMatTop, const naoth::CameraInfo& camInfo, const naoth::CameraInfoTop& camInfoTop):
    camMat(&camMat),
    camMatTop(&camMatTop),
    camInfo(&camInfo),
    camInfoTop(&camInfoTop),
    x(state)
{
    Eigen::Matrix2d q;
    q = processNoiseStdSingleDimension.cwiseProduct(processNoiseStdSingleDimension);

    // covariance matrix of process noise (values taken from old kalman filter)
    Q << q, Eigen::Matrix2d::Zero(), Eigen::Matrix2d::Zero(), q;

    Eigen::Matrix2d r;
    r = measurementNoiseStd.cwiseProduct(measurementNoiseStd);

    // covariance matrix of measurement noise (values taken from old kalman filter)
    R << r;

    // inital covariance matrix of current state (values taken from old kalman filter)
    //double p = 62500;
    Eigen::Matrix2d p;
    p = initialStateStdSingleDimension.cwiseProduct(initialStateStdSingleDimension);
    P << p, Eigen::Matrix2d::Zero(), Eigen::Matrix2d::Zero(), p;

    P_pre = P;  // covariance matrix of predicted state
    P_corr = P; // covariance matrix of corrected state

    x_pre = x;
    x_corr = x;
}

ExtendedKalmanFilter4d::~ExtendedKalmanFilter4d()
{

}

void ExtendedKalmanFilter4d::prediction(const Eigen::Vector2d& /*u*/, double dt)
{
    // adapt state transition matrix
    F << 1, dt, 0, 0,
         0,  1, 0, 0,
         0,  0, 1, dt,
         0,  0, 0, 1;

    // adapt control matrix to dt
    B << dt*dt/2, 0,
         dt     , 0,
         0      , dt*dt/2,
         0      , dt;

    // predict
    x_pre = F * x + B * u;
    P_pre = F * P * F.transpose() + Q;

    x = x_pre;
    P = P_pre;
}

void ExtendedKalmanFilter4d::update(const Eigen::Vector2d& z)
{
    Eigen::Vector2d predicted_measurement;

    predicted_measurement = getStateInMeasurementSpace();

    // approximate H with central differential quotient

    bool in_front_of_plane = true;
    double h = 0.0001;
    Vector2d dx1, dx2, dy1, dy2;

    if(useCamTop) {
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMatTop, *camInfoTop, Vector3d(x(0)-h, x(2), ball_height), dx1);
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMatTop, *camInfoTop, Vector3d(x(0)+h, x(2), ball_height), dx2);
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMatTop, *camInfoTop, Vector3d(x(0), x(2)-h, ball_height), dy1);
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMatTop, *camInfoTop, Vector3d(x(0), x(2)+h, ball_height), dy2);

        dx1 = CameraGeometry::angleToPointInImage(*camMatTop,*camInfoTop,dx1.x,dx1.y);
        dx2 = CameraGeometry::angleToPointInImage(*camMatTop,*camInfoTop,dx2.x,dx2.y);
        dy1 = CameraGeometry::angleToPointInImage(*camMatTop,*camInfoTop,dy1.x,dy1.y);
        dy2 = CameraGeometry::angleToPointInImage(*camMatTop,*camInfoTop,dy2.x,dy2.y);
    } else {
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMat, *camInfo, Vector3d(x(0)-h, x(2), ball_height), dx1);
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMat, *camInfo, Vector3d(x(0)+h, x(2), ball_height), dx2);
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMat, *camInfo, Vector3d(x(0), x(2)-h, ball_height), dy1);
        in_front_of_plane = in_front_of_plane && CameraGeometry::relativePointToImage(*camMat, *camInfo, Vector3d(x(0), x(2)+h, ball_height), dy2);

        dx1 = CameraGeometry::angleToPointInImage(*camMat,*camInfo,dx1.x,dx1.y);
        dx2 = CameraGeometry::angleToPointInImage(*camMat,*camInfo,dx2.x,dx2.y);
        dy1 = CameraGeometry::angleToPointInImage(*camMat,*camInfo,dy1.x,dy1.y);
        dy2 = CameraGeometry::angleToPointInImage(*camMat,*camInfo,dy2.x,dy2.y);
    }

    Vector2d dx = (dx2-dx1)/(2*h);
    Vector2d dy = (dy2-dy1)/(2*h);

    Eigen::Matrix<double,2,4> H_approx;
    H_approx << dx.x, 0, dy.x, 0,
                dx.y, 0, dy.y, 0;

    // use approximation
    H = H_approx;

    Eigen::Matrix2d temp1 = H * P_pre * H.transpose() + R;

    K = P_pre * H.transpose() * temp1.inverse();

    // just for debugging - begin
    x_pre = x;
    P_pre = P;
    // just for debugging - end

    x_corr = x_pre + K * (z - predicted_measurement);

    P_corr = (Eigen::Matrix4d::Identity()-K*H)*P_pre;

    x = x_corr;
    P = P_corr;
}

Eigen::Vector2d ExtendedKalmanFilter4d::createMeasurementVector(const BallPercept& bp)
{
    Vector2d angles;
    Eigen::Vector2d z;

    angles = CameraGeometry::angleToPointInImage(*camMat,*camInfo,bp.centerInImage.x,bp.centerInImage.y);

    z << angles.x, angles.y;

    useCamTop = false;

    return z;
}

Eigen::Vector2d ExtendedKalmanFilter4d::createMeasurementVector(const BallPerceptTop& bp)
{
    Vector2d angles;
    Eigen::Vector2d z;

    angles = CameraGeometry::angleToPointInImage(*camMatTop,*camInfoTop,bp.centerInImage.x,bp.centerInImage.y);

    z << angles.x, angles.y;

    useCamTop = true;

    return z;
}

//--- setter ---//

void ExtendedKalmanFilter4d::setState(Eigen::Vector4d& state)
{
    x = state;
}

void ExtendedKalmanFilter4d::setCovarianceOfProcessNoise(const Eigen::Matrix2d& q){
    Q << q, Eigen::Matrix2d::Zero(), Eigen::Matrix2d::Zero(), q;
}

void ExtendedKalmanFilter4d::setCovarianceOfMeasurementNoise(const Eigen::Matrix2d& r){
    R << r;
}

//--- getter ---//

const Eigen::Vector4d& ExtendedKalmanFilter4d::getState() const
{
    return x;
}

const Eigen::Matrix4d& ExtendedKalmanFilter4d::getProcessCovariance() const
{
    return P;
}

const Eigen::Matrix2d& ExtendedKalmanFilter4d::getMeasurementCovariance() const
{
    return R;
}

Eigen::Vector2d ExtendedKalmanFilter4d::getStateInMeasurementSpace() const
{
    bool in_front_of_plane;
    Vector3d point(x(0), x(2), ball_height);
    Vector2d pointInImage;

    Vector2d angles;

    if(useCamTop){
        in_front_of_plane = CameraGeometry::relativePointToImage(*camMatTop, *camInfoTop, point, pointInImage);
        angles            = CameraGeometry::angleToPointInImage(*camMatTop,*camInfoTop,pointInImage.x,pointInImage.y);
    }
    else {
        in_front_of_plane = CameraGeometry::relativePointToImage(*camMat, *camInfo, point, pointInImage);
        angles            = CameraGeometry::angleToPointInImage(*camMat,*camInfo,pointInImage.x,pointInImage.y);
    }

    Eigen::Vector2d z;

    if(in_front_of_plane)
        z << angles.x, angles.y;// angle horizontal, angle vertical
    else
        z << std::numeric_limits<double>::infinity(), std::numeric_limits<double>::infinity();

    return z;
}
<|endoftext|>


<commit_before>#include "Runtime/World/CScriptDamageableTrigger.hpp"

#include "Runtime/CStateManager.hpp"
#include "Runtime/World/CActorParameters.hpp"
#include "Runtime/World/CScriptActor.hpp"
#include "Runtime/World/CWorld.hpp"

#include "TCastTo.hpp" // Generated file, do not modify include path

namespace urde {
CActorParameters MakeDamageableTriggerActorParms(const CActorParameters& aParams, const CVisorParameters& vParams) {
  CActorParameters ret = aParams;
  ret.SetVisorParameters(vParams);
  return ret;
}

CMaterialList MakeDamageableTriggerMaterial(CScriptDamageableTrigger::ECanOrbit canOrbit) {
  if (canOrbit == CScriptDamageableTrigger::ECanOrbit::Orbit)
    return CMaterialList(EMaterialTypes::Orbit, EMaterialTypes::Trigger, EMaterialTypes::Immovable,
                         EMaterialTypes::NonSolidDamageable, EMaterialTypes::ExcludeFromLineOfSightTest);
  return CMaterialList(EMaterialTypes::Trigger, EMaterialTypes::Immovable, EMaterialTypes::NonSolidDamageable,
                       EMaterialTypes::ExcludeFromLineOfSightTest);
}

CScriptDamageableTrigger::CScriptDamageableTrigger(TUniqueId uid, std::string_view name, const CEntityInfo& info,
                                                   const zeus::CVector3f& position, const zeus::CVector3f& extent,
                                                   const CHealthInfo& hInfo, const CDamageVulnerability& dVuln,
                                                   u32 faceFlag, CAssetId patternTex1, CAssetId patternTex2,
                                                   CAssetId colorTex, ECanOrbit canOrbit, bool active,
                                                   const CVisorParameters& vParams)
: CActor(uid, active, name, info, zeus::CTransform::Translate(position), CModelData::CModelDataNull(),
         MakeDamageableTriggerMaterial(canOrbit), MakeDamageableTriggerActorParms(CActorParameters::None(), vParams),
         kInvalidUniqueId)
, x14c_bounds(-extent * 0.5f, extent * 0.5f)
, x164_origHInfo(hInfo)
, x16c_hInfo(hInfo)
, x174_dVuln(dVuln)
, x1dc_faceFlag(faceFlag)
, x254_fluidPlane(patternTex1, patternTex2, colorTex, 1.f, 2, EFluidType::NormalWater, 1.f, CFluidUVMotion(6.f, 0.f))
, x300_28_canOrbit(canOrbit == ECanOrbit::Orbit) {
  if (x1dc_faceFlag & 0x1) {
    x244_faceTranslate = zeus::CVector3f(0.f, x14c_bounds.max.y(), 0.f);
    x1e4_faceDir = zeus::CTransform::RotateX(-M_PIF / 2.f);
  } else if (x1dc_faceFlag & 0x2) {
    x244_faceTranslate = zeus::CVector3f(0.f, x14c_bounds.min.y(), 0.f);
    x1e4_faceDir = zeus::CTransform::RotateX(M_PIF / 2.f);
  } else if (x1dc_faceFlag & 0x4) {
    x244_faceTranslate = zeus::CVector3f(x14c_bounds.min.x(), 0.f, 0.f);
    x1e4_faceDir = zeus::CTransform::RotateY(-M_PIF / 2.f);
  } else if (x1dc_faceFlag & 0x8) {
    x244_faceTranslate = zeus::CVector3f(x14c_bounds.max.x(), 0.f, 0.f);
    x1e4_faceDir = zeus::CTransform::RotateY(M_PIF / 2.f);
  } else if (x1dc_faceFlag & 0x10) {
    x244_faceTranslate = zeus::CVector3f(0.f, 0.f, x14c_bounds.max.z());
    x1e4_faceDir = zeus::CTransform();
  } else if (x1dc_faceFlag & 0x20) {
    x244_faceTranslate = zeus::CVector3f(0.f, 0.f, x14c_bounds.min.z());
    x1e4_faceDir = zeus::CTransform::RotateY(M_PIF);
  }

  x214_faceDirInv = x1e4_faceDir.inverse();
}

void CScriptDamageableTrigger::Accept(IVisitor& visitor) { visitor.Visit(this); }

void CScriptDamageableTrigger::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId sender, CStateManager& mgr) {
  switch (msg) {
  case EScriptObjectMessage::Deactivate:
    if (x30_24_active && x300_25_alphaOut)
      return;
    [[fallthrough]];
  case EScriptObjectMessage::Activate:
    if (!x30_24_active || x300_25_alphaOut) {
      x250_alphaTimer = 0.f;
      x16c_hInfo = x164_origHInfo;
      x300_25_alphaOut = false;
      if (x300_28_canOrbit)
        AddMaterial(EMaterialTypes::Orbit, mgr);
      SetLinkedObjectAlpha(0.f, mgr);
      x1e0_alpha = 0.f;
    }
    break;
  case EScriptObjectMessage::Damage:
    if (x300_27_invulnerable)
      x16c_hInfo = x164_origHInfo;
    break;
  case EScriptObjectMessage::Increment:
    x300_27_invulnerable = true;
    break;
  case EScriptObjectMessage::Decrement:
    x300_27_invulnerable = false;
    break;
  default:
    break;
  }

  CActor::AcceptScriptMsg(msg, sender, mgr);
}

EWeaponCollisionResponseTypes CScriptDamageableTrigger::GetCollisionResponseType(const zeus::CVector3f&,
                                                                                const zeus::CVector3f&,
                                                                                const CWeaponMode& weapMode,
                                                                                EProjectileAttrib) const {
  return x174_dVuln.WeaponHurts(weapMode, false) ? EWeaponCollisionResponseTypes::OtherProjectile
                                                 : EWeaponCollisionResponseTypes::Unknown15;
}

void CScriptDamageableTrigger::Render(CStateManager& mgr) {
  if (x30_24_active && x1dc_faceFlag != 0 && std::fabs(x1e0_alpha) >= 0.00001f) {
    zeus::CAABox aabb = x14c_bounds.getTransformedAABox(x214_faceDirInv);
    zeus::CTransform xf = x34_transform * zeus::CTransform::Translate(x244_faceTranslate) * x1e4_faceDir;
    x254_fluidPlane.Render(mgr, x1e0_alpha, aabb, xf, zeus::CTransform(), false, xe8_frustum, {},
                           kInvalidUniqueId, nullptr, 0, 0, zeus::skZero3f);
  }

  CActor::Render(mgr);
}

void CScriptDamageableTrigger::AddToRenderer(const zeus::CFrustum& /*frustum*/, CStateManager& mgr) {
  if (x300_26_outOfFrustum) {
    return;
  }

  EnsureRendered(mgr, GetTranslation() - x244_faceTranslate, GetSortingBounds(mgr));
}

void CScriptDamageableTrigger::PreRender(CStateManager& mgr, const zeus::CFrustum& frustum) {
  x300_26_outOfFrustum = !frustum.aabbFrustumTest(x14c_bounds.getTransformedAABox(x34_transform));
  if (!x300_26_outOfFrustum) {
    xe8_frustum = frustum;
    CActor::PreRender(mgr, frustum);
  }
}

void CScriptDamageableTrigger::SetLinkedObjectAlpha(float a, CStateManager& mgr) {
  for (const SConnection& conn : x20_conns) {
    if (conn.x0_state != EScriptObjectState::MaxReached || conn.x4_msg != EScriptObjectMessage::Activate)
      continue;
    if (TCastToPtr<CScriptActor> act = mgr.ObjectById(mgr.GetIdForScript(conn.x8_objId))) {
      if (!act->GetActive())
        act->SetActive(true);
      act->SetDrawFlags(CModelFlags(5, 0, 3, zeus::CColor(1.f, a)));
    }
  }
}

float CScriptDamageableTrigger::GetPuddleAlphaScale() const {
  if (x250_alphaTimer <= 0.75f) {
    if (x300_25_alphaOut)
      return 1.f - x250_alphaTimer / 0.75f;
    return x250_alphaTimer / 0.75f;
  }

  if (x300_25_alphaOut)
    return 0.f;
  return 1.f;
}

void CScriptDamageableTrigger::Think(float dt, CStateManager& mgr) {
  if (!GetActive())
    return;

  const CGameArea* area = mgr.GetWorld()->GetAreaAlways(GetAreaIdAlways());
  CGameArea::EOcclusionState occState =
      area->IsPostConstructed() ? area->GetOcclusionState() : CGameArea::EOcclusionState::Occluded;
  x300_24_notOccluded = occState == CGameArea::EOcclusionState::Visible;

  if (x300_25_alphaOut) {
    if (x250_alphaTimer >= 0.75f) {
      SetActive(false);
      for (const SConnection& conn : x20_conns) {
        if (conn.x0_state != EScriptObjectState::MaxReached || conn.x4_msg != EScriptObjectMessage::Activate)
          continue;
        if (TCastToPtr<CScriptActor> act = mgr.ObjectById(mgr.GetIdForScript(conn.x8_objId)))
          act->SetActive(false);
      }

      SetLinkedObjectAlpha(0.f, mgr);
      x300_25_alphaOut = false;
      return;
    }
  } else if (x16c_hInfo.GetHP() <= 0.f && x30_24_active) {
    SendScriptMsgs(EScriptObjectState::Dead, mgr, EScriptObjectMessage::None);
    RemoveMaterial(EMaterialTypes::Orbit, mgr);
    x300_25_alphaOut = true;
    x250_alphaTimer = 0.f;
  }

  if (x250_alphaTimer <= 0.75f)
    x250_alphaTimer += dt;

  float objAlpha = GetPuddleAlphaScale();
  x1e0_alpha = 0.2f * objAlpha;
  SetLinkedObjectAlpha(objAlpha, mgr);
}

std::optional<zeus::CAABox> CScriptDamageableTrigger::GetTouchBounds() const {
  if (x30_24_active && x300_24_notOccluded) {
    return zeus::CAABox(x14c_bounds.min + GetTranslation(), x14c_bounds.max + GetTranslation());
  }
  return std::nullopt;
}

} // namespace urde
<commit_msg>CScriptDamageableTrigger: Mark helper functions as static where applicable<commit_after>#include "Runtime/World/CScriptDamageableTrigger.hpp"

#include "Runtime/CStateManager.hpp"
#include "Runtime/World/CActorParameters.hpp"
#include "Runtime/World/CScriptActor.hpp"
#include "Runtime/World/CWorld.hpp"

#include "TCastTo.hpp" // Generated file, do not modify include path

namespace urde {
static CActorParameters MakeDamageableTriggerActorParms(const CActorParameters& aParams, const CVisorParameters& vParams) {
  CActorParameters ret = aParams;
  ret.SetVisorParameters(vParams);
  return ret;
}

static constexpr CMaterialList MakeDamageableTriggerMaterial(CScriptDamageableTrigger::ECanOrbit canOrbit) {
  if (canOrbit == CScriptDamageableTrigger::ECanOrbit::Orbit) {
    return CMaterialList(EMaterialTypes::Orbit, EMaterialTypes::Trigger, EMaterialTypes::Immovable,
                         EMaterialTypes::NonSolidDamageable, EMaterialTypes::ExcludeFromLineOfSightTest);
  }
  return CMaterialList(EMaterialTypes::Trigger, EMaterialTypes::Immovable, EMaterialTypes::NonSolidDamageable,
                       EMaterialTypes::ExcludeFromLineOfSightTest);
}

CScriptDamageableTrigger::CScriptDamageableTrigger(TUniqueId uid, std::string_view name, const CEntityInfo& info,
                                                   const zeus::CVector3f& position, const zeus::CVector3f& extent,
                                                   const CHealthInfo& hInfo, const CDamageVulnerability& dVuln,
                                                   u32 faceFlag, CAssetId patternTex1, CAssetId patternTex2,
                                                   CAssetId colorTex, ECanOrbit canOrbit, bool active,
                                                   const CVisorParameters& vParams)
: CActor(uid, active, name, info, zeus::CTransform::Translate(position), CModelData::CModelDataNull(),
         MakeDamageableTriggerMaterial(canOrbit), MakeDamageableTriggerActorParms(CActorParameters::None(), vParams),
         kInvalidUniqueId)
, x14c_bounds(-extent * 0.5f, extent * 0.5f)
, x164_origHInfo(hInfo)
, x16c_hInfo(hInfo)
, x174_dVuln(dVuln)
, x1dc_faceFlag(faceFlag)
, x254_fluidPlane(patternTex1, patternTex2, colorTex, 1.f, 2, EFluidType::NormalWater, 1.f, CFluidUVMotion(6.f, 0.f))
, x300_28_canOrbit(canOrbit == ECanOrbit::Orbit) {
  if (x1dc_faceFlag & 0x1) {
    x244_faceTranslate = zeus::CVector3f(0.f, x14c_bounds.max.y(), 0.f);
    x1e4_faceDir = zeus::CTransform::RotateX(-M_PIF / 2.f);
  } else if (x1dc_faceFlag & 0x2) {
    x244_faceTranslate = zeus::CVector3f(0.f, x14c_bounds.min.y(), 0.f);
    x1e4_faceDir = zeus::CTransform::RotateX(M_PIF / 2.f);
  } else if (x1dc_faceFlag & 0x4) {
    x244_faceTranslate = zeus::CVector3f(x14c_bounds.min.x(), 0.f, 0.f);
    x1e4_faceDir = zeus::CTransform::RotateY(-M_PIF / 2.f);
  } else if (x1dc_faceFlag & 0x8) {
    x244_faceTranslate = zeus::CVector3f(x14c_bounds.max.x(), 0.f, 0.f);
    x1e4_faceDir = zeus::CTransform::RotateY(M_PIF / 2.f);
  } else if (x1dc_faceFlag & 0x10) {
    x244_faceTranslate = zeus::CVector3f(0.f, 0.f, x14c_bounds.max.z());
    x1e4_faceDir = zeus::CTransform();
  } else if (x1dc_faceFlag & 0x20) {
    x244_faceTranslate = zeus::CVector3f(0.f, 0.f, x14c_bounds.min.z());
    x1e4_faceDir = zeus::CTransform::RotateY(M_PIF);
  }

  x214_faceDirInv = x1e4_faceDir.inverse();
}

void CScriptDamageableTrigger::Accept(IVisitor& visitor) { visitor.Visit(this); }

void CScriptDamageableTrigger::AcceptScriptMsg(EScriptObjectMessage msg, TUniqueId sender, CStateManager& mgr) {
  switch (msg) {
  case EScriptObjectMessage::Deactivate:
    if (x30_24_active && x300_25_alphaOut)
      return;
    [[fallthrough]];
  case EScriptObjectMessage::Activate:
    if (!x30_24_active || x300_25_alphaOut) {
      x250_alphaTimer = 0.f;
      x16c_hInfo = x164_origHInfo;
      x300_25_alphaOut = false;
      if (x300_28_canOrbit)
        AddMaterial(EMaterialTypes::Orbit, mgr);
      SetLinkedObjectAlpha(0.f, mgr);
      x1e0_alpha = 0.f;
    }
    break;
  case EScriptObjectMessage::Damage:
    if (x300_27_invulnerable)
      x16c_hInfo = x164_origHInfo;
    break;
  case EScriptObjectMessage::Increment:
    x300_27_invulnerable = true;
    break;
  case EScriptObjectMessage::Decrement:
    x300_27_invulnerable = false;
    break;
  default:
    break;
  }

  CActor::AcceptScriptMsg(msg, sender, mgr);
}

EWeaponCollisionResponseTypes CScriptDamageableTrigger::GetCollisionResponseType(const zeus::CVector3f&,
                                                                                const zeus::CVector3f&,
                                                                                const CWeaponMode& weapMode,
                                                                                EProjectileAttrib) const {
  return x174_dVuln.WeaponHurts(weapMode, false) ? EWeaponCollisionResponseTypes::OtherProjectile
                                                 : EWeaponCollisionResponseTypes::Unknown15;
}

void CScriptDamageableTrigger::Render(CStateManager& mgr) {
  if (x30_24_active && x1dc_faceFlag != 0 && std::fabs(x1e0_alpha) >= 0.00001f) {
    zeus::CAABox aabb = x14c_bounds.getTransformedAABox(x214_faceDirInv);
    zeus::CTransform xf = x34_transform * zeus::CTransform::Translate(x244_faceTranslate) * x1e4_faceDir;
    x254_fluidPlane.Render(mgr, x1e0_alpha, aabb, xf, zeus::CTransform(), false, xe8_frustum, {},
                           kInvalidUniqueId, nullptr, 0, 0, zeus::skZero3f);
  }

  CActor::Render(mgr);
}

void CScriptDamageableTrigger::AddToRenderer(const zeus::CFrustum& /*frustum*/, CStateManager& mgr) {
  if (x300_26_outOfFrustum) {
    return;
  }

  EnsureRendered(mgr, GetTranslation() - x244_faceTranslate, GetSortingBounds(mgr));
}

void CScriptDamageableTrigger::PreRender(CStateManager& mgr, const zeus::CFrustum& frustum) {
  x300_26_outOfFrustum = !frustum.aabbFrustumTest(x14c_bounds.getTransformedAABox(x34_transform));
  if (!x300_26_outOfFrustum) {
    xe8_frustum = frustum;
    CActor::PreRender(mgr, frustum);
  }
}

void CScriptDamageableTrigger::SetLinkedObjectAlpha(float a, CStateManager& mgr) {
  for (const SConnection& conn : x20_conns) {
    if (conn.x0_state != EScriptObjectState::MaxReached || conn.x4_msg != EScriptObjectMessage::Activate)
      continue;
    if (TCastToPtr<CScriptActor> act = mgr.ObjectById(mgr.GetIdForScript(conn.x8_objId))) {
      if (!act->GetActive())
        act->SetActive(true);
      act->SetDrawFlags(CModelFlags(5, 0, 3, zeus::CColor(1.f, a)));
    }
  }
}

float CScriptDamageableTrigger::GetPuddleAlphaScale() const {
  if (x250_alphaTimer <= 0.75f) {
    if (x300_25_alphaOut)
      return 1.f - x250_alphaTimer / 0.75f;
    return x250_alphaTimer / 0.75f;
  }

  if (x300_25_alphaOut)
    return 0.f;
  return 1.f;
}

void CScriptDamageableTrigger::Think(float dt, CStateManager& mgr) {
  if (!GetActive())
    return;

  const CGameArea* area = mgr.GetWorld()->GetAreaAlways(GetAreaIdAlways());
  CGameArea::EOcclusionState occState =
      area->IsPostConstructed() ? area->GetOcclusionState() : CGameArea::EOcclusionState::Occluded;
  x300_24_notOccluded = occState == CGameArea::EOcclusionState::Visible;

  if (x300_25_alphaOut) {
    if (x250_alphaTimer >= 0.75f) {
      SetActive(false);
      for (const SConnection& conn : x20_conns) {
        if (conn.x0_state != EScriptObjectState::MaxReached || conn.x4_msg != EScriptObjectMessage::Activate)
          continue;
        if (TCastToPtr<CScriptActor> act = mgr.ObjectById(mgr.GetIdForScript(conn.x8_objId)))
          act->SetActive(false);
      }

      SetLinkedObjectAlpha(0.f, mgr);
      x300_25_alphaOut = false;
      return;
    }
  } else if (x16c_hInfo.GetHP() <= 0.f && x30_24_active) {
    SendScriptMsgs(EScriptObjectState::Dead, mgr, EScriptObjectMessage::None);
    RemoveMaterial(EMaterialTypes::Orbit, mgr);
    x300_25_alphaOut = true;
    x250_alphaTimer = 0.f;
  }

  if (x250_alphaTimer <= 0.75f)
    x250_alphaTimer += dt;

  float objAlpha = GetPuddleAlphaScale();
  x1e0_alpha = 0.2f * objAlpha;
  SetLinkedObjectAlpha(objAlpha, mgr);
}

std::optional<zeus::CAABox> CScriptDamageableTrigger::GetTouchBounds() const {
  if (x30_24_active && x300_24_notOccluded) {
    return zeus::CAABox(x14c_bounds.min + GetTranslation(), x14c_bounds.max + GetTranslation());
  }
  return std::nullopt;
}

} // namespace urde
<|endoftext|>


<commit_before>#ifndef INCLUDE_ROADAGAIN_GAME_HPP
#define INCLUDE_ROADAGAIN_GAME_HPP

#include <utility>

#include "board.hpp"

namespace roadagain
{

class Reversi : public Board
{
public:
    Reversi();
    ~Reversi();

    void start();
    void play();
    std::pair<int, int> move();
    void put(const std::pair<int, int>& point);
    bool reverse(const std::pair<int, int>& point);

    static const int DEFAULT_STONE = 4;
    static const int MAX_PUT = ROW * COL - DEFAULT_STONE;

private:
    bool reverse(const std::pair<int, int>& point, int dy, int dx);

    int black_;
    int white_;
};

}

#endif
<commit_msg>Changed several Reversi's functions private<commit_after>#ifndef INCLUDE_ROADAGAIN_GAME_HPP
#define INCLUDE_ROADAGAIN_GAME_HPP

#include <utility>

#include "board.hpp"

namespace roadagain
{

class Reversi : public Board
{
public:
    Reversi();
    ~Reversi();

    void start();
    void play();

    static const int DEFAULT_STONE = 4;
    static const int MAX_PUT = ROW * COL - DEFAULT_STONE;

private:
    std::pair<int, int> move();
    void put(const std::pair<int, int>& point);
    bool reverse(const std::pair<int, int>& point);
    bool reverse(const std::pair<int, int>& point, int dy, int dx);

    int black_;
    int white_;
};

}

#endif
<|endoftext|>


<commit_before>/**
 * @file  shared_ptr.hpp
 * @brief shared_ptr is a minimal implementation of smart pointer, a subset of the C++11 std::shared_ptr or boost::shared_ptr.
 *
 * Copyright (c) 2013 Sebastien Rombauts (sebastien.rombauts@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */
#pragma once

#include <cstddef>      // NULL
#include <algorithm>    // std::swap

// can be replaced by other error mechanism
#include <cassert>
#define SHARED_ASSERT(x)    assert(x)

/**
 * @brief minimal implementation of smart pointer, a subset of the C++11 std::shared_ptr or boost::shared_ptr.
 *
 * shared_ptr is a smart pointer retaining ownership of an object through a provided pointer,
 * and sharing this ownership with a reference counter.
 * It destroys the object when the last shared pointer pointing to it is destroyed or reset.
 */
template<class T>
class shared_ptr
{
public:
   typedef T element_type;

   /// @brief Default constructor
    shared_ptr(void) throw() : // never throws
        px(NULL),
        pn(NULL)
    {
    }
    /// @brief Constructor with the provided pointer to manage
    explicit shared_ptr(T* p) : // may throw std::bad_alloc
      //px(p), would be unsafe as acquire() may throw, which would call release() in destructor
        pn(NULL)
    {
        acquire(p);   // may throw std::bad_alloc
    }
    /// @brief Constructor to share ownership. Warning : to be used for pointer_cast only ! (does not manage two separate <T> and <U> pointers)
    template <class U>
    shared_ptr(const shared_ptr<U>& ptr, T* p) :
     //px(p), would be unsafe as acquire() may throw, which would call release() in destructor
       pn(ptr.pn)
    {
       acquire(p);   // may throw std::bad_alloc
    }
    /// @brief Copy constructor to convert from another pointer type
    template <class U>
    shared_ptr(const shared_ptr<U>& ptr) throw() : // never throws (see comment below)
      //px(ptr.px),
        pn(ptr.pn)
    {
        SHARED_ASSERT((NULL == ptr.px) || (NULL != ptr.pn)); // must be cohérent : no allocation allowed in this path
        acquire(static_cast<typename shared_ptr<T>::element_type*>(ptr.px));   // will never throw std::bad_alloc
    }
    /// @brief Copy constructor (used by the copy-and-swap idiom)
    shared_ptr(const shared_ptr& ptr) throw() : // never throws (see comment below)
       //px(ptr.px),
        pn(ptr.pn)
    {
        SHARED_ASSERT((NULL == ptr.px) || (NULL != ptr.pn)); // must be cohérent : no allocation allowed in this path
        acquire(ptr.px);   // will never throw std::bad_alloc
    }
    /// @brief Assignment operator using the copy-and-swap idiom (copy constructor and swap method)
    shared_ptr& operator=(shared_ptr ptr) throw() // never throws
    {
        swap(ptr);
        return *this;
    }
    /// @brief the destructor releases its ownership
    inline ~shared_ptr(void) throw() // never throws
    {
        release();
    }
    /// @brief this reset releases its ownership
    inline void reset(void) throw() // never throws
    {
        release();
    }
    /// @brief this reset release its ownership and re-acquire another one
    void reset(T* p) throw() // may throw std::bad_alloc
    {
        SHARED_ASSERT((NULL == p) || (px != p)); // auto-reset not allowed
        release();
        px = NULL; // px = p would be unsafe as acquire() may throw, which would call release() in destructor
        pn = NULL;
        acquire(p); // may throw std::bad_alloc
    }

    /// @brief Swap method for the copy-and-swap idiom (copy constructor and swap method)
    void swap(shared_ptr& lhs) throw() // never throws
    {
        // Would be nice to enable use of ustl::swap by define
        std::swap(px, lhs.px);
        std::swap(pn, lhs.pn);
    }

    // reference counter operations :
    inline operator bool() const throw() // never throws
    {
        return (0 < use_count());
    }
    inline bool unique(void)  const throw() // never throws
    {
        return (1 == use_count());
    }
    long use_count(void)  const throw() // never throws
    {
        long count = 0;
        if (NULL != pn)
        {
            count = *pn;
        }
        return count;
    }

    // underlying pointer operations :
    inline T& operator*()  const throw() // never throws
    {
        SHARED_ASSERT(NULL != px);
        return *px;
    }
    inline T* operator->() const throw() // never throws
    {
        SHARED_ASSERT(NULL != px);
        return px;
    }
    inline T* get(void)  const throw() // never throws
    {
        // no assert, car return NULL
        return px;
    }

private:
    /// @brief acquire/share the ownership of the px pointer, initializing the reference counter
    void acquire(T* p) // may throw std::bad_alloc
    {
        if (NULL != p)
        {
            if (NULL == pn)
            {
                try
                {
                    pn = new long(1); // may throw std::bad_alloc
                }
                catch (std::bad_alloc&)
                {
                    delete p;
                    throw; // rethrow the std::bad_alloc
                }
            }
            else
            {
                ++(*pn);
            }
        }
        // here it is safe to acquire the ownership of the provided raw pointer, where exception cannot be thrown any more
        px = p;
    }

    /// @brief release the ownership of the px pointer, destroying the object when appropriate
    void release(void) throw() // never throws
    {
        if (NULL != pn)
        {
            --(*pn);
            if (0 == *pn)
            {
                delete px;
                delete pn;
            }
            px = NULL;
            pn = NULL;
        }
    }

private:
    // This allow pointer_cast functions to share the reference counter between different shared_ptr types
    template<class U>
    friend class shared_ptr;

private:
    T*      px; //!< Native pointer
    long*   pn; //!< Reference counter
};

// comparaison operators
template<class T, class U> inline bool operator==(const shared_ptr<T>& l, const shared_ptr<U>& r) throw() // never throws
{
    return (l.get() == r.get());
}
template<class T, class U> inline bool operator!=(const shared_ptr<T>& l, const shared_ptr<U>& r) throw() // never throws
{
    return (l.get() != r.get());
}
template<class T, class U> inline bool operator<=(const shared_ptr<T>& l, const shared_ptr<U>& r) throw() // never throws
{
    return (l.get() <= r.get());
}
template<class T, class U> inline bool operator<(const shared_ptr<T>& l, const shared_ptr<U>& r) throw() // never throws
{
    return (l.get() < r.get());
}
template<class T, class U> inline bool operator>=(const shared_ptr<T>& l, const shared_ptr<U>& r) throw() // never throws
{
    return (l.get() >= r.get());
}
template<class T, class U> inline bool operator>(const shared_ptr<T>& l, const shared_ptr<U>& r) throw() // never throws
{
    return (l.get() > r.get());
}

// static cast of shared_ptr
template<class T, class U>
shared_ptr<T> static_pointer_cast(const shared_ptr<U>& ptr) // never throws
{
    return shared_ptr<T>(ptr, static_cast<typename shared_ptr<T>::element_type*>(ptr.get()));
}

// dynamic cast of shared_ptr
template<class T, class U>
shared_ptr<T> dynamic_pointer_cast(const shared_ptr<U>& ptr) // never throws
{
    T* p = dynamic_cast<typename shared_ptr<T>::element_type*>(ptr.get());
    if (NULL != p)
    {
        return shared_ptr<T>(ptr, p);
    }
    else
    {
        return shared_ptr<T>();
    }
}
<commit_msg>No more need to clear pn/px after a call to release()<commit_after>/**
 * @file  shared_ptr.hpp
 * @brief shared_ptr is a minimal implementation of smart pointer, a subset of the C++11 std::shared_ptr or boost::shared_ptr.
 *
 * Copyright (c) 2013 Sebastien Rombauts (sebastien.rombauts@gmail.com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */
#pragma once

#include <cstddef>      // NULL
#include <algorithm>    // std::swap

// can be replaced by other error mechanism
#include <cassert>
#define SHARED_ASSERT(x)    assert(x)

/**
 * @brief minimal implementation of smart pointer, a subset of the C++11 std::shared_ptr or boost::shared_ptr.
 *
 * shared_ptr is a smart pointer retaining ownership of an object through a provided pointer,
 * and sharing this ownership with a reference counter.
 * It destroys the object when the last shared pointer pointing to it is destroyed or reset.
 */
template<class T>
class shared_ptr
{
public:
   typedef T element_type;

   /// @brief Default constructor
    shared_ptr(void) throw() : // never throws
        px(NULL),
        pn(NULL)
    {
    }
    /// @brief Constructor with the provided pointer to manage
    explicit shared_ptr(T* p) : // may throw std::bad_alloc
      //px(p), would be unsafe as acquire() may throw, which would call release() in destructor
        pn(NULL)
    {
        acquire(p);   // may throw std::bad_alloc
    }
    /// @brief Constructor to share ownership. Warning : to be used for pointer_cast only ! (does not manage two separate <T> and <U> pointers)
    template <class U>
    shared_ptr(const shared_ptr<U>& ptr, T* p) :
     //px(p), would be unsafe as acquire() may throw, which would call release() in destructor
       pn(ptr.pn)
    {
       acquire(p);   // may throw std::bad_alloc
    }
    /// @brief Copy constructor to convert from another pointer type
    template <class U>
    shared_ptr(const shared_ptr<U>& ptr) throw() : // never throws (see comment below)
      //px(ptr.px),
        pn(ptr.pn)
    {
        SHARED_ASSERT((NULL == ptr.px) || (NULL != ptr.pn)); // must be cohérent : no allocation allowed in this path
        acquire(static_cast<typename shared_ptr<T>::element_type*>(ptr.px));   // will never throw std::bad_alloc
    }
    /// @brief Copy constructor (used by the copy-and-swap idiom)
    shared_ptr(const shared_ptr& ptr) throw() : // never throws (see comment below)
       //px(ptr.px),
        pn(ptr.pn)
    {
        SHARED_ASSERT((NULL == ptr.px) || (NULL != ptr.pn)); // must be cohérent : no allocation allowed in this path
        acquire(ptr.px);   // will never throw std::bad_alloc
    }
    /// @brief Assignment operator using the copy-and-swap idiom (copy constructor and swap method)
    shared_ptr& operator=(shared_ptr ptr) throw() // never throws
    {
        swap(ptr);
        return *this;
    }
    /// @brief the destructor releases its ownership
    inline ~shared_ptr(void) throw() // never throws
    {
        release();
    }
    /// @brief this reset releases its ownership
    inline void reset(void) throw() // never throws
    {
        release();
    }
    /// @brief this reset release its ownership and re-acquire another one
    void reset(T* p) throw() // may throw std::bad_alloc
    {
        SHARED_ASSERT((NULL == p) || (px != p)); // auto-reset not allowed
        release();
        acquire(p); // may throw std::bad_alloc
    }

    /// @brief Swap method for the copy-and-swap idiom (copy constructor and swap method)
    void swap(shared_ptr& lhs) throw() // never throws
    {
        // Would be nice to enable use of ustl::swap by define
        std::swap(px, lhs.px);
        std::swap(pn, lhs.pn);
    }

    // reference counter operations :
    inline operator bool() const throw() // never throws
    {
        return (0 < use_count());
    }
    inline bool unique(void)  const throw() // never throws
    {
        return (1 == use_count());
    }
    long use_count(void)  const throw() // never throws
    {
        long count = 0;
        if (NULL != pn)
        {
            count = *pn;
        }
        return count;
    }

    // underlying pointer operations :
    inline T& operator*()  const throw() // never throws
    {
        SHARED_ASSERT(NULL != px);
        return *px;
    }
    inline T* operator->() const throw() // never throws
    {
        SHARED_ASSERT(NULL != px);
        return px;
    }
    inline T* get(void)  const throw() // never throws
    {
        // no assert, car return NULL
        return px;
    }

private:
    /// @brief acquire/share the ownership of the px pointer, initializing the reference counter
    void acquire(T* p) // may throw std::bad_alloc
    {
        if (NULL != p)
        {
            if (NULL == pn)
            {
                try
                {
                    pn = new long(1); // may throw std::bad_alloc
                }
                catch (std::bad_alloc&)
                {
                    delete p;
                    throw; // rethrow the std::bad_alloc
                }
            }
            else
            {
                ++(*pn);
            }
        }
        // here it is safe to acquire the ownership of the provided raw pointer, where exception cannot be thrown any more
        px = p;
    }

    /// @brief release the ownership of the px pointer, destroying the object when appropriate
    void release(void) throw() // never throws
    {
        if (NULL != pn)
        {
            --(*pn);
            if (0 == *pn)
            {
                delete px;
                delete pn;
            }
            px = NULL;
            pn = NULL;
        }
    }

private:
    // This allow pointer_cast functions to share the reference counter between different shared_ptr types
    template<class U>
    friend class shared_ptr;

private:
    T*      px; //!< Native pointer
    long*   pn; //!< Reference counter
};

// comparaison operators
template<class T, class U> inline bool operator==(const shared_ptr<T>& l, const shared_ptr<U>& r) throw() // never throws
{
    return (l.get() == r.get());
}
template<class T, class U> inline bool operator!=(const shared_ptr<T>& l, const shared_ptr<U>& r) throw() // never throws
{
    return (l.get() != r.get());
}
template<class T, class U> inline bool operator<=(const shared_ptr<T>& l, const shared_ptr<U>& r) throw() // never throws
{
    return (l.get() <= r.get());
}
template<class T, class U> inline bool operator<(const shared_ptr<T>& l, const shared_ptr<U>& r) throw() // never throws
{
    return (l.get() < r.get());
}
template<class T, class U> inline bool operator>=(const shared_ptr<T>& l, const shared_ptr<U>& r) throw() // never throws
{
    return (l.get() >= r.get());
}
template<class T, class U> inline bool operator>(const shared_ptr<T>& l, const shared_ptr<U>& r) throw() // never throws
{
    return (l.get() > r.get());
}

// static cast of shared_ptr
template<class T, class U>
shared_ptr<T> static_pointer_cast(const shared_ptr<U>& ptr) // never throws
{
    return shared_ptr<T>(ptr, static_cast<typename shared_ptr<T>::element_type*>(ptr.get()));
}

// dynamic cast of shared_ptr
template<class T, class U>
shared_ptr<T> dynamic_pointer_cast(const shared_ptr<U>& ptr) // never throws
{
    T* p = dynamic_cast<typename shared_ptr<T>::element_type*>(ptr.get());
    if (NULL != p)
    {
        return shared_ptr<T>(ptr, p);
    }
    else
    {
        return shared_ptr<T>();
    }
}
<|endoftext|>


<commit_before>#include "cinder/app/AppBasic.h"
#include "cinder/Json.h"
#include "Resources.h"

class JsonTestApp : public ci::app::AppBasic
{

  public:

      void draw();
	  void mouseDown( ci::app::MouseEvent event );
	  void setup();

};

using namespace ci;
using namespace ci::app;
using namespace std;

void JsonTestApp::draw()
{
    gl::clear();
}

void JsonTestApp::setup()
{

    JsonTree value( "key", "value" );
    console() << value << endl;

	JsonTree doc( loadResource( RES_JSON ) );
	JsonTree musicLibrary( doc.getChild( "library" ) );

	JsonTree owner = doc.getChild( "library.owner" );
	for( JsonTree::ConstIter item = owner.begin(); item != owner.end(); ++item ) {
		console() << "Node: " << item->getKey() << " Value: " << item->getValue<string>() << endl;
	}

	JsonTree tracks = doc.getChild( "library.albums[0].tracks" );
	for( JsonTree::ConstIter track = tracks.begin(); track != tracks.end(); ++track ) {
		console() << track->getChild( "id" ).getValue<int>() << endl;
	}

	for( JsonTree::ConstIter trackIt = tracks.begin(); trackIt != tracks.end(); ++trackIt ) {
		JsonTree track = * trackIt;
		console() << track["id"].getValue<int>() << endl;
	}

	JsonTree firstAlbum = doc.getChild( "library.albums[0]" );
	for( JsonTree::Iter child = firstAlbum.begin(); child != firstAlbum.end(); ++child ) {
		if ( !child->hasChildren() ) {
			console() << "Key: " << child->getKey() << "  Value: " << child->getValue<string>() << endl;
		}
	}

	console() << doc.getChild( "library.owner" );
	JsonTree &ownerCity = doc.getChild( "library.owner.city" );
	string s = ownerCity.getPath();
	console() << "Path: " << ownerCity.getPath() << "\n  Value: " << ownerCity.getValue<string>() << endl;
	console() << doc;

	JsonTree firstTrackCopy = doc.getChild( "library.albums[0].tracks[0].title" );
	firstTrackCopy = JsonTree( firstTrackCopy.getKey(), string( "Replacement name" ) );
	console() << doc.getChild( "library.albums[0].tracks[0]['title']" ) << endl;

	JsonTree &firstTrackRef = doc.getChild( "library.albums[0].tracks[2].title" );
    console() << firstTrackRef.getPath() << endl;
	firstTrackRef = JsonTree( firstTrackRef.getKey(), string( "Replacement name" ) );
	console() << doc.getChild( "library.albums[0].tracks[0].title" ) << endl;

	try {
		JsonTree invalid( "%%%%%%%%" );
	} catch ( JsonTree::ExcJsonParserError ex ) {
		console() << ex.what() << endl;
	}

	JsonTree test64u( "uint64", uint64_t( math<uint64_t>::pow( 2, 64 ) - 1 ) );
	console() << test64u << endl;
	JsonTree test64( "int64", uint64_t( math<int64_t>::pow( 2, 64 ) - 1 ) );
	console() << test64 << endl;

}

void JsonTestApp::mouseDown( MouseEvent event )
{

	JsonTree doc;
	JsonTree library = JsonTree::makeObject( "library" );
	JsonTree album = JsonTree::makeArray( "album" );

	album.pushBack( JsonTree( "musician", string( "Sufjan Stevens" ) ) );
	album.pushBack( JsonTree( "year", string( "2004" ) ) );
	album.pushBack( JsonTree( "title", string( "Seven Swans" ) ) );

	JsonTree tracks = JsonTree::makeArray( "tracks" );

	for ( int32_t i = 0; i < 6; i ++ ) {

		JsonTree track;
		track.pushBack( JsonTree( "id", i + 1 ) );

		JsonTree title;
		switch ( i ) {
		case 0:
            title = JsonTree( "title", "All the Trees of the Field Will Clap Their Hands" );
			break;
		case 1:
			title = JsonTree( "title", "The Dress Looks Nice on You" );
			break;
		case 2:
			title = JsonTree( "title", "In the Dev Hole's Territory" );
			break;
		case 3:
			title = JsonTree( "title", "To Be a Clone With You" );
			break;
		case 4:
			title = JsonTree( "title", "To Be Removed" );
			break;
		case 5:
			title = JsonTree( "title", "To Be Removed" );
			break;
		}

		track.pushBack( title );
		tracks.pushBack( track );

	}

	for ( JsonTree::Iter trackIt = tracks.begin(); trackIt != tracks.end(); ++trackIt ) {
		if ( trackIt->getChild( "id" ).getValue<int>() == 3 ) {
			JsonTree track;
			track.pushBack( JsonTree( "id", 3 ) );
			track.pushBack( JsonTree( "title", "In the Devil's Territory" ) );
			tracks.replaceChild( trackIt, track );
		}
	}

	JsonTree track;
	track.pushBack( JsonTree( "id", 4 ) );
	track.pushBack( JsonTree( "title", "To Be Alone With You" ) );
	tracks.replaceChild( 3, track );

	tracks.removeChild( 4 );

	for ( JsonTree::Iter trackIt = tracks.begin(); trackIt != tracks.end(); ) {
		if ( trackIt->getChild( "id" ).getValue<int>() == 6 ) {
			trackIt = tracks.removeChild( trackIt );
		} else {
			++trackIt;
		}
	}

	album.pushBack( tracks );
	library.pushBack( album );
	doc.pushBack( library );

	console() << doc;

	doc.write( writeFile( getDocumentsDirectory() + "testoutput.json" ), false );

}

CINDER_APP_BASIC( JsonTestApp, RendererGl )
<commit_msg>Merging 64-bit support for JSON<commit_after>#include "cinder/app/AppBasic.h"
#include "cinder/Json.h"
#include "Resources.h"

class JsonTestApp : public ci::app::AppBasic
{

  public:

      void draw();
	  void mouseDown( ci::app::MouseEvent event );
	  void setup();

};

using namespace ci;
using namespace ci::app;
using namespace std;

void JsonTestApp::draw()
{
    gl::clear();
}

void JsonTestApp::setup()
{

    JsonTree value( "key", "value" );
    console() << value << endl;

	JsonTree doc( loadResource( RES_JSON ) );
	JsonTree musicLibrary( doc.getChild( "library" ) );

	JsonTree owner = doc.getChild( "library.owner" );
	for( JsonTree::ConstIter item = owner.begin(); item != owner.end(); ++item ) {
		console() << "Node: " << item->getKey() << " Value: " << item->getValue<string>() << endl;
	}

	JsonTree tracks = doc.getChild( "library.albums[0].tracks" );
	for( JsonTree::ConstIter track = tracks.begin(); track != tracks.end(); ++track ) {
		console() << track->getChild( "id" ).getValue<int>() << endl;
	}

	for( JsonTree::ConstIter trackIt = tracks.begin(); trackIt != tracks.end(); ++trackIt ) {
		JsonTree track = * trackIt;
		console() << track["id"].getValue<int>() << endl;
	}

	JsonTree firstAlbum = doc.getChild( "library.albums[0]" );
	for( JsonTree::Iter child = firstAlbum.begin(); child != firstAlbum.end(); ++child ) {
		if ( !child->hasChildren() ) {
			console() << "Key: " << child->getKey() << "  Value: " << child->getValue<string>() << endl;
		}
	}

	console() << doc.getChild( "library.owner" );
	JsonTree &ownerCity = doc.getChild( "library.owner.city" );
	string s = ownerCity.getPath();
	console() << "Path: " << ownerCity.getPath() << "\n  Value: " << ownerCity.getValue<string>() << endl;
	console() << doc;

	JsonTree firstTrackCopy = doc.getChild( "library.albums[0].tracks[0].title" );
	firstTrackCopy = JsonTree( firstTrackCopy.getKey(), string( "Replacement name" ) );
	console() << doc.getChild( "library.albums[0].tracks[0]['title']" ) << endl;

	JsonTree &firstTrackRef = doc.getChild( "library.albums[0].tracks[2].title" );
    console() << firstTrackRef.getPath() << endl;
	firstTrackRef = JsonTree( firstTrackRef.getKey(), string( "Replacement name" ) );
	console() << doc.getChild( "library.albums[0].tracks[0].title" ) << endl;

	try {
		JsonTree invalid( "%%%%%%%%" );
	} catch ( JsonTree::ExcJsonParserError ex ) {
		console() << ex.what() << endl;
	}

	JsonTree test32u( "uint32", uint32_t( math<uint64_t>::pow( 2, 32 ) ) - 1 );
	console() << test32u;
	console() << test32u.getValue() << endl;
	JsonTree test32( "int32", int32_t( math<int32_t>::pow( 2, 32 ) ) - 1 );
	console() << test32;
	console() << test32.getValue() << endl;
	JsonTree test64u( "uint64", uint64_t( math<uint64_t>::pow( 2, 64 ) ) - 1 );
	console() << test64u;
	console() << test64u.getValue() << endl;
	JsonTree test64( "int64", int64_t( math<int64_t>::pow( 2, 64 ) ) - 1 );
	console() << test64;
	console() << test64.getValue() << endl;

}

void JsonTestApp::mouseDown( MouseEvent event )
{

	JsonTree doc;
	JsonTree library = JsonTree::makeObject( "library" );
	JsonTree album = JsonTree::makeArray( "album" );

	album.pushBack( JsonTree( "musician", string( "Sufjan Stevens" ) ) );
	album.pushBack( JsonTree( "year", string( "2004" ) ) );
	album.pushBack( JsonTree( "title", string( "Seven Swans" ) ) );

	JsonTree tracks = JsonTree::makeArray( "tracks" );

	for ( int32_t i = 0; i < 6; i ++ ) {

		JsonTree track;
		track.pushBack( JsonTree( "id", i + 1 ) );

		JsonTree title;
		switch ( i ) {
		case 0:
            title = JsonTree( "title", "All the Trees of the Field Will Clap Their Hands" );
			break;
		case 1:
			title = JsonTree( "title", "The Dress Looks Nice on You" );
			break;
		case 2:
			title = JsonTree( "title", "In the Dev Hole's Territory" );
			break;
		case 3:
			title = JsonTree( "title", "To Be a Clone With You" );
			break;
		case 4:
			title = JsonTree( "title", "To Be Removed" );
			break;
		case 5:
			title = JsonTree( "title", "To Be Removed" );
			break;
		}

		track.pushBack( title );
		tracks.pushBack( track );

	}

	for ( JsonTree::Iter trackIt = tracks.begin(); trackIt != tracks.end(); ++trackIt ) {
		if ( trackIt->getChild( "id" ).getValue<int>() == 3 ) {
			JsonTree track;
			track.pushBack( JsonTree( "id", 3 ) );
			track.pushBack( JsonTree( "title", "In the Devil's Territory" ) );
			tracks.replaceChild( trackIt, track );
		}
	}

	JsonTree track;
	track.pushBack( JsonTree( "id", 4 ) );
	track.pushBack( JsonTree( "title", "To Be Alone With You" ) );
	tracks.replaceChild( 3, track );

	tracks.removeChild( 4 );

	for ( JsonTree::Iter trackIt = tracks.begin(); trackIt != tracks.end(); ) {
		if ( trackIt->getChild( "id" ).getValue<int>() == 6 ) {
			trackIt = tracks.removeChild( trackIt );
		} else {
			++trackIt;
		}
	}

	album.pushBack( tracks );
	library.pushBack( album );
	doc.pushBack( library );

	console() << doc;

	doc.write( writeFile( getDocumentsDirectory() + "testoutput.json" ), false );

}

CINDER_APP_BASIC( JsonTestApp, RendererGl )
<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright (c) 2015, Jean-David Gadina - www.xs-labs.com
 * Distributed under the Boost Software License, Version 1.0.
 *
 * Boost Software License - Version 1.0 - August 17th, 2003
 *
 * Permission is hereby granted, free of charge, to any person or organization
 * obtaining a copy of the software and accompanying documentation covered by
 * this license (the "Software") to use, reproduce, display, distribute,
 * execute, and transmit the Software, and to prepare derivative works of the
 * Software, and to permit third-parties to whom the Software is furnished to
 * do so, all subject to the following:
 *
 * The copyright notices in the Software and this entire statement, including
 * the above license grant, this restriction and the following disclaimer,
 * must be included in all copies of the Software, in whole or in part, and
 * all derivative works of the Software, unless such copies or derivative
 * works are solely in the form of machine-executable object code generated by
 * a source language processor.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 ******************************************************************************/

/*!
 * @copyright   (c) 2015 - Jean-David Gadina - www.xs-labs.com
 * @brief       Test case XS::Atomic
 */

/* Disabled warnings for GoogleMock */
#ifdef __clang__
#pragma clang diagnostic ignored "-Wglobal-constructors"
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic push
#if __clang_major__ >= 7
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#pragma clang diagnostic ignored "-Wmissing-noreturn"
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma clang diagnostic ignored "-Wdeprecated"
#endif

#include <GoogleMock/GoogleMock.h>

#ifdef __clang__
#pragma clang diagnostic pop
#endif

#include <XS/Atomic.hpp>

using namespace testing;
<commit_msg>Unit tests<commit_after>/*******************************************************************************
 * Copyright (c) 2015, Jean-David Gadina - www.xs-labs.com
 * Distributed under the Boost Software License, Version 1.0.
 *
 * Boost Software License - Version 1.0 - August 17th, 2003
 *
 * Permission is hereby granted, free of charge, to any person or organization
 * obtaining a copy of the software and accompanying documentation covered by
 * this license (the "Software") to use, reproduce, display, distribute,
 * execute, and transmit the Software, and to prepare derivative works of the
 * Software, and to permit third-parties to whom the Software is furnished to
 * do so, all subject to the following:
 *
 * The copyright notices in the Software and this entire statement, including
 * the above license grant, this restriction and the following disclaimer,
 * must be included in all copies of the Software, in whole or in part, and
 * all derivative works of the Software, unless such copies or derivative
 * works are solely in the form of machine-executable object code generated by
 * a source language processor.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE, TITLE AND NON-INFRINGEMENT. IN NO EVENT
 * SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
 * FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
 * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 ******************************************************************************/

/*!
 * @copyright   (c) 2015 - Jean-David Gadina - www.xs-labs.com
 * @brief       Test case XS::Atomic
 */

/* Disabled warnings for GoogleMock */
#ifdef __clang__
#pragma clang diagnostic ignored "-Wglobal-constructors"
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic push
#if __clang_major__ >= 7
#pragma clang diagnostic ignored "-Wreserved-id-macro"
#endif
#pragma clang diagnostic ignored "-Wmissing-noreturn"
#pragma clang diagnostic ignored "-Wpadded"
#pragma clang diagnostic ignored "-Wused-but-marked-unused"
#pragma clang diagnostic ignored "-Wdeprecated"
#endif

#include <GoogleMock/GoogleMock.h>

#ifdef __clang__
#pragma clang diagnostic pop
#endif

#include <XS/Atomic.hpp>

using namespace testing;

TEST( XS_Atomic_Trivial_Pointer, CTOR )
{
    XS::Atomic< const char * > a;

    ASSERT_TRUE( a == nullptr );
}

TEST( XS_Atomic_Trivial_Pointer, CTOR_V )
{
    XS::Atomic< const char * > a{ "hello, world" };

    ASSERT_TRUE( strcmp( a, "hello, world" ) == 0 );
}

TEST( XS_Atomic_Trivial_Pointer, CCTOR )
{
    XS::Atomic< const char * > a1{ "hello, world" };
    XS::Atomic< const char * > a2{ a1 };

    ASSERT_TRUE( strcmp( a1, "hello, world" ) == 0 );
    ASSERT_TRUE( strcmp( a2, "hello, world" ) == 0 );
}

TEST( XS_Atomic_Trivial_Pointer, OperatorAssign )
{
    XS::Atomic< const char * > a1{ "hello, world" };
    XS::Atomic< const char * > a2;

    a2 = a1;

    ASSERT_TRUE( strcmp( a1, "hello, world" ) == 0 );
    ASSERT_TRUE( strcmp( a2, "hello, world" ) == 0 );
}

TEST( XS_Atomic_Trivial_Pointer, OperatorAssign_V )
{
    XS::Atomic< const char * > a;

    a = "hello, world";

    ASSERT_TRUE( strcmp( a, "hello, world" ) == 0 );
}

TEST( XS_Atomic_Trivial_Pointer, OperatorCast )
{
    XS::Atomic< const char * > a{ "hello, world" };

    ASSERT_TRUE( strcmp( static_cast< const char * >( a ), "hello, world" ) == 0 );
}

TEST( XS_Atomic_Trivial_Pointer, IsLockFree )
{
    XS::Atomic< const char * > a;

    ASSERT_TRUE( a.IsLockFree() );
}

TEST( XS_Atomic_Trivial_Pointer, Swap )
{
    XS::Atomic< const char * > a1{ "hello, world" };
    XS::Atomic< const char * > a2{ "hello, universe" };

    ASSERT_TRUE( strcmp( a1, "hello, world" ) == 0 );
    ASSERT_TRUE( strcmp( a2, "hello, universe" ) == 0 );

    swap( a1, a2 );

    ASSERT_TRUE( strcmp( a1, "hello, universe" ) == 0 );
    ASSERT_TRUE( strcmp( a2, "hello, world" ) == 0 );
}
<|endoftext|>


<commit_before>/**
 *   SFCGAL
 *
 *   Copyright (C) 2012-2013 Oslandia <contact@oslandia.com>
 *   Copyright (C) 2012-2013 IGN (http://www.ign.fr)
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   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, see <http://www.gnu.org/licenses/>.
 *
 */
#include <fstream>

#include <SFCGAL/all.h>
#include <SFCGAL/io/wkt.h>
#include <SFCGAL/generator/hoch.h>
#include <SFCGAL/generator/disc.h>
#include <SFCGAL/algorithm/triangulate.h>

#include "../test_config.h"
#include "Bench.h"

#include <boost/test/unit_test.hpp>
#include <boost/format.hpp>

#include <CGAL/point_generators_2.h>

using namespace boost::unit_test ;
using namespace SFCGAL ;

#define N_POINTS 100000

typedef CGAL::Creator_uniform_2< double, Kernel::Point_2 > Creator ;

BOOST_AUTO_TEST_SUITE( SFCGAL_BenchTriangulation )

BOOST_AUTO_TEST_CASE( testMultiPointTriangulation )
{
	CGAL::Random_points_in_disc_2< Kernel::Point_2, Creator > g( 150.0 );

	MultiPoint multiPoint ;
	for ( int i = 0; i < N_POINTS; i++ ){
		Kernel::Point_2 p = *(++g) ;
		multiPoint.addGeometry( new Point( p ) ) ;
	}

	bench().start( boost::format("triangulate %s points") % N_POINTS );
	TriangulatedSurface triangulatedSurface ;
	SFCGAL::algorithm::triangulate( multiPoint, triangulatedSurface ) ;
	bench().stop();
}

BOOST_AUTO_TEST_CASE( testPolygonTriangulationHoch )
{
	const int N = 7 ;
	std::auto_ptr< Polygon > fractal( generator::hoch(N) );
	BOOST_CHECK_EQUAL( fractal->exteriorRing().numPoints(), 49153U );

	bench().start( boost::format("triangulate hoch(%s)") % N );
	TriangulatedSurface triangulatedSurface ;
	SFCGAL::algorithm::triangulate( *fractal, triangulatedSurface ) ;
	bench().stop() ;
}

BOOST_AUTO_TEST_CASE( testPolygonTriangulationHoch_roundingSixDecimal )
{
	const int N = 7 ;
	std::auto_ptr< Polygon > fractal( generator::hoch(N) );
	BOOST_CHECK_EQUAL( fractal->exteriorRing().numPoints(), 49153U );

	fractal->round( 100000 ) ;

	bench().start( boost::format("triangulate hoch(%s) (round 6 six decimals)") % N );
	TriangulatedSurface triangulatedSurface ;
	SFCGAL::algorithm::triangulate( *fractal, triangulatedSurface ) ;
	bench().stop() ;
}

BOOST_AUTO_TEST_CASE( testPolygonTriangulationDisc )
{
	const int N = 20000 ;

	std::auto_ptr< Polygon > disc( generator::disc( Point(0.0,0.0), 1.0, 8U ) );
//	std::cout << fractal->asText(5) << std::endl ;

	bench().start( boost::format("triangulate disc x %s") % N );
	for ( int i = 0; i < N; i++ ){
		TriangulatedSurface triangulatedSurface ;
		SFCGAL::algorithm::triangulate( *disc, triangulatedSurface ) ;
	}
	bench().stop();
}

BOOST_AUTO_TEST_CASE( testMultiPointTriangulation2D )
{
	CGAL::Random_points_in_disc_2< Kernel::Point_2, Creator > g( 150.0 );

	MultiPoint multiPoint ;
	for ( int i = 0; i < N_POINTS; i++ ){
		Kernel::Point_2 p = *(++g) ;
		multiPoint.addGeometry( new Point( p ) ) ;
	}

	bench().start( boost::format("triangulate2D %s points") % N_POINTS );
	TriangulatedSurface triangulatedSurface ;
	SFCGAL::algorithm::triangulate2D( multiPoint, triangulatedSurface ) ;
	bench().stop();
}

BOOST_AUTO_TEST_CASE( testPolygonTriangulationHoch2D )
{
	const int N = 7 ;
	std::auto_ptr< Polygon > fractal( generator::hoch(N) );
//	std::cout << fractal->asText(5) << std::endl ;

	bench().start( boost::format("triangulate2D hoch(%s)") % N );
	TriangulatedSurface triangulatedSurface ;
	SFCGAL::algorithm::triangulate2D( *fractal, triangulatedSurface ) ;
	bench().stop();
}

BOOST_AUTO_TEST_CASE( testPolygonTriangulationDisc2D )
{
	const int N = 20000 ;

	std::auto_ptr< Polygon > disc( generator::disc( Point(0.0,0.0), 1.0, 8U ) ) ;
//	std::cout << fractal->asText(5) << std::endl ;

	bench().start( boost::format("triangulate2D disc x %s") % N ) ;
	for ( int i = 0; i < N; i++ ){
		TriangulatedSurface triangulatedSurface ;
		SFCGAL::algorithm::triangulate2D( *disc, triangulatedSurface ) ;
	}
	bench().stop() ;
}

BOOST_AUTO_TEST_CASE( testPolygonTriangulationDisc2D_roundingSixDecimal )
{
	const int N = 20000 ;

	std::auto_ptr< Polygon > disc( generator::disc( Point(0.0,0.0), 1.0, 8U ) ) ;
	disc->round( 100000 ) ;

	bench().start( boost::format("triangulate2D disc x %s (round 6 six decimals)") % N ) ;
	for ( int i = 0; i < N; i++ ){
		TriangulatedSurface triangulatedSurface ;
		SFCGAL::algorithm::triangulate2D( *disc, triangulatedSurface ) ;
	}
	bench().stop() ;
}

BOOST_AUTO_TEST_SUITE_END()

<commit_msg>Fix TriangulationBench<commit_after>/**
 *   SFCGAL
 *
 *   Copyright (C) 2012-2013 Oslandia <contact@oslandia.com>
 *   Copyright (C) 2012-2013 IGN (http://www.ign.fr)
 *
 *   This program is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   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, see <http://www.gnu.org/licenses/>.
 *
 */
#include <fstream>

#include <SFCGAL/all.h>
#include <SFCGAL/io/wkt.h>
#include <SFCGAL/generator/hoch.h>
#include <SFCGAL/generator/disc.h>
#include <SFCGAL/triangulate/triangulate2DZ.h>
#include <SFCGAL/triangulate/triangulatePolygon.h>

#include "../test_config.h"
#include "Bench.h"

#include <boost/test/unit_test.hpp>
#include <boost/format.hpp>

#include <CGAL/point_generators_2.h>

using namespace boost::unit_test ;
using namespace SFCGAL ;

#define N_POINTS 100000

typedef CGAL::Creator_uniform_2< double, Kernel::Point_2 > Creator ;

BOOST_AUTO_TEST_SUITE( SFCGAL_BenchTriangulation )

BOOST_AUTO_TEST_CASE( testMultiPointTriangulation )
{
	CGAL::Random_points_in_disc_2< Kernel::Point_2, Creator > g( 150.0 );

	MultiPoint multiPoint ;
	for ( int i = 0; i < N_POINTS; i++ ){
		Kernel::Point_2 p = *(++g) ;
		multiPoint.addGeometry( new Point( p ) ) ;
	}

	bench().start( boost::format("triangulate %s points") % N_POINTS );
	TriangulatedSurface triangulatedSurface ;
	SFCGAL::triangulate::triangulatePolygon3D( multiPoint, triangulatedSurface ) ;
	bench().stop();
}

BOOST_AUTO_TEST_CASE( testPolygonTriangulationHoch )
{
	const int N = 7 ;
	std::auto_ptr< Polygon > fractal( generator::hoch(N) );
	BOOST_CHECK_EQUAL( fractal->exteriorRing().numPoints(), 49153U );

	bench().start( boost::format("triangulate hoch(%s)") % N );
	TriangulatedSurface triangulatedSurface ;
	SFCGAL::triangulate::triangulatePolygon3D( *fractal, triangulatedSurface ) ;
	bench().stop() ;
}

BOOST_AUTO_TEST_CASE( testPolygonTriangulationHoch_roundingSixDecimal )
{
	const int N = 7 ;
	std::auto_ptr< Polygon > fractal( generator::hoch(N) );
	BOOST_CHECK_EQUAL( fractal->exteriorRing().numPoints(), 49153U );

	fractal->round( 100000 ) ;

	bench().start( boost::format("triangulate hoch(%s) (round 6 six decimals)") % N );
	TriangulatedSurface triangulatedSurface ;
	SFCGAL::triangulate::triangulatePolygon3D( *fractal, triangulatedSurface ) ;
	bench().stop() ;
}

BOOST_AUTO_TEST_CASE( testPolygonTriangulationDisc )
{
	const int N = 20000 ;

	std::auto_ptr< Polygon > disc( generator::disc( Point(0.0,0.0), 1.0, 8U ) );
//	std::cout << fractal->asText(5) << std::endl ;

	bench().start( boost::format("triangulate disc x %s") % N );
	for ( int i = 0; i < N; i++ ){
		TriangulatedSurface triangulatedSurface ;
		SFCGAL::triangulate::triangulatePolygon3D( *disc, triangulatedSurface ) ;
	}
	bench().stop();
}

BOOST_AUTO_TEST_CASE( testMultiPointTriangulation2D )
{
	CGAL::Random_points_in_disc_2< Kernel::Point_2, Creator > g( 150.0 );

	MultiPoint multiPoint ;
	for ( int i = 0; i < N_POINTS; i++ ){
		Kernel::Point_2 p = *(++g) ;
		multiPoint.addGeometry( new Point( p ) ) ;
	}

	bench().start( boost::format("triangulate2D %s points") % N_POINTS );
	SFCGAL::triangulate::ConstraintDelaunayTriangulation cdt;
	SFCGAL::triangulate::triangulate2DZ( multiPoint, cdt ) ;
	bench().stop();
}

BOOST_AUTO_TEST_CASE( testPolygonTriangulationHoch2D )
{
	const int N = 7 ;
	std::auto_ptr< Polygon > fractal( generator::hoch(N) );
//	std::cout << fractal->asText(5) << std::endl ;

	bench().start( boost::format("triangulate2D hoch(%s)") % N );
	SFCGAL::triangulate::ConstraintDelaunayTriangulation cdt;
	SFCGAL::triangulate::triangulate2DZ( *fractal, cdt ) ;
	bench().stop();
}

BOOST_AUTO_TEST_CASE( testPolygonTriangulationDisc2D )
{
	const int N = 20000 ;

	std::auto_ptr< Polygon > disc( generator::disc( Point(0.0,0.0), 1.0, 8U ) ) ;
//	std::cout << fractal->asText(5) << std::endl ;

	bench().start( boost::format("triangulate2D disc x %s") % N ) ;
	for ( int i = 0; i < N; i++ ){
		SFCGAL::triangulate::ConstraintDelaunayTriangulation cdt;
		SFCGAL::triangulate::triangulate2DZ( *disc, cdt ) ;
	}
	bench().stop() ;
}

BOOST_AUTO_TEST_CASE( testPolygonTriangulationDisc2D_roundingSixDecimal )
{
	const int N = 20000 ;

	std::auto_ptr< Polygon > disc( generator::disc( Point(0.0,0.0), 1.0, 8U ) ) ;
	disc->round( 100000 ) ;

	bench().start( boost::format("triangulate2D disc x %s (round 6 six decimals)") % N ) ;
	for ( int i = 0; i < N; i++ ){
		SFCGAL::triangulate::ConstraintDelaunayTriangulation cdt;
		SFCGAL::triangulate::triangulate2DZ( *disc, cdt ) ;
	}
	bench().stop() ;
}

BOOST_AUTO_TEST_SUITE_END()

<|endoftext|>