<commit_before>//
//  NuoMaterial.cpp
//  ModelViewer
//
//  Created by middleware on 8/28/16.
//  Copyright © 2016 middleware. All rights reserved.
//

#include "NuoMaterial.h"

NuoMaterial::NuoMaterial() : id(-1)
{
}

NuoMaterial::NuoMaterial(const tinyobj::material_t& material) :
    id(0),

    ambient_texname(material.ambient_texname),
    diffuse_texname(material.diffuse_texname),
    specular_texname(material.specular_texname),
    specular_highlight_texname(material.specular_highlight_texname),
    bump_texname(material.bump_texname),
    displacement_texname(material.displacement_texname),
    alpha_texname(material.alpha_texname),

    // PBR extension
    roughness_texname(material.roughness_texname),
    metallic_texname(material.metallic_texname),
    sheen_texname(material.sheen_texname),
    emissive_texname(material.emissive_texname),
    normal_texname(material.normal_texname)
{
}

bool NuoMaterial::operator < (const NuoMaterial& other) const
{
    if (id < other.id)
        return true;

    if (id > other.id)
        return false;

    return
        (ambient_texname < other.ambient_texname             &&
         diffuse_texname < other.diffuse_texname             &&
         specular_texname < other.specular_texname           &&
         specular_highlight_texname < other.specular_texname &&
         bump_texname < other.bump_texname                   &&
         displacement_texname < other.displacement_texname   &&
         alpha_texname < other.alpha_texname                 &&

         // PBR extension
         roughness_texname < other.roughness_texname         &&
         metallic_texname < other.metallic_texname           &&
         sheen_texname < other.sheen_texname                 &&
         emissive_texname < other.emissive_texname           &&
         normal_texname < other.normal_texname);
}
<commit_msg>Fix the comparer of materials.<commit_after>//
//  NuoMaterial.cpp
//  ModelViewer
//
//  Created by middleware on 8/28/16.
//  Copyright © 2016 middleware. All rights reserved.
//

#include "NuoMaterial.h"

NuoMaterial::NuoMaterial() : id(-1)
{
}

NuoMaterial::NuoMaterial(const tinyobj::material_t& material) :
    id(0),

    ambient_texname(material.ambient_texname),
    diffuse_texname(material.diffuse_texname),
    specular_texname(material.specular_texname),
    specular_highlight_texname(material.specular_highlight_texname),
    bump_texname(material.bump_texname),
    displacement_texname(material.displacement_texname),
    alpha_texname(material.alpha_texname),

    // PBR extension
    roughness_texname(material.roughness_texname),
    metallic_texname(material.metallic_texname),
    sheen_texname(material.sheen_texname),
    emissive_texname(material.emissive_texname),
    normal_texname(material.normal_texname)
{
}

bool NuoMaterial::operator < (const NuoMaterial& other) const
{
    if (id < other.id)
        return true;

    if (id > other.id)
        return false;

    return
        (ambient_texname < other.ambient_texname             ||
         diffuse_texname < other.diffuse_texname             ||
         specular_texname < other.specular_texname           ||
         specular_highlight_texname < other.specular_texname ||
         bump_texname < other.bump_texname                   ||
         displacement_texname < other.displacement_texname   ||
         alpha_texname < other.alpha_texname                 ||

         // PBR extension
         roughness_texname < other.roughness_texname         ||
         metallic_texname < other.metallic_texname           ||
         sheen_texname < other.sheen_texname                 ||
         emissive_texname < other.emissive_texname           ||
         normal_texname < other.normal_texname);
}
<|endoftext|>


<commit_before>///
/// @file   int128.cpp
/// @brief  Test int128_t and uint128_t types.
///
/// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <int128_t.hpp>

#include <stdint.h>
#include <cassert>
#include <iostream>
#include <type_traits>

using namespace std;
using namespace primecount;

#if defined(HAVE_INT128_T)

#include <cstdlib>
#include <sstream>
#include <string>

void check(bool OK)
{
  cout << "   " << (OK ? "OK" : "ERROR") << "\n";
  if (!OK)
    exit(1);
}

#endif

int main()
{
  static_assert(prt::numeric_limits<int8_t>::max() == std::numeric_limits<int8_t>::max(),
                "prt::numeric_limits<int8_t>::max() is broken");

  static_assert(prt::numeric_limits<uint64_t>::max() == std::numeric_limits<uint64_t>::max(),
                "prt::numeric_limits<uint64_t>::max() is broken");

  static_assert(prt::is_integral<uint64_t>::value,
                "prt::is_integral<uint64_t> != true");

  static_assert(!prt::is_integral<double>::value,
                "prt::is_integral<double> != false");

  static_assert(prt::is_signed<int64_t>::value,
                "prt::is_signed<int64_t> != true");

  static_assert(!prt::is_signed<uint64_t>::value,
                "prt::is_signed<uint64_t> != false");

  static_assert(!prt::is_unsigned<int64_t>::value,
                "prt::is_unsigned<int64_t> != false");

  static_assert(prt::is_unsigned<uint64_t>::value,
                "prt::is_unsigned<uint64_t> != true");

  static_assert(std::is_same<typename prt::make_signed<uint64_t>::type, int64_t>::value,
                "prt::make_signed<uint64_t> != int64_t");

#if defined(HAVE_INT128_T)

  static_assert(prt::numeric_limits<uint128_t>::max() == ~((uint128_t) 0),
                "prt::numeric_limits<uint128_t>::max() is broken");

  static_assert(prt::is_integral<int128_t>::value,
                "prt::is_integral<int128_t> != true");

  static_assert(prt::is_integral<uint128_t>::value,
                "prt::is_integral<uint128_t> != true");

  static_assert(prt::is_signed<int128_t>::value,
                "prt::is_signed<int128_t> != true");

  static_assert(!prt::is_signed<uint128_t>::value,
                "prt::is_signed<uint128_t> != false");

  static_assert(!prt::is_unsigned<int128_t>::value,
                "prt::is_unsigned<int128_t> != false");

  static_assert(prt::is_unsigned<uint128_t>::value,
                "prt::is_unsigned<uint128_t> != true");

  static_assert(std::is_same<typename prt::make_signed<int128_t>::type, int128_t>::value,
                "prt::make_signed<int128_t> != int128_t");

  static_assert(std::is_same<typename prt::make_signed<uint128_t>::type, int128_t>::value,
                "prt::make_signed<uint128_t> != int128_t");

  {
    ostringstream s;
    s << (((int128_t) 1 ) << 100);
    cout << "2^100 = " << s.str();
    check(s.str() == "1267650600228229401496703205376");
  }

  {
    ostringstream s;
    s << prt::numeric_limits<int128_t>::min();
    cout << "-2^127 = " << s.str();
    check(s.str() == "-170141183460469231731687303715884105728");
  }

  {
    ostringstream s;
    s << prt::numeric_limits<int128_t>::max();
    cout << "2^127-1 = " << s.str();
    check(s.str() == "170141183460469231731687303715884105727");
  }

  {
    ostringstream s;
    s << prt::numeric_limits<uint128_t>::max();
    cout << "2^128-1 = " << s.str();
    check(s.str() == "340282366920938463463374607431768211455");
  }

#endif

  cout << endl;
  cout << "All tests passed successfully!" << endl;

  return 0;
}
<commit_msg>Fix undefined behaviour<commit_after>///
/// @file   int128.cpp
/// @brief  Test int128_t and uint128_t types.
///
/// Copyright (C) 2018 Kim Walisch, <kim.walisch@gmail.com>
///
/// This file is distributed under the BSD License. See the COPYING
/// file in the top level directory.
///

#include <int128_t.hpp>

#include <stdint.h>
#include <cassert>
#include <iostream>
#include <type_traits>

using namespace std;
using namespace primecount;

#if defined(HAVE_INT128_T)

#include <cstdlib>
#include <sstream>
#include <string>

void check(bool OK)
{
  cout << "   " << (OK ? "OK" : "ERROR") << "\n";
  if (!OK)
    exit(1);
}

#endif

int main()
{
  static_assert(prt::numeric_limits<int8_t>::max() == std::numeric_limits<int8_t>::max(),
                "prt::numeric_limits<int8_t>::max() is broken");

  static_assert(prt::numeric_limits<uint64_t>::max() == std::numeric_limits<uint64_t>::max(),
                "prt::numeric_limits<uint64_t>::max() is broken");

  static_assert(prt::is_integral<uint64_t>::value,
                "prt::is_integral<uint64_t> != true");

  static_assert(!prt::is_integral<double>::value,
                "prt::is_integral<double> != false");

  static_assert(prt::is_signed<int64_t>::value,
                "prt::is_signed<int64_t> != true");

  static_assert(!prt::is_signed<uint64_t>::value,
                "prt::is_signed<uint64_t> != false");

  static_assert(!prt::is_unsigned<int64_t>::value,
                "prt::is_unsigned<int64_t> != false");

  static_assert(prt::is_unsigned<uint64_t>::value,
                "prt::is_unsigned<uint64_t> != true");

  static_assert(std::is_same<typename prt::make_signed<uint64_t>::type, int64_t>::value,
                "prt::make_signed<uint64_t> != int64_t");

#if defined(HAVE_INT128_T)

  static_assert(prt::numeric_limits<uint128_t>::max() == ~((uint128_t) 0),
                "prt::numeric_limits<uint128_t>::max() is broken");

  static_assert(prt::is_integral<int128_t>::value,
                "prt::is_integral<int128_t> != true");

  static_assert(prt::is_integral<uint128_t>::value,
                "prt::is_integral<uint128_t> != true");

  static_assert(prt::is_signed<int128_t>::value,
                "prt::is_signed<int128_t> != true");

  static_assert(!prt::is_signed<uint128_t>::value,
                "prt::is_signed<uint128_t> != false");

  static_assert(!prt::is_unsigned<int128_t>::value,
                "prt::is_unsigned<int128_t> != false");

  static_assert(prt::is_unsigned<uint128_t>::value,
                "prt::is_unsigned<uint128_t> != true");

  static_assert(std::is_same<typename prt::make_signed<int128_t>::type, int128_t>::value,
                "prt::make_signed<int128_t> != int128_t");

  static_assert(std::is_same<typename prt::make_signed<uint128_t>::type, int128_t>::value,
                "prt::make_signed<uint128_t> != int128_t");

  {
    ostringstream s;
    s << (((int128_t) 1 ) << 100);
    cout << "2^100 = " << s.str();
    check(s.str() == "1267650600228229401496703205376");
  }

  {
    ostringstream s;
    s << prt::numeric_limits<int128_t>::min() + 1;
    cout << "-2^127+1 = " << s.str();
    check(s.str() == "-170141183460469231731687303715884105727");
  }

  {
    ostringstream s;
    s << prt::numeric_limits<int128_t>::max();
    cout << "2^127-1 = " << s.str();
    check(s.str() == "170141183460469231731687303715884105727");
  }

  {
    ostringstream s;
    s << prt::numeric_limits<uint128_t>::max();
    cout << "2^128-1 = " << s.str();
    check(s.str() == "340282366920938463463374607431768211455");
  }

#endif

  cout << endl;
  cout << "All tests passed successfully!" << endl;

  return 0;
}
<|endoftext|>


<commit_before>#include "catch.hpp"

#include "etl/fast_matrix.hpp"

//{{{ Init tests

TEST_CASE( "fast_matrix/init_1", "fast_matrix::fast_matrix(T)" ) {
    etl::fast_matrix<double, 2, 2> test_matrix(3.3);

    REQUIRE(test_matrix.size() == 4);

    for(std::size_t i = 0; i < test_matrix.size(); ++i){
        REQUIRE(test_matrix[i] == 3.3);
    }
}

TEST_CASE( "fast_matrix/init_2", "fast_matrix::operator=(T)" ) {
    etl::fast_matrix<double, 2, 2> test_matrix;

    test_matrix = 3.3;

    REQUIRE(test_matrix.size() == 4);

    for(std::size_t i = 0; i < test_matrix.size(); ++i){
        REQUIRE(test_matrix[i] == 3.3);
    }
}

TEST_CASE( "fast_matrix/init_3", "fast_matrix::fast_matrix(initializer_list)" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {1.0, 3.0, 5.0, 2.0};

    REQUIRE(test_matrix.size() == 4);

    REQUIRE(test_matrix[0] == 1.0);
    REQUIRE(test_matrix[1] == 3.0);
    REQUIRE(test_matrix[2] == 5.0);
}

//}}} Init tests

//{{{ Binary operators test

TEST_CASE( "fast_matrix/add_scalar_1", "fast_matrix::operator+" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0};

    test_matrix = 1.0 + test_matrix;

    REQUIRE(test_matrix[0] == 0.0);
    REQUIRE(test_matrix[1] == 3.0);
    REQUIRE(test_matrix[2] == 6.5);
}

TEST_CASE( "fast_matrix/add_scalar_2", "fast_matrix::operator+" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0};

    test_matrix = test_matrix + 1.0;

    REQUIRE(test_matrix[0] == 0.0);
    REQUIRE(test_matrix[1] == 3.0);
    REQUIRE(test_matrix[2] == 6.5);
}

TEST_CASE( "fast_matrix/add", "fast_matrix::operator+" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};
    etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0};

    etl::fast_matrix<double, 2, 2> c = a + b;

    REQUIRE(c[0] ==  1.5);
    REQUIRE(c[1] ==  5.0);
    REQUIRE(c[2] ==  9.0);
}

TEST_CASE( "fast_matrix/sub_scalar_1", "fast_matrix::operator+" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0};

    test_matrix = 1.0 - test_matrix;

    REQUIRE(test_matrix[0] == 2.0);
    REQUIRE(test_matrix[1] == -1.0);
    REQUIRE(test_matrix[2] == -4.5);
}

TEST_CASE( "fast_matrix/sub_scalar_2", "fast_matrix::operator+" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0};

    test_matrix = test_matrix - 1.0;

    REQUIRE(test_matrix[0] == -2.0);
    REQUIRE(test_matrix[1] == 1.0);
    REQUIRE(test_matrix[2] == 4.5);
}

TEST_CASE( "fast_matrix/sub", "fast_matrix::operator-" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};
    etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0};

    etl::fast_matrix<double, 2, 2> c = a - b;

    REQUIRE(c[0] == -3.5);
    REQUIRE(c[1] == -1.0);
    REQUIRE(c[2] ==  1.0);
}

TEST_CASE( "fast_matrix/mul_scalar_1", "fast_matrix::operator*" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0};

    test_matrix = 2.5 * test_matrix;

    REQUIRE(test_matrix[0] == -2.5);
    REQUIRE(test_matrix[1] ==  5.0);
    REQUIRE(test_matrix[2] == 12.5);
}

TEST_CASE( "fast_matrix/mul_scalar_2", "fast_matrix::operator*" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0};

    test_matrix = test_matrix * 2.5;

    REQUIRE(test_matrix[0] == -2.5);
    REQUIRE(test_matrix[1] ==  5.0);
    REQUIRE(test_matrix[2] == 12.5);
}

TEST_CASE( "fast_matrix/mul", "fast_matrix::operator*" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};
    etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0};

    etl::fast_matrix<double, 2, 2> c = a * b;

    REQUIRE(c[0] == -2.5);
    REQUIRE(c[1] ==  6.0);
    REQUIRE(c[2] == 20.0);
}

TEST_CASE( "fast_matrix/div_scalar_1", "fast_matrix::operator/" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0};

    test_matrix = test_matrix / 2.5;

    REQUIRE(test_matrix[0] == -1.0 / 2.5);
    REQUIRE(test_matrix[1] ==  2.0 / 2.5);
    REQUIRE(test_matrix[2] ==  5.0 / 2.5);
}

TEST_CASE( "fast_matrix/div_scalar_2", "fast_matrix::operator/" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0};

    test_matrix = 2.5 / test_matrix;

    REQUIRE(test_matrix[0] == 2.5 / -1.0);
    REQUIRE(test_matrix[1] == 2.5 /  2.0);
    REQUIRE(test_matrix[2] == 2.5 /  5.0);
}

TEST_CASE( "fast_matrix/div", "fast_matrix::operator/" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};
    etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0};

    etl::fast_matrix<double, 2, 2> c = a / b;

    REQUIRE(c[0] == -1.0 / 2.5);
    REQUIRE(c[1] == 2.0 / 3.0);
    REQUIRE(c[2] == 5.0 / 4.0);
}

TEST_CASE( "fast_matrix/mod_scalar_1", "fast_matrix::operator%" ) {
    etl::fast_matrix<int, 2, 2> test_matrix = {-1, 2, 5, 1};

    test_matrix = test_matrix % 2;

    REQUIRE(test_matrix[0] == -1 % 2);
    REQUIRE(test_matrix[1] ==  2 % 2);
    REQUIRE(test_matrix[2] ==  5 % 2);
}

TEST_CASE( "fast_matrix/mod_scalar_2", "fast_matrix::operator%" ) {
    etl::fast_matrix<int, 2, 2> test_matrix = {-1, 2, 5, 1};

    test_matrix = 2 % test_matrix;

    REQUIRE(test_matrix[0] == 2 % -1);
    REQUIRE(test_matrix[1] == 2 %  2);
    REQUIRE(test_matrix[2] == 2 %  5);
}

TEST_CASE( "fast_matrix/mod", "fast_matrix::operator*" ) {
    etl::fast_matrix<int, 2, 2> a = {-1, 2, 5, 1};
    etl::fast_matrix<int, 2, 2> b = {2, 3, 4, 1};

    etl::fast_matrix<int, 2, 2> c = a % b;

    REQUIRE(c[0] == -1 % 2);
    REQUIRE(c[1] == 2 % 3);
    REQUIRE(c[2] == 5 % 4);
}

//}}} Binary operator tests

//{{{ Unary operator tests

TEST_CASE( "fast_matrix/log", "fast_matrix::abs" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};

    etl::fast_matrix<double, 2, 2> d = log(a);

    REQUIRE(d[0] == log(-1.0));
    REQUIRE(d[1] == log(2.0));
    REQUIRE(d[2] == log(5.0));
}

TEST_CASE( "fast_matrix/abs", "fast_matrix::abs" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0};

    etl::fast_matrix<double, 2, 2> d = abs(a);

    REQUIRE(d[0] == 1.0);
    REQUIRE(d[1] == 2.0);
    REQUIRE(d[2] == 0.0);
}

TEST_CASE( "fast_matrix/sign", "fast_matrix::abs" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0};

    etl::fast_matrix<double, 2, 2> d = sign(a);

    REQUIRE(d[0] == -1.0);
    REQUIRE(d[1] == 1.0);
    REQUIRE(d[2] == 0.0);
}

TEST_CASE( "fast_matrix/unary_unary", "fast_matrix::abs" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0};

    etl::fast_matrix<double, 2, 2> d = abs(sign(a));

    REQUIRE(d[0] == 1.0);
    REQUIRE(d[1] == 1.0);
    REQUIRE(d[2] == 0.0);
}

TEST_CASE( "fast_matrix/unary_binary_1", "fast_matrix::abs" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0};

    etl::fast_matrix<double, 2, 2> d = abs(a + a);

    REQUIRE(d[0] == 2.0);
    REQUIRE(d[1] == 4.0);
    REQUIRE(d[2] == 0.0);
}

TEST_CASE( "fast_matrix/unary_binary_2", "fast_matrix::abs" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0};

    etl::fast_matrix<double, 2, 2> d = abs(a) + a;

    REQUIRE(d[0] == 0.0);
    REQUIRE(d[1] == 4.0);
    REQUIRE(d[2] == 0.0);
}

//}}} Unary operators test

//{{{ Complex tests

TEST_CASE( "fast_matrix/complex", "fast_matrix::complex" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};
    etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0};
    etl::fast_matrix<double, 2, 2> c = {1.2, -3.0, 3.5, 1.0};

    etl::fast_matrix<double, 2, 2> d = 2.5 * ((a * b) / (a + c)) / (1.5 * a * b / c);

    REQUIRE(d[0] == Approx(10.0));
    REQUIRE(d[1] == Approx(5.0));
    REQUIRE(d[2] == Approx(0.68627));
}

TEST_CASE( "fast_matrix/complex_2", "fast_matrix::complex" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};
    etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0};
    etl::fast_matrix<double, 2, 2> c = {1.2, -3.0, 3.5, 1.0};

    etl::fast_matrix<double, 2, 2> d = 2.5 * ((a * b) / (log(a) * abs(c))) / (1.5 * a * sign(b) / c) + 2.111 / log(c);

    REQUIRE(d[0] == Approx(10.0));
    REQUIRE(d[1] == Approx(5.0));
    REQUIRE(d[2] == Approx(5.8273));
}

TEST_CASE( "fast_matrix/complex_3", "fast_matrix::complex" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};
    etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0};
    etl::fast_matrix<double, 2, 2> c = {1.2, -3.0, 3.5, 1.0};

    etl::fast_matrix<double, 2, 2> d = 2.5 / (a * b);

    REQUIRE(d[0] == Approx(-1.0));
    REQUIRE(d[1] == Approx(0.416666));
    REQUIRE(d[2] == Approx(0.125));
}

//}}} Complex tests<commit_msg>Fix test<commit_after>#include "catch.hpp"

#include "etl/fast_matrix.hpp"

//{{{ Init tests

TEST_CASE( "fast_matrix/init_1", "fast_matrix::fast_matrix(T)" ) {
    etl::fast_matrix<double, 2, 2> test_matrix(3.3);

    REQUIRE(test_matrix.size() == 4);

    for(std::size_t i = 0; i < test_matrix.size(); ++i){
        REQUIRE(test_matrix[i] == 3.3);
    }
}

TEST_CASE( "fast_matrix/init_2", "fast_matrix::operator=(T)" ) {
    etl::fast_matrix<double, 2, 2> test_matrix;

    test_matrix = 3.3;

    REQUIRE(test_matrix.size() == 4);

    for(std::size_t i = 0; i < test_matrix.size(); ++i){
        REQUIRE(test_matrix[i] == 3.3);
    }
}

TEST_CASE( "fast_matrix/init_3", "fast_matrix::fast_matrix(initializer_list)" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {1.0, 3.0, 5.0, 2.0};

    REQUIRE(test_matrix.size() == 4);

    REQUIRE(test_matrix[0] == 1.0);
    REQUIRE(test_matrix[1] == 3.0);
    REQUIRE(test_matrix[2] == 5.0);
}

//}}} Init tests

//{{{ Binary operators test

TEST_CASE( "fast_matrix/add_scalar_1", "fast_matrix::operator+" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0};

    test_matrix = 1.0 + test_matrix;

    REQUIRE(test_matrix[0] == 0.0);
    REQUIRE(test_matrix[1] == 3.0);
    REQUIRE(test_matrix[2] == 6.5);
}

TEST_CASE( "fast_matrix/add_scalar_2", "fast_matrix::operator+" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0};

    test_matrix = test_matrix + 1.0;

    REQUIRE(test_matrix[0] == 0.0);
    REQUIRE(test_matrix[1] == 3.0);
    REQUIRE(test_matrix[2] == 6.5);
}

TEST_CASE( "fast_matrix/add", "fast_matrix::operator+" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};
    etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0};

    etl::fast_matrix<double, 2, 2> c = a + b;

    REQUIRE(c[0] ==  1.5);
    REQUIRE(c[1] ==  5.0);
    REQUIRE(c[2] ==  9.0);
}

TEST_CASE( "fast_matrix/sub_scalar_1", "fast_matrix::operator+" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0};

    test_matrix = 1.0 - test_matrix;

    REQUIRE(test_matrix[0] == 2.0);
    REQUIRE(test_matrix[1] == -1.0);
    REQUIRE(test_matrix[2] == -4.5);
}

TEST_CASE( "fast_matrix/sub_scalar_2", "fast_matrix::operator+" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.5, 1.0};

    test_matrix = test_matrix - 1.0;

    REQUIRE(test_matrix[0] == -2.0);
    REQUIRE(test_matrix[1] == 1.0);
    REQUIRE(test_matrix[2] == 4.5);
}

TEST_CASE( "fast_matrix/sub", "fast_matrix::operator-" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};
    etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0};

    etl::fast_matrix<double, 2, 2> c = a - b;

    REQUIRE(c[0] == -3.5);
    REQUIRE(c[1] == -1.0);
    REQUIRE(c[2] ==  1.0);
}

TEST_CASE( "fast_matrix/mul_scalar_1", "fast_matrix::operator*" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0};

    test_matrix = 2.5 * test_matrix;

    REQUIRE(test_matrix[0] == -2.5);
    REQUIRE(test_matrix[1] ==  5.0);
    REQUIRE(test_matrix[2] == 12.5);
}

TEST_CASE( "fast_matrix/mul_scalar_2", "fast_matrix::operator*" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0};

    test_matrix = test_matrix * 2.5;

    REQUIRE(test_matrix[0] == -2.5);
    REQUIRE(test_matrix[1] ==  5.0);
    REQUIRE(test_matrix[2] == 12.5);
}

TEST_CASE( "fast_matrix/mul", "fast_matrix::operator*" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};
    etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0};

    etl::fast_matrix<double, 2, 2> c = a * b;

    REQUIRE(c[0] == -2.5);
    REQUIRE(c[1] ==  6.0);
    REQUIRE(c[2] == 20.0);
}

TEST_CASE( "fast_matrix/div_scalar_1", "fast_matrix::operator/" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0};

    test_matrix = test_matrix / 2.5;

    REQUIRE(test_matrix[0] == -1.0 / 2.5);
    REQUIRE(test_matrix[1] ==  2.0 / 2.5);
    REQUIRE(test_matrix[2] ==  5.0 / 2.5);
}

TEST_CASE( "fast_matrix/div_scalar_2", "fast_matrix::operator/" ) {
    etl::fast_matrix<double, 2, 2> test_matrix = {-1.0, 2.0, 5.0, 1.0};

    test_matrix = 2.5 / test_matrix;

    REQUIRE(test_matrix[0] == 2.5 / -1.0);
    REQUIRE(test_matrix[1] == 2.5 /  2.0);
    REQUIRE(test_matrix[2] == 2.5 /  5.0);
}

TEST_CASE( "fast_matrix/div", "fast_matrix::operator/" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};
    etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0};

    etl::fast_matrix<double, 2, 2> c = a / b;

    REQUIRE(c[0] == -1.0 / 2.5);
    REQUIRE(c[1] == 2.0 / 3.0);
    REQUIRE(c[2] == 5.0 / 4.0);
}

TEST_CASE( "fast_matrix/mod_scalar_1", "fast_matrix::operator%" ) {
    etl::fast_matrix<int, 2, 2> test_matrix = {-1, 2, 5, 1};

    test_matrix = test_matrix % 2;

    REQUIRE(test_matrix[0] == -1 % 2);
    REQUIRE(test_matrix[1] ==  2 % 2);
    REQUIRE(test_matrix[2] ==  5 % 2);
}

TEST_CASE( "fast_matrix/mod_scalar_2", "fast_matrix::operator%" ) {
    etl::fast_matrix<int, 2, 2> test_matrix = {-1, 2, 5, 1};

    test_matrix = 2 % test_matrix;

    REQUIRE(test_matrix[0] == 2 % -1);
    REQUIRE(test_matrix[1] == 2 %  2);
    REQUIRE(test_matrix[2] == 2 %  5);
}

TEST_CASE( "fast_matrix/mod", "fast_matrix::operator*" ) {
    etl::fast_matrix<int, 2, 2> a = {-1, 2, 5, 1};
    etl::fast_matrix<int, 2, 2> b = {2, 3, 4, 1};

    etl::fast_matrix<int, 2, 2> c = a % b;

    REQUIRE(c[0] == -1 % 2);
    REQUIRE(c[1] == 2 % 3);
    REQUIRE(c[2] == 5 % 4);
}

//}}} Binary operator tests

//{{{ Unary operator tests

TEST_CASE( "fast_matrix/log", "fast_matrix::abs" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};

    etl::fast_matrix<double, 2, 2> d = log(a);

    REQUIRE(d[0] == log(-1.0));
    REQUIRE(d[1] == log(2.0));
    REQUIRE(d[2] == log(5.0));
}

TEST_CASE( "fast_matrix/abs", "fast_matrix::abs" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0};

    etl::fast_matrix<double, 2, 2> d = abs(a);

    REQUIRE(d[0] == 1.0);
    REQUIRE(d[1] == 2.0);
    REQUIRE(d[2] == 0.0);
}

TEST_CASE( "fast_matrix/sign", "fast_matrix::abs" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0};

    etl::fast_matrix<double, 2, 2> d = sign(a);

    REQUIRE(d[0] == -1.0);
    REQUIRE(d[1] == 1.0);
    REQUIRE(d[2] == 0.0);
}

TEST_CASE( "fast_matrix/unary_unary", "fast_matrix::abs" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 3.0};

    etl::fast_matrix<double, 2, 2> d = abs(sign(a));

    REQUIRE(d[0] == 1.0);
    REQUIRE(d[1] == 1.0);
    REQUIRE(d[2] == 0.0);
}

TEST_CASE( "fast_matrix/unary_binary_1", "fast_matrix::abs" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0};

    etl::fast_matrix<double, 2, 2> d = abs(a + a);

    REQUIRE(d[0] == 2.0);
    REQUIRE(d[1] == 4.0);
    REQUIRE(d[2] == 0.0);
}

TEST_CASE( "fast_matrix/unary_binary_2", "fast_matrix::abs" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 0.0, 1.0};

    etl::fast_matrix<double, 2, 2> d = abs(a) + a;

    REQUIRE(d[0] == 0.0);
    REQUIRE(d[1] == 4.0);
    REQUIRE(d[2] == 0.0);
}

//}}} Unary operators test

//{{{ Complex tests

TEST_CASE( "fast_matrix/complex", "fast_matrix::complex" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};
    etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0};
    etl::fast_matrix<double, 2, 2> c = {1.2, -3.0, 3.5, 1.0};

    etl::fast_matrix<double, 2, 2> d = 2.5 * ((a * b) / (a + c)) / (1.5 * a * b / c);

    REQUIRE(d[0] == Approx(10.0));
    REQUIRE(d[1] == Approx(5.0));
    REQUIRE(d[2] == Approx(0.68627));
}

TEST_CASE( "fast_matrix/complex_2", "fast_matrix::complex" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};
    etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0};
    etl::fast_matrix<double, 2, 2> c = {1.2, -3.0, 3.5, 1.0};

    etl::fast_matrix<double, 2, 2> d = 2.5 * ((a * b) / (log(a) * abs(c))) / (1.5 * a * sign(b) / c) + 2.111 / log(c);

    REQUIRE(d[0] == Approx(10.0));
    REQUIRE(d[1] == Approx(5.0));
    REQUIRE(d[2] == Approx(5.8273));
}

TEST_CASE( "fast_matrix/complex_3", "fast_matrix::complex" ) {
    etl::fast_matrix<double, 2, 2> a = {-1.0, 2.0, 5.0, 1.0};
    etl::fast_matrix<double, 2, 2> b = {2.5, 3.0, 4.0, 1.0};
    etl::fast_matrix<double, 2, 2> c = {1.2, -3.0, 3.5, 1.0};

    etl::fast_matrix<double, 2, 2> d = 2.5 / (a * b);

    REQUIRE(d[0] == Approx(-1.0));
    REQUIRE(d[1] == Approx(0.416666));
    REQUIRE(d[2] == Approx(0.125));
}

//}}} Complex tests<|endoftext|>


<commit_before>#include "../include/process.h"
#include "../include/sandbox.h"

#include <gtest/gtest.h>
#include <sys/syscall.h>

TEST (Sandbox, run) {
	Sandbox sandbox;

	constexpr size_t MEM_LIMIT = 16 << 20; // 16 MB (in bytes)
	constexpr timespec REAL_TIME_LIMIT = {0, (int)0.5e9}; // 0.5 s
	constexpr timespec CPU_TIME_LIMIT = {0, (int)0.2e9}; // 0.2 s

	Sandbox::Options opts {
		-1,
		-1,
		-1,
		REAL_TIME_LIMIT,
		MEM_LIMIT,
		CPU_TIME_LIMIT
	};

	// Compiled test case executable
	InplaceBuff<40> exec("/tmp/simlib.test.sandbox.XXXXXX");
	{
		int fd = mkstemp(exec.data());
		if (fd == -1)
			THROW("mkstemp()", errmsg());

		sclose(fd);
	}
	FileRemover exec_remover(exec.to_cstr());

	const auto test_cases_dir =
		concat(getExecDir(getpid()), "sandbox_test_cases/");

	auto compile_test_case = [&] (StringView case_filename) {
		Spawner::ExitStat es = Spawner::run("cc", {
			"cc",
			concat_tostr(test_cases_dir, case_filename),
			"-o",
			exec.to_string(),
			"-static",
		}, {-1, STDOUT_FILENO, STDERR_FILENO});

		// Compilation must be successful
		throw_assert(es.si.code == CLD_EXITED and es.si.status == 0);
	};

	Sandbox::ExitStat es;

	compile_test_case("1.c");
	es = sandbox.run(exec.to_cstr(), {}, opts);
	EXPECT_EQ(es.si.code, CLD_KILLED);
	EXPECT_EQ(es.si.status, SIGKILL);
	EXPECT_EQ(es.message, "Memory limit exceeded");
	EXPECT_LT((timespec{0, 0}), es.cpu_runtime);
	EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT);
	EXPECT_LT((timespec{0, 0}), es.runtime);
	EXPECT_LT(es.runtime, REAL_TIME_LIMIT);
	EXPECT_LT(0, es.vm_peak);
	EXPECT_LT(es.vm_peak, MEM_LIMIT);

	compile_test_case("2.c");
	es = sandbox.run(exec.to_cstr(), {}, opts);
	EXPECT_EQ(es.si.code, CLD_KILLED);
	EXPECT_EQ(es.si.status, SIGSEGV);
	EXPECT_EQ(es.message, "killed by signal 11 - Segmentation fault");
	EXPECT_EQ(es.cpu_runtime, (timespec{0, 0}));
	EXPECT_EQ(es.runtime, (timespec{0, 0}));
	EXPECT_EQ(es.vm_peak, 0);

	compile_test_case("3.c");
	es = sandbox.run(exec.to_cstr(), {}, opts);
	EXPECT_EQ(es.si.code, CLD_EXITED);
	EXPECT_EQ(es.si.status, 37);
	EXPECT_EQ(es.message, "exited with 37");
	EXPECT_LT((timespec{0, 0}), es.cpu_runtime);
	EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT);
	EXPECT_LT((timespec{0, 0}), es.runtime);
	EXPECT_LT(es.runtime, REAL_TIME_LIMIT);
	EXPECT_LT(0, es.vm_peak);
	EXPECT_LT(es.vm_peak, MEM_LIMIT);

	compile_test_case("4.c");
	es = sandbox.run(exec.to_cstr(), {}, opts);
	EXPECT_EQ(es.si.code, CLD_KILLED);
	EXPECT_EQ(es.si.status, SIGKILL);
	EXPECT_EQ(es.message, concat_tostr("forbidden syscall: ", SYS_socket, " - socket"));
	EXPECT_LT((timespec{0, 0}), es.cpu_runtime);
	EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT);
	EXPECT_LT((timespec{0, 0}), es.runtime);
	EXPECT_LT(es.runtime, REAL_TIME_LIMIT);
	EXPECT_LT(0, es.vm_peak);
	EXPECT_LT(es.vm_peak, MEM_LIMIT);

	compile_test_case("5.c");
	es = sandbox.run(exec.to_cstr(), {}, opts);
	EXPECT_EQ(es.si.code, CLD_DUMPED);
	EXPECT_EQ(es.si.status, SIGABRT);
	EXPECT_EQ(es.message, "killed and dumped by signal 6 - Aborted");
	EXPECT_LT((timespec{0, 0}), es.cpu_runtime);
	EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT);
	EXPECT_LT((timespec{0, 0}), es.runtime);
	EXPECT_LT(es.runtime, REAL_TIME_LIMIT);
	EXPECT_LT(0, es.vm_peak);
	EXPECT_LT(es.vm_peak, MEM_LIMIT);

	compile_test_case("6.c");
	es = sandbox.run(exec.to_cstr(), {}, opts);
	EXPECT_EQ(es.si.code, CLD_DUMPED);
	EXPECT_EQ(es.si.status, SIGABRT);
	EXPECT_EQ(es.message, "killed and dumped by signal 6 - Aborted");
	EXPECT_LT((timespec{0, 0}), es.cpu_runtime);
	EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT);
	EXPECT_LT((timespec{0, 0}), es.runtime);
	EXPECT_LT(es.runtime, REAL_TIME_LIMIT);
	EXPECT_LT(0, es.vm_peak);
	EXPECT_LT(es.vm_peak, MEM_LIMIT);

	// compile_test_case("6.c"); // not needed
	es = sandbox.run(exec.to_cstr(), {}, opts, {{"/tmp", OpenAccess::RDONLY}});
	EXPECT_EQ(es.si.code, CLD_EXITED);
	EXPECT_EQ(es.si.status, 0);
	EXPECT_EQ(es.message, "");
	EXPECT_LT((timespec{0, 0}), es.cpu_runtime);
	EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT);
	EXPECT_LT((timespec{0, 0}), es.runtime);
	EXPECT_LT(es.runtime, REAL_TIME_LIMIT);
	EXPECT_LT(0, es.vm_peak);
	EXPECT_LT(es.vm_peak, MEM_LIMIT);

	for (auto perm : {OpenAccess::NONE, OpenAccess::WRONLY, OpenAccess::RDWR}) {
		// compile_test_case("6.c"); // not needed
		es = sandbox.run(exec.to_cstr(), {}, opts, {{"/tmp", perm}});
		EXPECT_EQ(es.si.code, CLD_DUMPED);
		EXPECT_EQ(es.si.status, SIGABRT);
		EXPECT_EQ(es.message, "killed and dumped by signal 6 - Aborted");
		EXPECT_LT((timespec{0, 0}), es.cpu_runtime);
		EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT);
		EXPECT_LT((timespec{0, 0}), es.runtime);
		EXPECT_LT(es.runtime, REAL_TIME_LIMIT);
		EXPECT_LT(0, es.vm_peak);
		EXPECT_LT(es.vm_peak, MEM_LIMIT);
	}
}
<commit_msg>Updated the sandbox unit tests, so that they allow killing or dumping by SIGABRT<commit_after>#include "../include/process.h"
#include "../include/sandbox.h"

#include <gtest/gtest.h>
#include <sys/syscall.h>

TEST (Sandbox, run) {
	Sandbox sandbox;

	constexpr size_t MEM_LIMIT = 16 << 20; // 16 MB (in bytes)
	constexpr timespec REAL_TIME_LIMIT = {0, (int)0.5e9}; // 0.5 s
	constexpr timespec CPU_TIME_LIMIT = {0, (int)0.2e9}; // 0.2 s

	Sandbox::Options opts {
		-1,
		-1,
		-1,
		REAL_TIME_LIMIT,
		MEM_LIMIT,
		CPU_TIME_LIMIT
	};

	// Compiled test case executable
	InplaceBuff<40> exec("/tmp/simlib.test.sandbox.XXXXXX");
	{
		int fd = mkstemp(exec.data());
		if (fd == -1)
			THROW("mkstemp()", errmsg());

		sclose(fd);
	}
	FileRemover exec_remover(exec.to_cstr());

	const auto test_cases_dir =
		concat(getExecDir(getpid()), "sandbox_test_cases/");

	auto compile_test_case = [&] (StringView case_filename) {
		Spawner::ExitStat es = Spawner::run("cc", {
			"cc",
			concat_tostr(test_cases_dir, case_filename),
			"-o",
			exec.to_string(),
			"-static",
		}, {-1, STDOUT_FILENO, STDERR_FILENO});

		// Compilation must be successful
		throw_assert(es.si.code == CLD_EXITED and es.si.status == 0);
	};

	Sandbox::ExitStat es;

	auto killed_or_dumped_by_abort = [&](decltype(es.si.code) si_code,
		const decltype(es.message)& message)
	{
		return ((si_code == CLD_KILLED and
				message == "killed by signal 6 - Aborted") or
			(si_code == CLD_DUMPED and
				message == "killed and dumped by signal 6 - Aborted"));
	};

	compile_test_case("1.c");
	es = sandbox.run(exec.to_cstr(), {}, opts);
	EXPECT_EQ(es.si.code, CLD_KILLED);
	EXPECT_EQ(es.si.status, SIGKILL);
	EXPECT_EQ(es.message, "Memory limit exceeded");
	EXPECT_LT((timespec{0, 0}), es.cpu_runtime);
	EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT);
	EXPECT_LT((timespec{0, 0}), es.runtime);
	EXPECT_LT(es.runtime, REAL_TIME_LIMIT);
	EXPECT_LT(0, es.vm_peak);
	EXPECT_LT(es.vm_peak, MEM_LIMIT);

	compile_test_case("2.c");
	es = sandbox.run(exec.to_cstr(), {}, opts);
	EXPECT_EQ(es.si.code, CLD_KILLED);
	EXPECT_EQ(es.si.status, SIGSEGV);
	EXPECT_EQ(es.message, "killed by signal 11 - Segmentation fault");
	EXPECT_EQ(es.cpu_runtime, (timespec{0, 0}));
	EXPECT_EQ(es.runtime, (timespec{0, 0}));
	EXPECT_EQ(es.vm_peak, 0);

	compile_test_case("3.c");
	es = sandbox.run(exec.to_cstr(), {}, opts);
	EXPECT_EQ(es.si.code, CLD_EXITED);
	EXPECT_EQ(es.si.status, 37);
	EXPECT_EQ(es.message, "exited with 37");
	EXPECT_LT((timespec{0, 0}), es.cpu_runtime);
	EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT);
	EXPECT_LT((timespec{0, 0}), es.runtime);
	EXPECT_LT(es.runtime, REAL_TIME_LIMIT);
	EXPECT_LT(0, es.vm_peak);
	EXPECT_LT(es.vm_peak, MEM_LIMIT);

	compile_test_case("4.c");
	es = sandbox.run(exec.to_cstr(), {}, opts);
	EXPECT_EQ(es.si.code, CLD_KILLED);
	EXPECT_EQ(es.si.status, SIGKILL);
	EXPECT_EQ(es.message, concat_tostr("forbidden syscall: ", SYS_socket, " - socket"));
	EXPECT_LT((timespec{0, 0}), es.cpu_runtime);
	EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT);
	EXPECT_LT((timespec{0, 0}), es.runtime);
	EXPECT_LT(es.runtime, REAL_TIME_LIMIT);
	EXPECT_LT(0, es.vm_peak);
	EXPECT_LT(es.vm_peak, MEM_LIMIT);

	compile_test_case("5.c");
	es = sandbox.run(exec.to_cstr(), {}, opts);
	EXPECT_PRED2(killed_or_dumped_by_abort, es.si.code, es.message);
	EXPECT_EQ(es.si.status, SIGABRT);
	EXPECT_LT((timespec{0, 0}), es.cpu_runtime);
	EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT);
	EXPECT_LT((timespec{0, 0}), es.runtime);
	EXPECT_LT(es.runtime, REAL_TIME_LIMIT);
	EXPECT_LT(0, es.vm_peak);
	EXPECT_LT(es.vm_peak, MEM_LIMIT);

	compile_test_case("6.c");
	es = sandbox.run(exec.to_cstr(), {}, opts);
	EXPECT_PRED2(killed_or_dumped_by_abort, es.si.code, es.message);
	EXPECT_EQ(es.si.status, SIGABRT);
	EXPECT_LT((timespec{0, 0}), es.cpu_runtime);
	EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT);
	EXPECT_LT((timespec{0, 0}), es.runtime);
	EXPECT_LT(es.runtime, REAL_TIME_LIMIT);
	EXPECT_LT(0, es.vm_peak);
	EXPECT_LT(es.vm_peak, MEM_LIMIT);

	// compile_test_case("6.c"); // not needed
	es = sandbox.run(exec.to_cstr(), {}, opts, {{"/tmp", OpenAccess::RDONLY}});
	EXPECT_EQ(es.si.code, CLD_EXITED);
	EXPECT_EQ(es.si.status, 0);
	EXPECT_EQ(es.message, "");
	EXPECT_LT((timespec{0, 0}), es.cpu_runtime);
	EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT);
	EXPECT_LT((timespec{0, 0}), es.runtime);
	EXPECT_LT(es.runtime, REAL_TIME_LIMIT);
	EXPECT_LT(0, es.vm_peak);
	EXPECT_LT(es.vm_peak, MEM_LIMIT);

	for (auto perm : {OpenAccess::NONE, OpenAccess::WRONLY, OpenAccess::RDWR}) {
		// compile_test_case("6.c"); // not needed
		es = sandbox.run(exec.to_cstr(), {}, opts, {{"/tmp", perm}});
		EXPECT_PRED2(killed_or_dumped_by_abort, es.si.code, es.message);
		EXPECT_EQ(es.si.status, SIGABRT);
		EXPECT_LT((timespec{0, 0}), es.cpu_runtime);
		EXPECT_LT(es.cpu_runtime, CPU_TIME_LIMIT);
		EXPECT_LT((timespec{0, 0}), es.runtime);
		EXPECT_LT(es.runtime, REAL_TIME_LIMIT);
		EXPECT_LT(0, es.vm_peak);
		EXPECT_LT(es.vm_peak, MEM_LIMIT);
	}
}
<|endoftext|>


<commit_before>#include "test.h"

int main() {

	rangetree<u16, const char> tree;

	tree.add(1, 1, "one");
	tree.add(1, 2, "two");
	tree.add(1, 3, "three");

	tree.finalize();

	u32 res = tree.count(0, 1, 0, 1);
	printf("The number of points in x (0, 1) and y (0, 1) is %u\n", res);
	if (res != 1)
		fail("Count wrong, got %u, expected 1\n", res);

	res = tree.count(0, 0, 0, 1);
	if (res != 0)
		fail("Count wrong, got %u, expected 1\n", res);

	res = tree.count(0, 800, 0, 1);
	if (res != 1)
		fail("Count wrong, got %u, expected 1\n", res);

	res = tree.count(0, 800, 0, 2);
	if (res != 2)
		fail("Count wrong, got %u, expected 1\n", res);

	res = tree.count(0, 80, 0, 81);
	if (res != 3)
		fail("Count wrong, got %u, expected 1\n", res);

	std::vector<const char *> *joo = tree.search(0,500,2,600);
	printf("(0,500) (2,600) search got %ld results\n", joo->size());
	for (u32 i = 0; i < joo->size(); i++) {
		printf("Node %u name %s\n", i, (*joo)[i]);
	}

	if (joo->size() != 2)
		fail("Search count wrong, got %u expected 2\n", joo->size());

	return 0;
}
<commit_msg>Simple's errors were wrong<commit_after>#include "test.h"

int main() {

	rangetree<u16, const char> tree;

	tree.add(1, 1, "one");
	tree.add(1, 2, "two");
	tree.add(1, 3, "three");

	tree.finalize();

	u32 res = tree.count(0, 1, 0, 1);
	printf("The number of points in x (0, 1) and y (0, 1) is %u\n", res);
	if (res != 1)
		fail("Count wrong, got %u, expected 1\n", res);

	res = tree.count(0, 0, 0, 1);
	if (res != 0)
		fail("Count wrong, got %u, expected 0\n", res);

	res = tree.count(0, 800, 0, 1);
	if (res != 1)
		fail("Count wrong, got %u, expected 1\n", res);

	res = tree.count(0, 800, 0, 2);
	if (res != 2)
		fail("Count wrong, got %u, expected 2\n", res);

	res = tree.count(0, 80, 0, 81);
	if (res != 3)
		fail("Count wrong, got %u, expected 3\n", res);

	std::vector<const char *> *joo = tree.search(0,500,2,600);
	printf("(0,500) (2,600) search got %ld results\n", joo->size());
	for (u32 i = 0; i < joo->size(); i++) {
		printf("Node %u name %s\n", i, (*joo)[i]);
	}

	if (joo->size() != 2)
		fail("Search count wrong, got %u expected 2\n", joo->size());

	return 0;
}
<|endoftext|>


<commit_before>include "test.haha"
<commit_msg>Updates<commit_after><|endoftext|>


<commit_before>/*
 * A little test program for md5 code which does a md5 on all the
 * bytes sent to stdin.
 */

#include <string.h>
#include <cstdlib>
#include <string>
#include <iostream>
#include <fstream>
#include <vector>
#include <sstream>

#include "../src/md5.h"

/*
 * Print a signature
 */
static void print_sig(const unsigned char *sig) {
    const unsigned char* sig_p;

    for (sig_p = sig; sig_p < sig + MD5_SIZE; sig_p++) {
        (void)printf("%02x", *sig_p);
    }
}

/*
 * Read in from stdin and run MD5 on the input
 */
static void read_file(const char* filename) {
    unsigned char sig[MD5_SIZE];
    char buffer[4096];
    md5::md5_t md5;
    bool useCin;
    std::ifstream file;

    if (filename[0] == '-') {
        useCin = true;
    } else {
        useCin = false;
        file.open(filename, std::ios::binary);
        if (!file.is_open()) {
            std::cerr << "failed to open file " << filename << std::endl;
            exit(1);
        }
    }

    /* iterate over file */
    if (useCin) {
        const char* input = filename + 1;
        std::cout << "Processing: '" << input << "'\n";
        md5.process(input, strlen(input));
    } else {
        do {
            file.read(buffer, 4096);
            md5.process(buffer, file.gcount());
        } while (file);
    }

    md5.finish(sig);

    (void)printf("%25s '", "Resulting signature:");
    print_sig(sig);
    (void)printf("'\n");

    /* convert to string to print */
    md5::sig_to_string(sig, buffer, sizeof(buffer));
    (void)printf("%25s '%s'\n", "Results of md5_to_string:", buffer);

    /* now we convert it from string back into the sig */
    md5::sig_from_string(sig, buffer);

    (void)printf("%25s '", "After md5_from_string:");
    print_sig(sig);
    (void)printf("'\n");
}

static void run_tests(void)
{
    unsigned char sig[MD5_SIZE], sig2[MD5_SIZE];
    char str[33];

  /* MD5 Test Suite from RFC1321 */
    std::vector<std::pair<const char*, const char*> > tests;
    tests.push_back(std::pair<const char*, const char*>("", "d41d8cd98f00b204e9800998ecf8427e"));
    tests.push_back(std::pair<const char*, const char*>("a", "0cc175b9c0f1b6a831c399e269772661"));
    tests.push_back(std::pair<const char*, const char*>("abc", "900150983cd24fb0d6963f7d28e17f72"));
    tests.push_back(std::pair<const char*, const char*>("message digest", "f96b697d7cb7938d525a2f31aaf161d0"));
    tests.push_back(std::pair<const char*, const char*>("abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b"));
    tests.push_back(std::pair<const char*, const char*>("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "d174ab98d277d9f5a5611c2c9f419d9f"));
    tests.push_back(std::pair<const char*, const char*>("12345678901234567890123456789012345678901234567890123456789012345678901234567890", "57edf4a22be3c955ac49da2e2107b67a"));

    tests.push_back(std::pair<const char*, const char*>("This string is precisely 56 characters long for a reason", "93d268e9bef6608ff1a6a96adbeee106"));
    tests.push_back(std::pair<const char*, const char*>("This string is exactly 64 characters long for a very good reason", "655c37c2c8451a60306d09f2971e49ff"));
    tests.push_back(std::pair<const char*, const char*>("This string is also a specific length.  It is exactly 128 characters long for a very good reason as well. We are testing bounds.", "2ac62baa5be7fa36587c55691c026b35"));

    int passed = 0;
    int passed_h = 0;
    int passed_c = 0;

    /* run our tests */
    for (unsigned int i = 0; i < tests.size(); i++) {
        bool passed_hash = 0;
        bool passed_convert = 0;

        std::cout << "Test: " << i << ": '" << tests[i].first << "'" << std::endl;
        std::cout << "Length: " << strlen(tests[i].first) << std::endl;

        /* calculate the sig for our test string */
        md5::md5_t md5(tests[i].first, strlen(tests[i].first), sig);

        /* convert from the sig to a string rep */
        md5::sig_to_string(sig, str, sizeof(str));
        if (strcmp(str, tests[i].second) == 0) {
            std::cout << "Sig for '" << tests[i].first << "' matches '" << tests[i].second << "'" << std::endl;
            passed_hash = true;
            passed_h++;
        } else {
            std::cout << "ERROR: Sig for '" << tests[i].first << "' is '" << tests[i].second << "' not '" << str << "'" << std::endl;
        }

        /* convert from the string back into a MD5 signature */
        md5::sig_from_string(sig2, str);
        if (memcmp(sig, sig2, MD5_SIZE) == 0) {
            std::cout << "  String conversion also matches\n";
            passed_convert = true;
            passed_c++;
        } else {
            std::cout << "  ERROR: String conversion for '" << tests[i].second << "' failed\n";
        }

        if (passed_hash and passed_convert) {
            passed++;
        }
    }

    std::cout << std::endl << "*******************************" << std::endl
              << "    " << passed << " of " << tests.size() << " tests passed" << std::endl;
    if (passed != tests.size()) {
        std::cout << std::endl << "   Please notify developer" << std::endl;
        std::cout << "  " << passed_h << " passed hashing check" << std::endl
                  << "  " << passed_h << " passed comparison check" << std::endl;
    }
    std::cout << "*******************************" << std::endl;
}

/*
 * print the usage message
 */
static void usage(void) {
    (void)fprintf(stderr, "Usage: md5_t [-r file]\n");
    exit(1);
}

int main(int argc, char **argv) {
    char do_read = 0;
    char* infile = NULL;

    argc--;
    argv++;

    /* process the args */
    for (; *argv != NULL; argc--, argv++) {
        if (**argv != '-') {
            continue;
        }

        switch (*(*argv + 1)) {
            case 'r':
                do_read = 1;
                argc--;
                argv++;

                if (argc == 0) {
                    usage();
                }

                infile = *argv;
                break;

            default:
                usage();
                break;
            }
    }

    if (argc > 0) {
        usage();
    }

    /* do we need to read in from stdin */
    if (do_read) {
        read_file(infile);
    } else {
        run_tests();
    }

    return 0;
}

<commit_msg>removes erroneous includes<commit_after>/*
 * A little test program for md5 code which does a md5 on all the
 * bytes sent to stdin.
 */

#include <string.h>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <vector>

#include "../src/md5.h"

/*
 * Print a signature
 */
static void print_sig(const unsigned char *sig) {
    const unsigned char* sig_p;

    for (sig_p = sig; sig_p < sig + MD5_SIZE; sig_p++) {
        (void)printf("%02x", *sig_p);
    }
}

/*
 * Read in from stdin and run MD5 on the input
 */
static void read_file(const char* filename) {
    unsigned char sig[MD5_SIZE];
    char buffer[4096];
    md5::md5_t md5;
    bool useCin;
    std::ifstream file;

    if (filename[0] == '-') {
        useCin = true;
    } else {
        useCin = false;
        file.open(filename, std::ios::binary);
        if (!file.is_open()) {
            std::cerr << "failed to open file " << filename << std::endl;
            exit(1);
        }
    }

    /* iterate over file */
    if (useCin) {
        const char* input = filename + 1;
        std::cout << "Processing: '" << input << "'\n";
        md5.process(input, strlen(input));
    } else {
        do {
            file.read(buffer, 4096);
            md5.process(buffer, file.gcount());
        } while (file);
    }

    md5.finish(sig);

    (void)printf("%25s '", "Resulting signature:");
    print_sig(sig);
    (void)printf("'\n");

    /* convert to string to print */
    md5::sig_to_string(sig, buffer, sizeof(buffer));
    (void)printf("%25s '%s'\n", "Results of md5_to_string:", buffer);

    /* now we convert it from string back into the sig */
    md5::sig_from_string(sig, buffer);

    (void)printf("%25s '", "After md5_from_string:");
    print_sig(sig);
    (void)printf("'\n");
}

static void run_tests(void)
{
    unsigned char sig[MD5_SIZE], sig2[MD5_SIZE];
    char str[33];

  /* MD5 Test Suite from RFC1321 */
    std::vector<std::pair<const char*, const char*> > tests;
    tests.push_back(std::pair<const char*, const char*>("", "d41d8cd98f00b204e9800998ecf8427e"));
    tests.push_back(std::pair<const char*, const char*>("a", "0cc175b9c0f1b6a831c399e269772661"));
    tests.push_back(std::pair<const char*, const char*>("abc", "900150983cd24fb0d6963f7d28e17f72"));
    tests.push_back(std::pair<const char*, const char*>("message digest", "f96b697d7cb7938d525a2f31aaf161d0"));
    tests.push_back(std::pair<const char*, const char*>("abcdefghijklmnopqrstuvwxyz", "c3fcd3d76192e4007dfb496cca67e13b"));
    tests.push_back(std::pair<const char*, const char*>("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789", "d174ab98d277d9f5a5611c2c9f419d9f"));
    tests.push_back(std::pair<const char*, const char*>("12345678901234567890123456789012345678901234567890123456789012345678901234567890", "57edf4a22be3c955ac49da2e2107b67a"));

    tests.push_back(std::pair<const char*, const char*>("This string is precisely 56 characters long for a reason", "93d268e9bef6608ff1a6a96adbeee106"));
    tests.push_back(std::pair<const char*, const char*>("This string is exactly 64 characters long for a very good reason", "655c37c2c8451a60306d09f2971e49ff"));
    tests.push_back(std::pair<const char*, const char*>("This string is also a specific length.  It is exactly 128 characters long for a very good reason as well. We are testing bounds.", "2ac62baa5be7fa36587c55691c026b35"));

    int passed = 0;
    int passed_h = 0;
    int passed_c = 0;

    /* run our tests */
    for (unsigned int i = 0; i < tests.size(); i++) {
        bool passed_hash = 0;
        bool passed_convert = 0;

        std::cout << "Test: " << i << ": '" << tests[i].first << "'" << std::endl;
        std::cout << "Length: " << strlen(tests[i].first) << std::endl;

        /* calculate the sig for our test string */
        md5::md5_t md5(tests[i].first, strlen(tests[i].first), sig);

        /* convert from the sig to a string rep */
        md5::sig_to_string(sig, str, sizeof(str));
        if (strcmp(str, tests[i].second) == 0) {
            std::cout << "Sig for '" << tests[i].first << "' matches '" << tests[i].second << "'" << std::endl;
            passed_hash = true;
            passed_h++;
        } else {
            std::cout << "ERROR: Sig for '" << tests[i].first << "' is '" << tests[i].second << "' not '" << str << "'" << std::endl;
        }

        /* convert from the string back into a MD5 signature */
        md5::sig_from_string(sig2, str);
        if (memcmp(sig, sig2, MD5_SIZE) == 0) {
            std::cout << "  String conversion also matches\n";
            passed_convert = true;
            passed_c++;
        } else {
            std::cout << "  ERROR: String conversion for '" << tests[i].second << "' failed\n";
        }

        if (passed_hash and passed_convert) {
            passed++;
        }
    }

    std::cout << std::endl << "*******************************" << std::endl
              << "    " << passed << " of " << tests.size() << " tests passed" << std::endl;
    if (passed != tests.size()) {
        std::cout << std::endl << "   Please notify developer" << std::endl;
        std::cout << "  " << passed_h << " passed hashing check" << std::endl
                  << "  " << passed_h << " passed comparison check" << std::endl;
    }
    std::cout << "*******************************" << std::endl;
}

/*
 * print the usage message
 */
static void usage(void) {
    (void)fprintf(stderr, "Usage: md5_t [-r file]\n");
    exit(1);
}

int main(int argc, char **argv) {
    char do_read = 0;
    char* infile = NULL;

    argc--;
    argv++;

    /* process the args */
    for (; *argv != NULL; argc--, argv++) {
        if (**argv != '-') {
            continue;
        }

        switch (*(*argv + 1)) {
            case 'r':
                do_read = 1;
                argc--;
                argv++;

                if (argc == 0) {
                    usage();
                }

                infile = *argv;
                break;

            default:
                usage();
                break;
            }
    }

    if (argc > 0) {
        usage();
    }

    /* do we need to read in from stdin */
    if (do_read) {
        read_file(infile);
    } else {
        run_tests();
    }

    return 0;
}

<|endoftext|>


<commit_before>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2010, Rice University
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of the Rice University nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/

/* Author: Ioan Sucan */

#include "ompl/control/PathControl.h"
#include "ompl/geometric/PathGeometric.h"
#include "ompl/base/samplers/UniformValidStateSampler.h"
#include "ompl/util/Exception.h"
#include <numeric>
#include <cmath>

ompl::control::PathControl::PathControl(const base::SpaceInformationPtr &si) : base::Path(si)
{
    if (!dynamic_cast<const SpaceInformation*>(si_.get()))
        throw Exception("Cannot create a path with controls from a space that does not support controls");
}

ompl::control::PathControl::PathControl(const PathControl &path) : base::Path(path.si_)
{
    copyFrom(path);
}

ompl::geometric::PathGeometric ompl::control::PathControl::asGeometric(void) const
{
    PathControl pc(*this);
    pc.interpolate();
    geometric::PathGeometric pg(si_);
    pg.states.swap(pc.states);
    return pg;
}

ompl::control::PathControl& ompl::control::PathControl::operator=(const PathControl& other)
{
    freeMemory();
    si_ = other.si_;
    copyFrom(other);
    return *this;
}

void ompl::control::PathControl::copyFrom(const PathControl& other)
{
    states.resize(other.states.size());
    controls.resize(other.controls.size());

    for (unsigned int i = 0 ; i < states.size() ; ++i)
        states[i] = si_->cloneState(other.states[i]);

    const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get());
    for (unsigned int i = 0 ; i < controls.size() ; ++i)
        controls[i] = si->cloneControl(other.controls[i]);

    controlDurations = other.controlDurations;
}

double ompl::control::PathControl::length(void) const
{
    return std::accumulate(controlDurations.begin(), controlDurations.end(), 0.0);
}

void ompl::control::PathControl::print(std::ostream &out) const
{
    const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get());
    double res = si->getPropagationStepSize();
    out << "Control path with " << states.size() << " states" << std::endl;
    for (unsigned int i = 0 ; i < controls.size() ; ++i)
    {
        out << "At state ";
        si_->printState(states[i], out);
        out << "  apply control ";
        si->printControl(controls[i], out);
        out << "  for " << (int)floor(0.5 + controlDurations[i]/res) << " steps" << std::endl;
    }
    out << "Arrive at state ";
    si_->printState(states[controls.size()], out);
    out << std::endl;
}

void ompl::control::PathControl::interpolate(void)
{
    const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get());
    std::vector<base::State*> newStates;
    std::vector<Control*> newControls;
    std::vector<double> newControlDurations;

    double res = si->getPropagationStepSize();
    for (unsigned int  i = 0 ; i < controls.size() ; ++i)
    {
        int steps = (int)floor(0.5 + controlDurations[i] / res);
        assert(steps >= 0);
        if (steps <= 1)
        {
            newStates.push_back(states[i]);
            newControls.push_back(controls[i]);
            newControlDurations.push_back(controlDurations[i]);
            continue;
        }
        std::vector<base::State*> istates;
        si->propagate(states[i], controls[i], steps, istates, true);
        // last state is already in the non-interpolated path
        if (!istates.empty())
        {
            si_->freeState(istates.back());
            istates.pop_back();
        }
        newStates.push_back(states[i]);
        newStates.insert(newStates.end(), istates.begin(), istates.end());
        newControls.push_back(controls[i]);
        newControlDurations.push_back(res);
        for (int j = 1 ; j < steps; ++j)
        {
            newControls.push_back(si->cloneControl(controls[i]));
            newControlDurations.push_back(res);
        }
    }
    newStates.push_back(states[controls.size()]);
    states.swap(newStates);
    controls.swap(newControls);
    controlDurations.swap(newControlDurations);
}

bool ompl::control::PathControl::check(void) const
{
    bool valid = true;
    const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get());
    double res = si->getPropagationStepSize();
    base::State *dummy = si_->allocState();
    for (unsigned int  i = 0 ; i < controls.size() ; ++i)
    {
        unsigned int steps = (unsigned int)floor(0.5 + controlDurations[i] / res);
        if (si->propagateWhileValid(states[i], controls[i], steps, dummy) != steps)
        {
            valid = false;
            break;
        }
    }
    si_->freeState(dummy);

    if (valid)
        for (unsigned int j = 0 ; j < states.size() ; ++j)
            if (!si_->isValid(states[j]))
                throw Exception("Internal error. This should not ever happen. Please contact the developers.");

    return valid;
}

void ompl::control::PathControl::random(void)
{
    freeMemory();
    states.resize(2);
    controlDurations.resize(1);
    controls.resize(1);

    const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get());
    states[0] = si->allocState();
    states[1] = si->allocState();
    controls[0] = si->allocControl();

    base::ManifoldStateSamplerPtr ss = si->allocManifoldStateSampler();
    ss->sampleUniform(states[0]);
    ControlSamplerPtr cs = si->allocControlSampler();
    cs->sample(controls[0], states[0]);
    controlDurations[0] = cs->sampleStepCount(si->getMinControlDuration(), si->getMaxControlDuration());
    si->propagate(states[0], controls[0], controlDurations[0], states[1]);
}

bool ompl::control::PathControl::randomValid(unsigned int attempts)
{
    freeMemory();
    states.resize(2);
    controlDurations.resize(1);
    controls.resize(1);

    const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get());
    states[0] = si->allocState();
    states[1] = si->allocState();
    controls[0] = si->allocControl();

    ControlSamplerPtr cs = si->allocControlSampler();
    base::UniformValidStateSampler *uvss = new base::UniformValidStateSampler(si);
    uvss->setNrAttempts(attempts);
    bool ok = false;
    for (unsigned int i = 0 ; i < attempts ; ++i)
        if (uvss->sample(states[0]))
        {
            cs->sample(controls[0], states[0]);
            controlDurations[0] = cs->sampleStepCount(si->getMinControlDuration(), si->getMaxControlDuration());
            if (si->propagateWhileValid(states[0], controls[0], controlDurations[0], states[1]) == controlDurations[0])
            {
                ok = true;
                break;
            }
        }
    delete uvss;

    if (!ok)
    {
        freeMemory();
        states.clear();
        controls.clear();
        controlDurations.clear();
    }
    return ok;
}

void ompl::control::PathControl::freeMemory(void)
{
    for (unsigned int i = 0 ; i < states.size() ; ++i)
        si_->freeState(states[i]);
    const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get());
    for (unsigned int i = 0 ; i < controls.size() ; ++i)
        si->freeControl(controls[i]);
}
<commit_msg>bugfix for random path generation<commit_after>/*********************************************************************
* Software License Agreement (BSD License)
*
*  Copyright (c) 2010, Rice University
*  All rights reserved.
*
*  Redistribution and use in source and binary forms, with or without
*  modification, are permitted provided that the following conditions
*  are met:
*
*   * Redistributions of source code must retain the above copyright
*     notice, this list of conditions and the following disclaimer.
*   * Redistributions in binary form must reproduce the above
*     copyright notice, this list of conditions and the following
*     disclaimer in the documentation and/or other materials provided
*     with the distribution.
*   * Neither the name of the Rice University nor the names of its
*     contributors may be used to endorse or promote products derived
*     from this software without specific prior written permission.
*
*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
*  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
*  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
*  FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
*  COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
*  INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
*  BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
*  CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
*  LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
*  ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
*  POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/

/* Author: Ioan Sucan */

#include "ompl/control/PathControl.h"
#include "ompl/geometric/PathGeometric.h"
#include "ompl/base/samplers/UniformValidStateSampler.h"
#include "ompl/util/Exception.h"
#include <numeric>
#include <cmath>

ompl::control::PathControl::PathControl(const base::SpaceInformationPtr &si) : base::Path(si)
{
    if (!dynamic_cast<const SpaceInformation*>(si_.get()))
        throw Exception("Cannot create a path with controls from a space that does not support controls");
}

ompl::control::PathControl::PathControl(const PathControl &path) : base::Path(path.si_)
{
    copyFrom(path);
}

ompl::geometric::PathGeometric ompl::control::PathControl::asGeometric(void) const
{
    PathControl pc(*this);
    pc.interpolate();
    geometric::PathGeometric pg(si_);
    pg.states.swap(pc.states);
    return pg;
}

ompl::control::PathControl& ompl::control::PathControl::operator=(const PathControl& other)
{
    freeMemory();
    si_ = other.si_;
    copyFrom(other);
    return *this;
}

void ompl::control::PathControl::copyFrom(const PathControl& other)
{
    states.resize(other.states.size());
    controls.resize(other.controls.size());

    for (unsigned int i = 0 ; i < states.size() ; ++i)
        states[i] = si_->cloneState(other.states[i]);

    const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get());
    for (unsigned int i = 0 ; i < controls.size() ; ++i)
        controls[i] = si->cloneControl(other.controls[i]);

    controlDurations = other.controlDurations;
}

double ompl::control::PathControl::length(void) const
{
    return std::accumulate(controlDurations.begin(), controlDurations.end(), 0.0);
}

void ompl::control::PathControl::print(std::ostream &out) const
{
    const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get());
    double res = si->getPropagationStepSize();
    out << "Control path with " << states.size() << " states" << std::endl;
    for (unsigned int i = 0 ; i < controls.size() ; ++i)
    {
        out << "At state ";
        si_->printState(states[i], out);
        out << "  apply control ";
        si->printControl(controls[i], out);
        out << "  for " << (int)floor(0.5 + controlDurations[i]/res) << " steps" << std::endl;
    }
    out << "Arrive at state ";
    si_->printState(states[controls.size()], out);
    out << std::endl;
}

void ompl::control::PathControl::interpolate(void)
{
    const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get());
    std::vector<base::State*> newStates;
    std::vector<Control*> newControls;
    std::vector<double> newControlDurations;

    double res = si->getPropagationStepSize();
    for (unsigned int  i = 0 ; i < controls.size() ; ++i)
    {
        int steps = (int)floor(0.5 + controlDurations[i] / res);
        assert(steps >= 0);
        if (steps <= 1)
        {
            newStates.push_back(states[i]);
            newControls.push_back(controls[i]);
            newControlDurations.push_back(controlDurations[i]);
            continue;
        }
        std::vector<base::State*> istates;
        si->propagate(states[i], controls[i], steps, istates, true);
        // last state is already in the non-interpolated path
        if (!istates.empty())
        {
            si_->freeState(istates.back());
            istates.pop_back();
        }
        newStates.push_back(states[i]);
        newStates.insert(newStates.end(), istates.begin(), istates.end());
        newControls.push_back(controls[i]);
        newControlDurations.push_back(res);
        for (int j = 1 ; j < steps; ++j)
        {
            newControls.push_back(si->cloneControl(controls[i]));
            newControlDurations.push_back(res);
        }
    }
    newStates.push_back(states[controls.size()]);
    states.swap(newStates);
    controls.swap(newControls);
    controlDurations.swap(newControlDurations);
}

bool ompl::control::PathControl::check(void) const
{
    bool valid = true;
    const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get());
    double res = si->getPropagationStepSize();
    base::State *dummy = si_->allocState();
    for (unsigned int  i = 0 ; i < controls.size() ; ++i)
    {
        unsigned int steps = (unsigned int)floor(0.5 + controlDurations[i] / res);
        if (si->propagateWhileValid(states[i], controls[i], steps, dummy) != steps)
        {
            valid = false;
            break;
        }
    }
    si_->freeState(dummy);

    if (valid)
        for (unsigned int j = 0 ; j < states.size() ; ++j)
            if (!si_->isValid(states[j]))
                throw Exception("Internal error. This should not ever happen. Please contact the developers.");

    return valid;
}

void ompl::control::PathControl::random(void)
{
    freeMemory();
    states.resize(2);
    controlDurations.resize(1);
    controls.resize(1);

    const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get());
    states[0] = si->allocState();
    states[1] = si->allocState();
    controls[0] = si->allocControl();

    base::ManifoldStateSamplerPtr ss = si->allocManifoldStateSampler();
    ss->sampleUniform(states[0]);
    ControlSamplerPtr cs = si->allocControlSampler();
    cs->sample(controls[0], states[0]);
    unsigned int steps = cs->sampleStepCount(si->getMinControlDuration(), si->getMaxControlDuration());
    controlDurations[0] = steps * si->getPropagationStepSize();
    si->propagate(states[0], controls[0], steps, states[1]);
}

bool ompl::control::PathControl::randomValid(unsigned int attempts)
{
    freeMemory();
    states.resize(2);
    controlDurations.resize(1);
    controls.resize(1);

    const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get());
    states[0] = si->allocState();
    states[1] = si->allocState();
    controls[0] = si->allocControl();

    ControlSamplerPtr cs = si->allocControlSampler();
    base::UniformValidStateSampler *uvss = new base::UniformValidStateSampler(si);
    uvss->setNrAttempts(attempts);
    bool ok = false;
    for (unsigned int i = 0 ; i < attempts ; ++i)
        if (uvss->sample(states[0]))
        {
            cs->sample(controls[0], states[0]);
            unsigned int steps = cs->sampleStepCount(si->getMinControlDuration(), si->getMaxControlDuration());
            controlDurations[0] = steps * si->getPropagationStepSize();
            if (si->propagateWhileValid(states[0], controls[0], steps, states[1]) == steps)
            {
                ok = true;
                break;
            }
        }
    delete uvss;

    if (!ok)
    {
        freeMemory();
        states.clear();
        controls.clear();
        controlDurations.clear();
    }
    return ok;
}

void ompl::control::PathControl::freeMemory(void)
{
    for (unsigned int i = 0 ; i < states.size() ; ++i)
        si_->freeState(states[i]);
    const SpaceInformation *si = static_cast<const SpaceInformation*>(si_.get());
    for (unsigned int i = 0 ; i < controls.size() ; ++i)
        si->freeControl(controls[i]);
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestPLYReaderTextureUV.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// .NAME Test of vtkPLYReader
// .SECTION Description
//

#include "vtkPLYReader.h"
#include "vtkDebugLeaks.h"

#include "vtkActor.h"
#include "vtkPNGReader.h"
#include "vtkPolyDataMapper.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRegressionTestImage.h"
#include "vtkTestUtilities.h"
#include "vtkTexture.h"

#include "vtkWindowToImageFilter.h"

int TestPLYReaderTextureUV( int argc, char *argv[] )
{
  // Read file name.
  const char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/squareTextured.ply");
  const char* fnameImg = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/vtk.png");

  // Test if the reader thinks it can open the file.
  int canRead = vtkPLYReader::CanReadFile(fname);
  canRead = vtkPLYReader::CanReadFile(fnameImg);
  (void)canRead;

  // Create the reader.
  vtkPLYReader* reader = vtkPLYReader::New();
  reader->SetFileName(fname);
  reader->Update();
  delete [] fname;

  vtkPNGReader* readerImg = vtkPNGReader::New();
  readerImg->SetFileName(fnameImg);
  readerImg->Update();
  delete[] fnameImg;

  // Create the texture.
  vtkTexture* texture = vtkTexture::New();
  texture->SetInputConnection(readerImg->GetOutputPort());

  // Create a mapper.
  vtkPolyDataMapper* mapper = vtkPolyDataMapper::New();
  mapper->SetInputConnection(reader->GetOutputPort());
  mapper->ScalarVisibilityOn();

  // Create the actor.
  vtkActor* actor = vtkActor::New();
  actor->SetMapper(mapper);
  actor->SetTexture(texture);

  // Basic visualisation.
  vtkRenderWindow* renWin = vtkRenderWindow::New();
  vtkRenderer* ren = vtkRenderer::New();
  renWin->AddRenderer(ren);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);

  ren->AddActor(actor);
  ren->SetBackground(0,0,0);
  renWin->SetSize(300,300);

  // interact with data
  renWin->Render();

  int retVal = vtkRegressionTestImage( renWin );

  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  actor->Delete();
  mapper->Delete();
  reader->Delete();
  readerImg->Delete();
  texture->Delete();
  renWin->Delete();
  ren->Delete();
  iren->Delete();

  return !retVal;
}
<commit_msg>Add return value check in the unit test.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    TestPLYReaderTextureUV.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
// .NAME Test of vtkPLYReader
// .SECTION Description
//

#include "vtkPLYReader.h"

#include "vtkActor.h"
#include "vtkPNGReader.h"
#include "vtkPolyDataMapper.h"
#include "vtkRenderer.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRegressionTestImage.h"
#include "vtkTestUtilities.h"
#include "vtkTexture.h"

int TestPLYReaderTextureUV( int argc, char *argv[] )
{
  // Read file name.
  const char* fname = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/squareTextured.ply");
  const char* fnameImg = vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/vtk.png");

  // Test if the reader thinks it can open the file.
  if (0 == vtkPLYReader::CanReadFile(fname))
    {
    std::cout << "The PLY reader can not read the input file." << std::endl;
    return EXIT_FAILURE;
    }

  // Create the reader.
  vtkPLYReader* reader = vtkPLYReader::New();
  reader->SetFileName(fname);
  reader->Update();
  delete [] fname;

  vtkPNGReader* readerImg = vtkPNGReader::New();
  if (0 == readerImg->CanReadFile(fnameImg))
  {
     std::cout << "The PNG reader can not read the input file." << std::endl;
     return EXIT_FAILURE;
  }
  readerImg->SetFileName(fnameImg);
  readerImg->Update();
  delete[] fnameImg;

  // Create the texture.
  vtkTexture* texture = vtkTexture::New();
  texture->SetInputConnection(readerImg->GetOutputPort());

  // Create a mapper.
  vtkPolyDataMapper* mapper = vtkPolyDataMapper::New();
  mapper->SetInputConnection(reader->GetOutputPort());
  mapper->ScalarVisibilityOn();

  // Create the actor.
  vtkActor* actor = vtkActor::New();
  actor->SetMapper(mapper);
  actor->SetTexture(texture);

  // Basic visualisation.
  vtkRenderWindow* renWin = vtkRenderWindow::New();
  vtkRenderer* ren = vtkRenderer::New();
  renWin->AddRenderer(ren);
  vtkRenderWindowInteractor *iren = vtkRenderWindowInteractor::New();
  iren->SetRenderWindow(renWin);

  ren->AddActor(actor);
  ren->SetBackground(0,0,0);
  renWin->SetSize(300,300);

  // interact with data
  renWin->Render();

  int retVal = vtkRegressionTestImage( renWin );

  if ( retVal == vtkRegressionTester::DO_INTERACTOR)
    {
    iren->Start();
    }

  actor->Delete();
  mapper->Delete();
  reader->Delete();
  readerImg->Delete();
  texture->Delete();
  renWin->Delete();
  ren->Delete();
  iren->Delete();

  return !retVal;
}
<|endoftext|>