<commit_before>// Copyright (c) 2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#include "test.hpp"

#include "verify_meta.hpp"

namespace TAO_PEGTL_NAMESPACE
{
   template< tracking_mode M >
   void unit_test()
   {
      memory_input< M > in( "foo\nbar bla blubb\nbaz", "test_source" );

      try {
         parse< seq< identifier, eol, identifier, one< ' ' >, must< digit > > >( in );
      }
      catch( const parse_error& e ) {
         TAO_PEGTL_TEST_ASSERT( e.what(), "parse error matching tao::pegtl::ascii::digit" );

         TAO_PEGTL_TEST_ASSERT( e.positions.size() == 1 );
         const auto& p = e.positions.front();

         TAO_PEGTL_TEST_ASSERT( p.byte == 8 );
         TAO_PEGTL_TEST_ASSERT( p.line == 2 );
         TAO_PEGTL_TEST_ASSERT( p.byte_in_line == 5 );
         TAO_PEGTL_TEST_ASSERT( p.source == "test_source" );
         TAO_PEGTL_TEST_ASSERT( to_string( p ) == "test_source:2:5(8)" );

         TAO_PEGTL_TEST_ASSERT( to_string( e ) == "test_source:2:5(8): parse error matching tao::pegtl::ascii::digit" );

         TAO_PEGTL_TEST_ASSERT( in.line_at( p ) == "bar bla blubb" );

         return;
      }
      TAO_PEGTL_TEST_UNREACHABLE;
   }

   void unit_test()
   {
      unit_test< tracking_mode::eager >();
      unit_test< tracking_mode::lazy >();
   }

}  // namespace TAO_PEGTL_NAMESPACE

#include "main.hpp"
<commit_msg>Fix test for MSVC<commit_after>// Copyright (c) 2020 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/

#include "test.hpp"

#include "verify_meta.hpp"

namespace TAO_PEGTL_NAMESPACE
{
   template< tracking_mode M >
   void unit_test()
   {
      const std::string rulename{ demangle< digit >() };

      memory_input< M > in( "foo\nbar bla blubb\nbaz", "test_source" );

      try {
         parse< seq< identifier, eol, identifier, one< ' ' >, must< digit > > >( in );
      }
      catch( const parse_error& e ) {
         TAO_PEGTL_TEST_ASSERT( e.what() == "parse error matching " + rulename );

         TAO_PEGTL_TEST_ASSERT( e.positions.size() == 1 );
         const auto& p = e.positions.front();

         TAO_PEGTL_TEST_ASSERT( p.byte == 8 );
         TAO_PEGTL_TEST_ASSERT( p.line == 2 );
         TAO_PEGTL_TEST_ASSERT( p.byte_in_line == 5 );
         TAO_PEGTL_TEST_ASSERT( p.source == "test_source" );
         TAO_PEGTL_TEST_ASSERT( to_string( p ) == "test_source:2:5(8)" );

         TAO_PEGTL_TEST_ASSERT( to_string( e ) == "test_source:2:5(8): parse error matching " + rulename );

         TAO_PEGTL_TEST_ASSERT( in.line_at( p ) == "bar bla blubb" );

         return;
      }
      TAO_PEGTL_TEST_UNREACHABLE;
   }

   void unit_test()
   {
      unit_test< tracking_mode::eager >();
      unit_test< tracking_mode::lazy >();
   }

}  // namespace TAO_PEGTL_NAMESPACE

#include "main.hpp"
<|endoftext|>


<commit_before>#include "StdAfx.h"
#include "Tests.h"
#include "stdlib.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

void TestAllocationMismatch_malloc_delete()
{
	int* pint = (int*)malloc(56);
	// use the wrong function to deallocate
	delete pint;
}

void TestAllocationMismatch_malloc_deleteVec()
{
	int* pint = (int*)malloc(56);
	// use the wrong function to deallocate
	delete [] pint;
}

void TestAllocationMismatch_new_free()
{
	int* pint = new int(45); // scalar new
	// use the wrong function to deallocate
	free(pint);
}

void TestAllocationMismatch_newVec_free()
{
	int* pint = new int[3]; // vector new
	// use the wrong function to deallocate
	free(pint);
}

void TestHeapMismatch()
{
	HANDLE test_heap = HeapCreate(HEAP_GENERATE_EXCEPTIONS | HEAP_CREATE_ENABLE_EXECUTE,
									0, // initialize reserved size;
									0); // maximum size can grow
	HANDLE default_heap = GetProcessHeap();
	// Have to initialize vld with something, so it doesn't dismiss
	// the default heap as having no memory allocs in it.
	void* aptr = HeapAlloc(default_heap, 0, 42);
	// Allocate it in the new heap
	void* vptr = HeapAlloc(test_heap, 0, 56);
	// Free this using the WRONG heap!
	HeapFree( default_heap, 0, vptr);

	HeapDestroy(test_heap);
}
<commit_msg>Set HeapEnableTerminationOnCorruption to ensure process termination on corruption test<commit_after>#include "StdAfx.h"
#include "Tests.h"
#include "stdlib.h"
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>

void TestAllocationMismatch_malloc_delete()
{
	int* pint = (int*)malloc(56);
	// use the wrong function to deallocate
	delete pint;
}

void TestAllocationMismatch_malloc_deleteVec()
{
	int* pint = (int*)malloc(56);
	// use the wrong function to deallocate
	delete [] pint;
}

void TestAllocationMismatch_new_free()
{
	int* pint = new int(45); // scalar new
	// use the wrong function to deallocate
	free(pint);
}

void TestAllocationMismatch_newVec_free()
{
	int* pint = new int[3]; // vector new
	// use the wrong function to deallocate
	free(pint);
}

void TestHeapMismatch()
{
	HANDLE test_heap = HeapCreate(HEAP_GENERATE_EXCEPTIONS | HEAP_CREATE_ENABLE_EXECUTE,
									0, // initialize reserved size;
									0); // maximum size can grow
	HeapSetInformation(test_heap, HeapEnableTerminationOnCorruption, NULL, 0);
	HANDLE default_heap = GetProcessHeap();
	HeapSetInformation(default_heap, HeapEnableTerminationOnCorruption, NULL, 0);
	// Have to initialize vld with something, so it doesn't dismiss
	// the default heap as having no memory allocs in it.
	void* aptr = HeapAlloc(default_heap, 0, 42);
	// Allocate it in the new heap
	void* vptr = HeapAlloc(test_heap, 0, 56);
	// Free this using the WRONG heap!
	HeapFree( default_heap, 0, vptr);

	HeapDestroy(test_heap);
}
<|endoftext|>


<commit_before>#include <iostream>     // std::cout, std::cin, std::endl
#include <queue>        // std::queue, std::push, std::pop, std::front
#include <tuple>
#include "extra.hpp"    // int_to_string

#ifndef CUBE_H
#define CUBE_H

class Cube {
/*
    Vamos a definir que un cubo tiene las siguientes caras,
    que comienzan de los colores:
        front = white
        back  = yellow
        left  = orange
        right = red
        top   = blue
        down  = green

          ____________
         /   /   /   /\
        /___/___/___/  \
       /   / T /   /\  /\
     L/___/___/___/  \/  \B
     /   /   /   /\  /\  /\
    /___/___/___/  \/  \/  \
    \   \   \   \  /\R /\  /
     \___\___\___\/  \/  \/
      \   \ F \   \  /\  /
       \___\___\___\/  \/D
        \   \   \   \  /
         \___\___\___\/

    LTF:
        LT = X
        FT = Y
        LF = Z

        T = XY = A
        L = YZ = B
        F = XZ = C

////////////////////////////////////////

    cubie    X  orientation
    |_|_|_| |_| |_|_|_|_|
     A B C        0 - 7

    C -> goal orientation for all corners and eight edges

 */

    public:
        // Constructor
        Cube();
        ~Cube();
        Cube* clone();

        std::string to_string();
        std::string corners_to_string();
        std::string edges_to_string();
        std::string printable();

        bool equals(Cube* other);

        // operations on the cube
        void clock(char face);
        void counter(char face);
        void hundred(char face);

        std::queue<Cube*>* succ();

        uint8_t* get_corners();
        bool equals_corners(uint8_t *other);

    private:
        uint8_t *corners;
        uint8_t *edges;
        char last;

        int* switch_get(char chr);
        void switch_set(char chr, int* face);

        // getters and setters for the faces of the cube
        int* get_front();
        void set_front(int* face);
        int* get_back();
        void set_back(int* face);
        int* get_right();
        void set_right(int* face);
        int* get_left();
        void set_left(int* face);
        int* get_top();
        void set_top(int* face);
        int* get_down();
        void set_down(int* face);

        std::string color_face(int* face, char chr);
};
#endif
<commit_msg>comentario de goal para edges<commit_after>#include <iostream>     // std::cout, std::cin, std::endl
#include <queue>        // std::queue, std::push, std::pop, std::front
#include <tuple>
#include "extra.hpp"    // int_to_string

#ifndef CUBE_H
#define CUBE_H

class Cube {
/*
    Vamos a definir que un cubo tiene las siguientes caras,
    que comienzan de los colores:
        front = white
        back  = yellow
        left  = orange
        right = red
        top   = blue
        down  = green

          ____________
         /   /   /   /\
        /___/___/___/  \
       /   / T /   /\  /\
     L/___/___/___/  \/  \B
     /   /   /   /\  /\  /\
    /___/___/___/  \/  \/  \
    \   \   \   \  /\R /\  /
     \___\___\___\/  \/  \/
      \   \ F \   \  /\  /
       \___\___\___\/  \/D
        \   \   \   \  /
         \___\___\___\/

    LTF:
        LT = X
        FT = Y
        LF = Z

        T = XY = A
        L = YZ = B
        F = XZ = C

////////////////////////////////////////

    cubie    X  orientation
    |_|_|_| |_| |_|_|_|_|
     A B C        0 - 7

    C -> goal orientation for all corners and eight edges
    B -> goal orientation for other 4 edges
 */

    public:
        // Constructor
        Cube();
        ~Cube();
        Cube* clone();

        std::string to_string();
        std::string corners_to_string();
        std::string edges_to_string();
        std::string printable();

        bool equals(Cube* other);

        // operations on the cube
        void clock(char face);
        void counter(char face);
        void hundred(char face);

        std::queue<Cube*>* succ();

        uint8_t* get_corners();
        bool equals_corners(uint8_t *other);

    private:
        uint8_t *corners;
        uint8_t *edges;
        char last;

        int* switch_get(char chr);
        void switch_set(char chr, int* face);

        // getters and setters for the faces of the cube
        int* get_front();
        void set_front(int* face);
        int* get_back();
        void set_back(int* face);
        int* get_right();
        void set_right(int* face);
        int* get_left();
        void set_left(int* face);
        int* get_top();
        void set_top(int* face);
        int* get_down();
        void set_down(int* face);

        std::string color_face(int* face, char chr);
};
#endif
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/
#include "modules/planning/math/smoothing_spline/spline_2d_constraint.h"

#include "glog/logging.h"
#include "gtest/gtest.h"

namespace apollo {
namespace planning {

using apollo::common::math::Vec2d;

TEST(Spline2dConstraint, add_boundary_01) {
  std::vector<double> x_knots = {0.0, 1.0};
  int32_t spline_order = 4;
  Spline2dConstraint constraint(x_knots, spline_order);

  std::vector<double> t_coord = {0.0};
  std::vector<double> angle = {0.0};
  std::vector<Vec2d> ref_point;
  ref_point.emplace_back(Vec2d(0.0, 0.0));
  std::vector<double> longitidinal_bound = {1.0};
  std::vector<double> lateral_bound = {2.0};

  constraint.Add2dBoundary(t_coord, angle, ref_point, longitidinal_bound,
                           lateral_bound);
  const auto mat = constraint.inequality_constraint().constraint_matrix();
  const auto boundary =
      constraint.inequality_constraint().constraint_boundary();

  // clang-format off
  Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 8);
  ref_mat <<
     -0, -0,  -0,  -0,            1,  0,  0,  0,
      0,  0,   0,   0,           -1, -0, -0, -0,
      1,  0,   0,   0,  6.12323e-17,  0,  0,  0,
     -1, -0,  -0,  -0, -6.12323e-17, -0, -0, -0;
  // clang-format on

  for (int i = 0; i < mat.rows(); ++i) {
    for (int j = 0; j < mat.cols(); ++j) {
      EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-6);
    }
  }

  Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(4, 1);
  ref_boundary << -1.0, -1.0, -2.0, -2.0;

  for (int i = 0; i < ref_boundary.rows(); ++i) {
    EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-5);
  }
}

// test add boundary with non-zero angle
TEST(Spline2dConstraint, add_boundary_02) {
  std::vector<double> x_knots = {0.0, 1.0};
  int32_t spline_order = 4;
  Spline2dConstraint constraint(x_knots, spline_order);

  std::vector<double> t_coord = {0.0};
  std::vector<double> angle = {0.2};
  std::vector<Vec2d> ref_point;
  ref_point.emplace_back(Vec2d(0.0, 0.0));
  std::vector<double> longitidinal_bound = {1.0};
  std::vector<double> lateral_bound = {2.0};

  constraint.Add2dBoundary(t_coord, angle, ref_point, longitidinal_bound,
                           lateral_bound);
  const auto mat = constraint.inequality_constraint().constraint_matrix();
  const auto boundary =
      constraint.inequality_constraint().constraint_boundary();

  // clang-format off
  Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 8);
  ref_mat <<
    -0.198669,    -0,    -0,    -0,  0.980067,     0,     0,     0,
     0.198669,     0,     0,     0, -0.980067,    -0,    -0,    -0,
     0.980067,     0,     0,     0,  0.198669,     0,     0,     0,
    -0.980067,    -0,    -0,    -0, -0.198669,    -0,    -0,    -0;
  // clang-format on

  for (int i = 0; i < mat.rows(); ++i) {
    for (int j = 0; j < mat.cols(); ++j) {
      EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-6);
    }
  }

  Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(4, 1);
  ref_boundary << -1.0, -1.0, -2.0, -2.0;

  for (int i = 0; i < ref_boundary.rows(); ++i) {
    EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-5);
  }
}

}  // namespace planning
}  // namespace apollo
<commit_msg>Planning: Added add boundary with multiple splines test for 2d spline<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/**
 * @file
 **/
#include "modules/planning/math/smoothing_spline/spline_2d_constraint.h"

#include "glog/logging.h"
#include "gtest/gtest.h"

namespace apollo {
namespace planning {

using apollo::common::math::Vec2d;

TEST(Spline2dConstraint, add_boundary_01) {
  std::vector<double> x_knots = {0.0, 1.0};
  int32_t spline_order = 4;
  Spline2dConstraint constraint(x_knots, spline_order);

  std::vector<double> t_coord = {0.0};
  std::vector<double> angle = {0.0};
  std::vector<Vec2d> ref_point;
  ref_point.emplace_back(Vec2d(0.0, 0.0));
  std::vector<double> longitidinal_bound = {1.0};
  std::vector<double> lateral_bound = {2.0};

  constraint.Add2dBoundary(t_coord, angle, ref_point, longitidinal_bound,
                           lateral_bound);
  const auto mat = constraint.inequality_constraint().constraint_matrix();
  const auto boundary =
      constraint.inequality_constraint().constraint_boundary();

  // clang-format off
  Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 8);
  ref_mat <<
     -0, -0,  -0,  -0,            1,  0,  0,  0,
      0,  0,   0,   0,           -1, -0, -0, -0,
      1,  0,   0,   0,  6.12323e-17,  0,  0,  0,
     -1, -0,  -0,  -0, -6.12323e-17, -0, -0, -0;
  // clang-format on

  for (int i = 0; i < mat.rows(); ++i) {
    for (int j = 0; j < mat.cols(); ++j) {
      EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-6);
    }
  }

  Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(4, 1);
  ref_boundary << -1.0, -1.0, -2.0, -2.0;

  for (int i = 0; i < ref_boundary.rows(); ++i) {
    EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-5);
  }
}

// test add boundary with non-zero angle
TEST(Spline2dConstraint, add_boundary_02) {
  std::vector<double> x_knots = {0.0, 1.0};
  int32_t spline_order = 4;
  Spline2dConstraint constraint(x_knots, spline_order);

  std::vector<double> t_coord = {0.0};
  std::vector<double> angle = {0.2};
  std::vector<Vec2d> ref_point;
  ref_point.emplace_back(Vec2d(0.0, 0.0));
  std::vector<double> longitidinal_bound = {1.0};
  std::vector<double> lateral_bound = {2.0};

  constraint.Add2dBoundary(t_coord, angle, ref_point, longitidinal_bound,
                           lateral_bound);
  const auto mat = constraint.inequality_constraint().constraint_matrix();
  const auto boundary =
      constraint.inequality_constraint().constraint_boundary();

  // clang-format off
  Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 8);
  ref_mat <<
    -0.198669,    -0,    -0,    -0,  0.980067,     0,     0,     0,
     0.198669,     0,     0,     0, -0.980067,    -0,    -0,    -0,
     0.980067,     0,     0,     0,  0.198669,     0,     0,     0,
    -0.980067,    -0,    -0,    -0, -0.198669,    -0,    -0,    -0;
  // clang-format on

  for (int i = 0; i < mat.rows(); ++i) {
    for (int j = 0; j < mat.cols(); ++j) {
      EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-6);
    }
  }

  Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(4, 1);
  ref_boundary << -1.0, -1.0, -2.0, -2.0;

  for (int i = 0; i < ref_boundary.rows(); ++i) {
    EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-5);
  }
}

// test add boundary with multiple splines
TEST(Spline2dConstraint, add_boundary_03) {
  std::vector<double> x_knots = {0.0, 1.0, 2.0};
  int32_t spline_order = 4;
  Spline2dConstraint constraint(x_knots, spline_order);

  std::vector<double> t_coord = {1.0};
  std::vector<double> angle = {0.2};
  std::vector<Vec2d> ref_point;
  ref_point.emplace_back(Vec2d(0.0, 0.0));
  std::vector<double> longitidinal_bound = {1.0};
  std::vector<double> lateral_bound = {2.0};

  constraint.Add2dBoundary(t_coord, angle, ref_point, longitidinal_bound,
                           lateral_bound);
  const auto mat = constraint.inequality_constraint().constraint_matrix();
  const auto boundary =
      constraint.inequality_constraint().constraint_boundary();

  // clang-format off
  Eigen::MatrixXd ref_mat = Eigen::MatrixXd::Zero(4, 16);
  ref_mat <<
        0,         0,         0,         0,         0,         0,         0,         0, -0.198669,        -0,        -0,        -0,  0.980067,         0,         0,         0, // NOLINT
        0,         0,         0,         0,         0,         0,         0,         0,  0.198669,         0,         0,         0, -0.980067,        -0,        -0,        -0, // NOLINT
        0,         0,         0,         0,         0,         0,         0,         0,  0.980067,         0,         0,         0,  0.198669,         0,         0,         0, // NOLINT
        0,         0,         0,         0,         0,         0,         0,         0, -0.980067,        -0,        -0,        -0, -0.198669,        -0,        -0,        -0; // NOLINT
  // clang-format on

  for (int i = 0; i < mat.rows(); ++i) {
    for (int j = 0; j < mat.cols(); ++j) {
      EXPECT_NEAR(mat(i, j), ref_mat(i, j), 1e-6);
    }
  }

  Eigen::MatrixXd ref_boundary = Eigen::MatrixXd::Zero(4, 1);
  ref_boundary << -1.0, -1.0, -2.0, -2.0;

  for (int i = 0; i < ref_boundary.rows(); ++i) {
    EXPECT_NEAR(boundary(i, 0), ref_boundary(i, 0), 1e-5);
  }
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective icvers.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/

#ifndef __OPENCV_FAST_NLMEANS_DENOISING_INVOKER_HPP__
#define __OPENCV_FAST_NLMEANS_DENOISING_INVOKER_HPP__

#include "precomp.hpp"
#include <limits>

#include "fast_nlmeans_denoising_invoker_commons.hpp"
#include "arrays.hpp"

using namespace cv;

template <typename T, typename IT, typename UIT, typename D, typename WT>
struct FastNlMeansDenoisingInvoker :
        public ParallelLoopBody
{
public:
    FastNlMeansDenoisingInvoker(const Mat& src, Mat& dst,
        int template_window_size, int search_window_size, const float *h);

    void operator() (const Range& range) const;

private:
    void operator= (const FastNlMeansDenoisingInvoker&);

    const Mat& src_;
    Mat& dst_;

    Mat extended_src_;
    int border_size_;

    int template_window_size_;
    int search_window_size_;

    int template_window_half_size_;
    int search_window_half_size_;

    typename pixelInfo<WT>::sampleType fixed_point_mult_;
    int almost_template_window_size_sq_bin_shift_;
    std::vector<WT> almost_dist2weight_;

    void calcDistSumsForFirstElementInRow(
        int i, Array2d<int>& dist_sums,
        Array3d<int>& col_dist_sums,
        Array3d<int>& up_col_dist_sums) const;

    void calcDistSumsForElementInFirstRow(
        int i, int j, int first_col_num,
        Array2d<int>& dist_sums,
        Array3d<int>& col_dist_sums,
        Array3d<int>& up_col_dist_sums) const;
};

inline int getNearestPowerOf2(int value)
{
    int p = 0;
    while( 1 << p < value)
        ++p;
    return p;
}

template <typename T, typename IT, typename UIT, typename D, typename WT>
FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::FastNlMeansDenoisingInvoker(
    const Mat& src, Mat& dst,
    int template_window_size,
    int search_window_size,
    const float *h) :
    src_(src), dst_(dst)
{
    CV_Assert(src.channels() == pixelInfo<T>::channels);

    template_window_half_size_ = template_window_size / 2;
    search_window_half_size_   = search_window_size   / 2;
    template_window_size_      = template_window_half_size_ * 2 + 1;
    search_window_size_        = search_window_half_size_   * 2 + 1;

    border_size_ = search_window_half_size_ + template_window_half_size_;
    copyMakeBorder(src_, extended_src_, border_size_, border_size_, border_size_, border_size_, BORDER_DEFAULT);

    const IT max_estimate_sum_value =
        (IT)search_window_size_ * (IT)search_window_size_ * (IT)pixelInfo<T>::sampleMax();
    fixed_point_mult_ = (int)std::min<IT>(std::numeric_limits<IT>::max() / max_estimate_sum_value,
                                          pixelInfo<WT>::sampleMax());

    // precalc weight for every possible l2 dist between blocks
    // additional optimization of precalced weights to replace division(averaging) by binary shift
    CV_Assert(template_window_size_ <= 46340); // sqrt(INT_MAX)
    int template_window_size_sq = template_window_size_ * template_window_size_;
    almost_template_window_size_sq_bin_shift_ = getNearestPowerOf2(template_window_size_sq);
    double almost_dist2actual_dist_multiplier = ((double)(1 << almost_template_window_size_sq_bin_shift_)) / template_window_size_sq;

    int max_dist = D::template maxDist<T>();
    int almost_max_dist = (int)(max_dist / almost_dist2actual_dist_multiplier + 1);
    almost_dist2weight_.resize(almost_max_dist);

    for (int almost_dist = 0; almost_dist < almost_max_dist; almost_dist++)
    {
        double dist = almost_dist * almost_dist2actual_dist_multiplier;
        almost_dist2weight_[almost_dist] =
            D::template calcWeight<T, WT>(dist, h, fixed_point_mult_);
    }

    // additional optimization init end
    if (dst_.empty())
        dst_ = Mat::zeros(src_.size(), src_.type());
}

template <typename T, typename IT, typename UIT, typename D, typename WT>
void FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::operator() (const Range& range) const
{
    int row_from = range.start;
    int row_to = range.end - 1;

    // sums of cols anf rows for current pixel p
    Array2d<int> dist_sums(search_window_size_, search_window_size_);

    // for lazy calc optimization (sum of cols for current pixel)
    Array3d<int> col_dist_sums(template_window_size_, search_window_size_, search_window_size_);

    int first_col_num = -1;
    // last elements of column sum (for each element in row)
    Array3d<int> up_col_dist_sums(src_.cols, search_window_size_, search_window_size_);

    for (int i = row_from; i <= row_to; i++)
    {
        for (int j = 0; j < src_.cols; j++)
        {
            int search_window_y = i - search_window_half_size_;
            int search_window_x = j - search_window_half_size_;

            // calc dist_sums
            if (j == 0)
            {
                calcDistSumsForFirstElementInRow(i, dist_sums, col_dist_sums, up_col_dist_sums);
                first_col_num = 0;
            }
            else
            {
                // calc cur dist_sums using previous dist_sums
                if (i == row_from)
                {
                    calcDistSumsForElementInFirstRow(i, j, first_col_num,
                        dist_sums, col_dist_sums, up_col_dist_sums);
                }
                else
                {
                    int ay = border_size_ + i;
                    int ax = border_size_ + j + template_window_half_size_;

                    int start_by = border_size_ + i - search_window_half_size_;
                    int start_bx = border_size_ + j - search_window_half_size_ + template_window_half_size_;

                    T a_up = extended_src_.at<T>(ay - template_window_half_size_ - 1, ax);
                    T a_down = extended_src_.at<T>(ay + template_window_half_size_, ax);

                    // copy class member to local variable for optimization
                    int search_window_size = search_window_size_;

                    for (int y = 0; y < search_window_size; y++)
                    {
                        int * dist_sums_row = dist_sums.row_ptr(y);
                        int * col_dist_sums_row = col_dist_sums.row_ptr(first_col_num, y);
                        int * up_col_dist_sums_row = up_col_dist_sums.row_ptr(j, y);

                        const T * b_up_ptr = extended_src_.ptr<T>(start_by - template_window_half_size_ - 1 + y);
                        const T * b_down_ptr = extended_src_.ptr<T>(start_by + template_window_half_size_ + y);

                        for (int x = 0; x < search_window_size; x++)
                        {
                            // remove from current pixel sum column sum with index "first_col_num"
                            dist_sums_row[x] -= col_dist_sums_row[x];

                            int bx = start_bx + x;
                            col_dist_sums_row[x] = up_col_dist_sums_row[x] + D::template calcUpDownDist<T>(a_up, a_down, b_up_ptr[bx], b_down_ptr[bx]);

                            dist_sums_row[x] += col_dist_sums_row[x];
                            up_col_dist_sums_row[x] = col_dist_sums_row[x];
                        }
                    }
                }

                first_col_num = (first_col_num + 1) % template_window_size_;
            }

            // calc weights
            IT estimation[pixelInfo<T>::channels], weights_sum[pixelInfo<WT>::channels];
            for (int channel_num = 0; channel_num < pixelInfo<T>::channels; channel_num++)
                estimation[channel_num] = 0;
            for (int channel_num = 0; channel_num < pixelInfo<WT>::channels; channel_num++)
                weights_sum[channel_num] = 0;

            for (int y = 0; y < search_window_size_; y++)
            {
                const T* cur_row_ptr = extended_src_.ptr<T>(border_size_ + search_window_y + y);
                int* dist_sums_row = dist_sums.row_ptr(y);
                for (int x = 0; x < search_window_size_; x++)
                {
                    int almostAvgDist = dist_sums_row[x] >> almost_template_window_size_sq_bin_shift_;
                    WT weight = almost_dist2weight_[almostAvgDist];
                    T p = cur_row_ptr[border_size_ + search_window_x + x];
                    incWithWeight<T, IT, WT>(estimation, weights_sum, weight, p);
                }
            }

            divByWeightsSum<IT, UIT, pixelInfo<T>::channels, pixelInfo<WT>::channels>(estimation,
                                                                                weights_sum);
            dst_.at<T>(i,j) = saturateCastFromArray<T, IT>(estimation);
        }
    }
}

template <typename T, typename IT, typename UIT, typename D, typename WT>
inline void FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::calcDistSumsForFirstElementInRow(
    int i,
    Array2d<int>& dist_sums,
    Array3d<int>& col_dist_sums,
    Array3d<int>& up_col_dist_sums) const
{
    int j = 0;

    for (int y = 0; y < search_window_size_; y++)
        for (int x = 0; x < search_window_size_; x++)
        {
            dist_sums[y][x] = 0;
            for (int tx = 0; tx < template_window_size_; tx++)
                col_dist_sums[tx][y][x] = 0;

            int start_y = i + y - search_window_half_size_;
            int start_x = j + x - search_window_half_size_;

            for (int ty = -template_window_half_size_; ty <= template_window_half_size_; ty++)
                for (int tx = -template_window_half_size_; tx <= template_window_half_size_; tx++)
                {
                    int dist = D::template calcDist<T>(extended_src_,
                        border_size_ + i + ty, border_size_ + j + tx,
                        border_size_ + start_y + ty, border_size_ + start_x + tx);

                    dist_sums[y][x] += dist;
                    col_dist_sums[tx + template_window_half_size_][y][x] += dist;
                }

            up_col_dist_sums[j][y][x] = col_dist_sums[template_window_size_ - 1][y][x];
        }
}

template <typename T, typename IT, typename UIT, typename D, typename WT>
inline void FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::calcDistSumsForElementInFirstRow(
    int i, int j, int first_col_num,
    Array2d<int>& dist_sums,
    Array3d<int>& col_dist_sums,
    Array3d<int>& up_col_dist_sums) const
{
    int ay = border_size_ + i;
    int ax = border_size_ + j + template_window_half_size_;

    int start_by = border_size_ + i - search_window_half_size_;
    int start_bx = border_size_ + j - search_window_half_size_ + template_window_half_size_;

    int new_last_col_num = first_col_num;

    for (int y = 0; y < search_window_size_; y++)
        for (int x = 0; x < search_window_size_; x++)
        {
            dist_sums[y][x] -= col_dist_sums[first_col_num][y][x];

            col_dist_sums[new_last_col_num][y][x] = 0;
            int by = start_by + y;
            int bx = start_bx + x;
            for (int ty = -template_window_half_size_; ty <= template_window_half_size_; ty++)
                col_dist_sums[new_last_col_num][y][x] += D::template calcDist<T>(extended_src_, ay + ty, ax, by + ty, bx);

            dist_sums[y][x] += col_dist_sums[new_last_col_num][y][x];
            up_col_dist_sums[j][y][x] = col_dist_sums[new_last_col_num][y][x];
        }
}

#endif
<commit_msg>photo: crash workaround for MSVC 2015 32-bit<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                        Intel License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective icvers.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of Intel Corporation may not 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 Intel Corporation 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.
//
//M*/

#ifndef __OPENCV_FAST_NLMEANS_DENOISING_INVOKER_HPP__
#define __OPENCV_FAST_NLMEANS_DENOISING_INVOKER_HPP__

#include "precomp.hpp"
#include <limits>

#include "fast_nlmeans_denoising_invoker_commons.hpp"
#include "arrays.hpp"

using namespace cv;

template <typename T, typename IT, typename UIT, typename D, typename WT>
struct FastNlMeansDenoisingInvoker :
        public ParallelLoopBody
{
public:
    FastNlMeansDenoisingInvoker(const Mat& src, Mat& dst,
        int template_window_size, int search_window_size, const float *h);

    void operator() (const Range& range) const;

private:
    void operator= (const FastNlMeansDenoisingInvoker&);

    const Mat& src_;
    Mat& dst_;

    Mat extended_src_;
    int border_size_;

    int template_window_size_;
    int search_window_size_;

    int template_window_half_size_;
    int search_window_half_size_;

    typename pixelInfo<WT>::sampleType fixed_point_mult_;
    int almost_template_window_size_sq_bin_shift_;
    std::vector<WT> almost_dist2weight_;

    void calcDistSumsForFirstElementInRow(
        int i, Array2d<int>& dist_sums,
        Array3d<int>& col_dist_sums,
        Array3d<int>& up_col_dist_sums) const;

    void calcDistSumsForElementInFirstRow(
        int i, int j, int first_col_num,
        Array2d<int>& dist_sums,
        Array3d<int>& col_dist_sums,
        Array3d<int>& up_col_dist_sums) const;
};

inline int getNearestPowerOf2(int value)
{
    int p = 0;
    while( 1 << p < value)
        ++p;
    return p;
}

template <typename T, typename IT, typename UIT, typename D, typename WT>
FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::FastNlMeansDenoisingInvoker(
    const Mat& src, Mat& dst,
    int template_window_size,
    int search_window_size,
    const float *h) :
    src_(src), dst_(dst)
{
    CV_Assert(src.channels() == pixelInfo<T>::channels);

    template_window_half_size_ = template_window_size / 2;
    search_window_half_size_   = search_window_size   / 2;
    template_window_size_      = template_window_half_size_ * 2 + 1;
    search_window_size_        = search_window_half_size_   * 2 + 1;

    border_size_ = search_window_half_size_ + template_window_half_size_;
    copyMakeBorder(src_, extended_src_, border_size_, border_size_, border_size_, border_size_, BORDER_DEFAULT);

    const IT max_estimate_sum_value =
        (IT)search_window_size_ * (IT)search_window_size_ * (IT)pixelInfo<T>::sampleMax();
    fixed_point_mult_ = (int)std::min<IT>(std::numeric_limits<IT>::max() / max_estimate_sum_value,
                                          pixelInfo<WT>::sampleMax());

    // precalc weight for every possible l2 dist between blocks
    // additional optimization of precalced weights to replace division(averaging) by binary shift
    CV_Assert(template_window_size_ <= 46340); // sqrt(INT_MAX)
    int template_window_size_sq = template_window_size_ * template_window_size_;
    almost_template_window_size_sq_bin_shift_ = getNearestPowerOf2(template_window_size_sq);
    double almost_dist2actual_dist_multiplier = ((double)(1 << almost_template_window_size_sq_bin_shift_)) / template_window_size_sq;

    int max_dist = D::template maxDist<T>();
    int almost_max_dist = (int)(max_dist / almost_dist2actual_dist_multiplier + 1);
    almost_dist2weight_.resize(almost_max_dist);

    for (int almost_dist = 0; almost_dist < almost_max_dist; almost_dist++)
    {
        double dist = almost_dist * almost_dist2actual_dist_multiplier;
        almost_dist2weight_[almost_dist] =
            D::template calcWeight<T, WT>(dist, h, fixed_point_mult_);
    }

    // additional optimization init end
    if (dst_.empty())
        dst_ = Mat::zeros(src_.size(), src_.type());
}

template <typename T, typename IT, typename UIT, typename D, typename WT>
void FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::operator() (const Range& range) const
{
    int row_from = range.start;
    int row_to = range.end - 1;

    // sums of cols anf rows for current pixel p
    Array2d<int> dist_sums(search_window_size_, search_window_size_);

    // for lazy calc optimization (sum of cols for current pixel)
    Array3d<int> col_dist_sums(template_window_size_, search_window_size_, search_window_size_);

    int first_col_num = -1;
    // last elements of column sum (for each element in row)
    Array3d<int> up_col_dist_sums(src_.cols, search_window_size_, search_window_size_);

    for (int i = row_from; i <= row_to; i++)
    {
        for (int j = 0; j < src_.cols; j++)
        {
            int search_window_y = i - search_window_half_size_;
            int search_window_x = j - search_window_half_size_;

            // calc dist_sums
            if (j == 0)
            {
                calcDistSumsForFirstElementInRow(i, dist_sums, col_dist_sums, up_col_dist_sums);
                first_col_num = 0;
            }
            else
            {
                // calc cur dist_sums using previous dist_sums
                if (i == row_from)
                {
                    calcDistSumsForElementInFirstRow(i, j, first_col_num,
                        dist_sums, col_dist_sums, up_col_dist_sums);
                }
                else
                {
                    int ay = border_size_ + i;
                    int ax = border_size_ + j + template_window_half_size_;

                    int start_by = border_size_ + i - search_window_half_size_;
                    int start_bx = border_size_ + j - search_window_half_size_ + template_window_half_size_;

                    T a_up = extended_src_.at<T>(ay - template_window_half_size_ - 1, ax);
                    T a_down = extended_src_.at<T>(ay + template_window_half_size_, ax);

                    // copy class member to local variable for optimization
                    int search_window_size = search_window_size_;

                    for (int y = 0; y < search_window_size; y++)
                    {
                        int * dist_sums_row = dist_sums.row_ptr(y);
                        int * col_dist_sums_row = col_dist_sums.row_ptr(first_col_num, y);
                        int * up_col_dist_sums_row = up_col_dist_sums.row_ptr(j, y);

                        const T * b_up_ptr = extended_src_.ptr<T>(start_by - template_window_half_size_ - 1 + y);
                        const T * b_down_ptr = extended_src_.ptr<T>(start_by + template_window_half_size_ + y);

// MSVC 2015 generates unaligned destination for "movaps" instruction for 32-bit builds
#if defined _MSC_VER && _MSC_VER == 1900 && !defined _WIN64
#pragma loop(no_vector)
#endif
                        for (int x = 0; x < search_window_size; x++)
                        {
                            // remove from current pixel sum column sum with index "first_col_num"
                            dist_sums_row[x] -= col_dist_sums_row[x];

                            int bx = start_bx + x;
                            col_dist_sums_row[x] = up_col_dist_sums_row[x] + D::template calcUpDownDist<T>(a_up, a_down, b_up_ptr[bx], b_down_ptr[bx]);

                            dist_sums_row[x] += col_dist_sums_row[x];
                            up_col_dist_sums_row[x] = col_dist_sums_row[x];
                        }
                    }
                }

                first_col_num = (first_col_num + 1) % template_window_size_;
            }

            // calc weights
            IT estimation[pixelInfo<T>::channels], weights_sum[pixelInfo<WT>::channels];
            for (int channel_num = 0; channel_num < pixelInfo<T>::channels; channel_num++)
                estimation[channel_num] = 0;
            for (int channel_num = 0; channel_num < pixelInfo<WT>::channels; channel_num++)
                weights_sum[channel_num] = 0;

            for (int y = 0; y < search_window_size_; y++)
            {
                const T* cur_row_ptr = extended_src_.ptr<T>(border_size_ + search_window_y + y);
                int* dist_sums_row = dist_sums.row_ptr(y);
                for (int x = 0; x < search_window_size_; x++)
                {
                    int almostAvgDist = dist_sums_row[x] >> almost_template_window_size_sq_bin_shift_;
                    WT weight = almost_dist2weight_[almostAvgDist];
                    T p = cur_row_ptr[border_size_ + search_window_x + x];
                    incWithWeight<T, IT, WT>(estimation, weights_sum, weight, p);
                }
            }

            divByWeightsSum<IT, UIT, pixelInfo<T>::channels, pixelInfo<WT>::channels>(estimation,
                                                                                weights_sum);
            dst_.at<T>(i,j) = saturateCastFromArray<T, IT>(estimation);
        }
    }
}

template <typename T, typename IT, typename UIT, typename D, typename WT>
inline void FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::calcDistSumsForFirstElementInRow(
    int i,
    Array2d<int>& dist_sums,
    Array3d<int>& col_dist_sums,
    Array3d<int>& up_col_dist_sums) const
{
    int j = 0;

    for (int y = 0; y < search_window_size_; y++)
        for (int x = 0; x < search_window_size_; x++)
        {
            dist_sums[y][x] = 0;
            for (int tx = 0; tx < template_window_size_; tx++)
                col_dist_sums[tx][y][x] = 0;

            int start_y = i + y - search_window_half_size_;
            int start_x = j + x - search_window_half_size_;

            for (int ty = -template_window_half_size_; ty <= template_window_half_size_; ty++)
                for (int tx = -template_window_half_size_; tx <= template_window_half_size_; tx++)
                {
                    int dist = D::template calcDist<T>(extended_src_,
                        border_size_ + i + ty, border_size_ + j + tx,
                        border_size_ + start_y + ty, border_size_ + start_x + tx);

                    dist_sums[y][x] += dist;
                    col_dist_sums[tx + template_window_half_size_][y][x] += dist;
                }

            up_col_dist_sums[j][y][x] = col_dist_sums[template_window_size_ - 1][y][x];
        }
}

template <typename T, typename IT, typename UIT, typename D, typename WT>
inline void FastNlMeansDenoisingInvoker<T, IT, UIT, D, WT>::calcDistSumsForElementInFirstRow(
    int i, int j, int first_col_num,
    Array2d<int>& dist_sums,
    Array3d<int>& col_dist_sums,
    Array3d<int>& up_col_dist_sums) const
{
    int ay = border_size_ + i;
    int ax = border_size_ + j + template_window_half_size_;

    int start_by = border_size_ + i - search_window_half_size_;
    int start_bx = border_size_ + j - search_window_half_size_ + template_window_half_size_;

    int new_last_col_num = first_col_num;

    for (int y = 0; y < search_window_size_; y++)
        for (int x = 0; x < search_window_size_; x++)
        {
            dist_sums[y][x] -= col_dist_sums[first_col_num][y][x];

            col_dist_sums[new_last_col_num][y][x] = 0;
            int by = start_by + y;
            int bx = start_bx + x;
            for (int ty = -template_window_half_size_; ty <= template_window_half_size_; ty++)
                col_dist_sums[new_last_col_num][y][x] += D::template calcDist<T>(extended_src_, ay + ty, ax, by + ty, bx);

            dist_sums[y][x] += col_dist_sums[new_last_col_num][y][x];
            up_col_dist_sums[j][y][x] = col_dist_sums[new_last_col_num][y][x];
        }
}

#endif
<|endoftext|>


<commit_before>#include "Processor.h"
#include "Config.h"
#include "Controller.h"
#include "SpeedyController.h"
#include "Memory.h"
#include "DRAM.h"
#include "Statistics.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdlib.h>
#include <functional>
#include <map>

/* Standards */
#include "Gem5Wrapper.h"
#include "DDR3.h"
#include "DDR4.h"
#include "DSARP.h"
#include "GDDR5.h"
#include "LPDDR3.h"
#include "LPDDR4.h"
#include "WideIO.h"
#include "WideIO2.h"
#include "HBM.h"
#include "SALP.h"
#include "ALDRAM.h"
#include "TLDRAM.h"

using namespace std;
using namespace ramulator;

template<typename T>
void run_dramtrace(const Config& configs, Memory<T, Controller>& memory, const char* tracename) {

    /* initialize DRAM trace */
    Trace trace(tracename);

    /* run simulation */
    bool stall = false, end = false;
    int reads = 0, writes = 0, clks = 0;
    long addr = 0;
    Request::Type type = Request::Type::READ;
    map<int, int> latencies;
    auto read_complete = [&latencies](Request& r){latencies[r.depart - r.arrive]++;};

    Request req(addr, type, read_complete);

    while (!end || memory.pending_requests()){
        if (!end && !stall){
            end = !trace.get_request(addr, type);
        }

        if (!end){
            req.addr = addr;
            req.type = type;
            stall = !memory.send(req);
            if (!stall){
                if (type == Request::Type::READ) reads++;
                else if (type == Request::Type::WRITE) writes++;
            }
        }
        memory.tick();
        clks ++;
        Stats::curTick++; // memory clock, global, for Statistics
    }
    // This a workaround for statistics set only initially lost in the end
    memory.finish();
    Stats::statlist.printall();

}

template <typename T>
void run_cputrace(const Config& configs, Memory<T, Controller>& memory, const char * file)
{
    int cpu_tick = configs.get_cpu_tick();
    int mem_tick = configs.get_mem_tick();
    auto send = bind(&Memory<T, Controller>::send, &memory, placeholders::_1);
    Processor proc(configs, file, send);
    for (long i = 0; ; i++) {
        proc.tick();
        Stats::curTick++; // processor clock, global, for Statistics
        if (i % cpu_tick == (cpu_tick - 1))
            for (int j = 0; j < mem_tick; j++)
                memory.tick();
      if (configs.is_early_exit()) {
        if (proc.finished())
            break;
      } else {
        if (proc.finished() && (memory.pending_requests() == 0))
            break;
      }
    }
    // This a workaround for statistics set only initially lost in the end
    memory.finish();
    Stats::statlist.printall();
}

template<typename T>
void start_run(const Config& configs, T* spec, const char* file) {
  // initiate controller and memory
  int C = configs.get_channels(), R = configs.get_ranks();
  // Check and Set channel, rank number
  spec->set_channel_number(C);
  spec->set_rank_number(R);
  std::vector<Controller<T>*> ctrls;
  for (int c = 0 ; c < C ; c++) {
    DRAM<T>* channel = new DRAM<T>(spec, T::Level::Channel);
    channel->id = c;
    channel->regStats("");
    Controller<T>* ctrl = new Controller<T>(configs, channel);
    ctrls.push_back(ctrl);
  }
  Memory<T, Controller> memory(configs, ctrls);

  if (configs["trace_type"] == "CPU") {
    run_cputrace(configs, memory, file);
  } else if (configs["trace_type"] == "DRAM") {
    run_dramtrace(configs, memory, file);
  }
}

int main(int argc, const char *argv[])
{
    if (argc < 2) {
        printf("Usage: %s <configs-file> --mode=cpu,dram [--stats <filename>] <trace-filename>\n"
            "Example: %s ramulator-configs.cfg cpu.trace\n", argv[0], argv[0]);
        return 0;
    }

    Config configs(argv[1]);

    const std::string& standard = configs["standard"];
    assert(standard != "" || "DRAM standard should be specified.");

    char *trace_type = strstr(argv[2], "=");
    trace_type++;
    if (strcmp(trace_type, "cpu") == 0) {
      configs.add("trace_type", "CPU");
    } else if (strcmp(trace_type, "mem") == 0) {
      configs.add("trace_type", "DRAM");
    } else {
      printf("invalid trace type: %s\n", trace_type);
      assert(false);
    }

    int trace_start = 3;
    string stats_out;
    if (strcmp(argv[3], "--stats") == 0) {
      Stats::statlist.output(argv[4]);
      stats_out = argv[4];
      trace_start = 5;
    } else {
      Stats::statlist.output(standard+".stats");
      stats_out = standard + string(".stats");
    }
    const char* file = argv[trace_start];

    if (standard == "DDR3") {
      DDR3* ddr3 = new DDR3(configs["org"], configs["speed"]);
      start_run(configs, ddr3, file);
    } else if (standard == "DDR4") {
      DDR4* ddr4 = new DDR4(configs["org"], configs["speed"]);
      start_run(configs, ddr4, file);
    } else if (standard == "SALP-MASA") {
      SALP* salp8 = new SALP(configs["org"], configs["speed"], "SALP-MASA", configs.get_subarrays());
      start_run(configs, salp8, file);
    } else if (standard == "LPDDR3") {
      LPDDR3* lpddr3 = new LPDDR3(configs["org"], configs["speed"]);
      start_run(configs, lpddr3, file);
    } else if (standard == "LPDDR4") {
      // total cap: 2GB, 1/2 of others
      LPDDR4* lpddr4 = new LPDDR4(configs["org"], configs["speed"]);
      start_run(configs, lpddr4, file);
    } else if (standard == "GDDR5") {
      GDDR5* gddr5 = new GDDR5(configs["org"], configs["speed"]);
      start_run(configs, gddr5, file);
    } else if (standard == "HBM") {
      HBM* hbm = new HBM(configs["org"], configs["speed"]);
      start_run(configs, hbm, file);
    } else if (standard == "WideIO") {
      // total cap: 1GB, 1/4 of others
      WideIO* wio = new WideIO(configs["org"], configs["speed"]);
      start_run(configs, wio, file);
    } else if (standard == "WideIO2") {
      // total cap: 2GB, 1/2 of others
      WideIO2* wio2 = new WideIO2(configs["org"], configs["speed"], configs.get_channels());
      wio2->channel_width *= 2;
      start_run(configs, wio2, file);
    }
    // Various refresh mechanisms
      else if (standard == "DSARP") {
      DSARP* dsddr3_dsarp = new DSARP(configs["org"], configs["speed"], DSARP::Type::DSARP, configs.get_subarrays());
      start_run(configs, dsddr3_dsarp, file);
    } else if (standard == "ALDRAM") {
      ALDRAM* aldram = new ALDRAM(configs["org"], configs["speed"]);
      start_run(configs, aldram, file);
    } else if (standard == "TLDRAM") {
      TLDRAM* tldram = new TLDRAM(configs["org"], configs["speed"], configs.get_subarrays());
      start_run(configs, tldram, file);
    }

    printf("Simulation done. Statistics written to %s\n", stats_out.c_str());

    return 0;
}
<commit_msg>Fix compile error when assign const char* to char*<commit_after>#include "Processor.h"
#include "Config.h"
#include "Controller.h"
#include "SpeedyController.h"
#include "Memory.h"
#include "DRAM.h"
#include "Statistics.h"
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <stdlib.h>
#include <functional>
#include <map>

/* Standards */
#include "Gem5Wrapper.h"
#include "DDR3.h"
#include "DDR4.h"
#include "DSARP.h"
#include "GDDR5.h"
#include "LPDDR3.h"
#include "LPDDR4.h"
#include "WideIO.h"
#include "WideIO2.h"
#include "HBM.h"
#include "SALP.h"
#include "ALDRAM.h"
#include "TLDRAM.h"

using namespace std;
using namespace ramulator;

template<typename T>
void run_dramtrace(const Config& configs, Memory<T, Controller>& memory, const char* tracename) {

    /* initialize DRAM trace */
    Trace trace(tracename);

    /* run simulation */
    bool stall = false, end = false;
    int reads = 0, writes = 0, clks = 0;
    long addr = 0;
    Request::Type type = Request::Type::READ;
    map<int, int> latencies;
    auto read_complete = [&latencies](Request& r){latencies[r.depart - r.arrive]++;};

    Request req(addr, type, read_complete);

    while (!end || memory.pending_requests()){
        if (!end && !stall){
            end = !trace.get_request(addr, type);
        }

        if (!end){
            req.addr = addr;
            req.type = type;
            stall = !memory.send(req);
            if (!stall){
                if (type == Request::Type::READ) reads++;
                else if (type == Request::Type::WRITE) writes++;
            }
        }
        memory.tick();
        clks ++;
        Stats::curTick++; // memory clock, global, for Statistics
    }
    // This a workaround for statistics set only initially lost in the end
    memory.finish();
    Stats::statlist.printall();

}

template <typename T>
void run_cputrace(const Config& configs, Memory<T, Controller>& memory, const char * file)
{
    int cpu_tick = configs.get_cpu_tick();
    int mem_tick = configs.get_mem_tick();
    auto send = bind(&Memory<T, Controller>::send, &memory, placeholders::_1);
    Processor proc(configs, file, send);
    for (long i = 0; ; i++) {
        proc.tick();
        Stats::curTick++; // processor clock, global, for Statistics
        if (i % cpu_tick == (cpu_tick - 1))
            for (int j = 0; j < mem_tick; j++)
                memory.tick();
      if (configs.is_early_exit()) {
        if (proc.finished())
            break;
      } else {
        if (proc.finished() && (memory.pending_requests() == 0))
            break;
      }
    }
    // This a workaround for statistics set only initially lost in the end
    memory.finish();
    Stats::statlist.printall();
}

template<typename T>
void start_run(const Config& configs, T* spec, const char* file) {
  // initiate controller and memory
  int C = configs.get_channels(), R = configs.get_ranks();
  // Check and Set channel, rank number
  spec->set_channel_number(C);
  spec->set_rank_number(R);
  std::vector<Controller<T>*> ctrls;
  for (int c = 0 ; c < C ; c++) {
    DRAM<T>* channel = new DRAM<T>(spec, T::Level::Channel);
    channel->id = c;
    channel->regStats("");
    Controller<T>* ctrl = new Controller<T>(configs, channel);
    ctrls.push_back(ctrl);
  }
  Memory<T, Controller> memory(configs, ctrls);

  if (configs["trace_type"] == "CPU") {
    run_cputrace(configs, memory, file);
  } else if (configs["trace_type"] == "DRAM") {
    run_dramtrace(configs, memory, file);
  }
}

int main(int argc, const char *argv[])
{
    if (argc < 2) {
        printf("Usage: %s <configs-file> --mode=cpu,dram [--stats <filename>] <trace-filename>\n"
            "Example: %s ramulator-configs.cfg cpu.trace\n", argv[0], argv[0]);
        return 0;
    }

    Config configs(argv[1]);

    const std::string& standard = configs["standard"];
    assert(standard != "" || "DRAM standard should be specified.");

    const char *trace_type = strstr(argv[2], "=");
    trace_type++;
    if (strcmp(trace_type, "cpu") == 0) {
      configs.add("trace_type", "CPU");
    } else if (strcmp(trace_type, "mem") == 0) {
      configs.add("trace_type", "DRAM");
    } else {
      printf("invalid trace type: %s\n", trace_type);
      assert(false);
    }

    int trace_start = 3;
    string stats_out;
    if (strcmp(argv[3], "--stats") == 0) {
      Stats::statlist.output(argv[4]);
      stats_out = argv[4];
      trace_start = 5;
    } else {
      Stats::statlist.output(standard+".stats");
      stats_out = standard + string(".stats");
    }
    const char* file = argv[trace_start];

    if (standard == "DDR3") {
      DDR3* ddr3 = new DDR3(configs["org"], configs["speed"]);
      start_run(configs, ddr3, file);
    } else if (standard == "DDR4") {
      DDR4* ddr4 = new DDR4(configs["org"], configs["speed"]);
      start_run(configs, ddr4, file);
    } else if (standard == "SALP-MASA") {
      SALP* salp8 = new SALP(configs["org"], configs["speed"], "SALP-MASA", configs.get_subarrays());
      start_run(configs, salp8, file);
    } else if (standard == "LPDDR3") {
      LPDDR3* lpddr3 = new LPDDR3(configs["org"], configs["speed"]);
      start_run(configs, lpddr3, file);
    } else if (standard == "LPDDR4") {
      // total cap: 2GB, 1/2 of others
      LPDDR4* lpddr4 = new LPDDR4(configs["org"], configs["speed"]);
      start_run(configs, lpddr4, file);
    } else if (standard == "GDDR5") {
      GDDR5* gddr5 = new GDDR5(configs["org"], configs["speed"]);
      start_run(configs, gddr5, file);
    } else if (standard == "HBM") {
      HBM* hbm = new HBM(configs["org"], configs["speed"]);
      start_run(configs, hbm, file);
    } else if (standard == "WideIO") {
      // total cap: 1GB, 1/4 of others
      WideIO* wio = new WideIO(configs["org"], configs["speed"]);
      start_run(configs, wio, file);
    } else if (standard == "WideIO2") {
      // total cap: 2GB, 1/2 of others
      WideIO2* wio2 = new WideIO2(configs["org"], configs["speed"], configs.get_channels());
      wio2->channel_width *= 2;
      start_run(configs, wio2, file);
    }
    // Various refresh mechanisms
      else if (standard == "DSARP") {
      DSARP* dsddr3_dsarp = new DSARP(configs["org"], configs["speed"], DSARP::Type::DSARP, configs.get_subarrays());
      start_run(configs, dsddr3_dsarp, file);
    } else if (standard == "ALDRAM") {
      ALDRAM* aldram = new ALDRAM(configs["org"], configs["speed"]);
      start_run(configs, aldram, file);
    } else if (standard == "TLDRAM") {
      TLDRAM* tldram = new TLDRAM(configs["org"], configs["speed"], configs.get_subarrays());
      start_run(configs, tldram, file);
    }

    printf("Simulation done. Statistics written to %s\n", stats_out.c_str());

    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <opencv2/opencv.hpp>

#include "DB.hpp"
#include "Image.hpp"
#include "Mosaic.hpp"

int main()
{
	// Setup directory and folder paths, no recursive solution yet
	string image_name = "zlatan_blue_background_1920x1080.jpg";

	// ----> Directory for: KRISTOFER <-----
	//string mainDirectory = "C:/Users/StoffesBok/Bilddatabaser_TNM025/dataset/";
	//cv::Mat image_temp = imread("C:/Users/StoffesBok/Bilddatabaser_TNM025/dataset/zlatan/zlatan_blue_background_1920x1080.jpg", 1);

	// ----> Directory for: GABRIEL <-----
	//string mainDirectory = "C:/Users/Gabriel/Desktop/Bildatabaser/Bilddatabaser_TNM025/dataset/";
	//cv::Mat image_temp = imread("C:/Users/Gabriel/Desktop/Bildatabaser/Bilddatabaser_TNM025/dataset/zlatan/" + image_name, 1);

	if (!image_temp.data){
		cout << "Zlatan is too big!" << endl; return -1;
	}

	vector<string> inputFolders = { "animal2", "beach2", "cat2", "colorful2",
								    "doll2", "elegant2", "flower2", "food2", "formal2", "garden2" };
	vector<string> animalFolder = { "animal2" };

	// Initilize the database
	DB database = DB();
	database.loadImages(mainDirectory, inputFolders);

	DB zlatan_DB = DB(image_temp, 32);
	zlatan_DB.reconstructImageFromDB(zlatan_DB, image_name);

	// A test for color histogram
	/*Mat src = imread("test.png", 1)
	cout << "Total: " << src.total() << endl;

	int r_bins = 2;
	int g_bins = 2;
	int b_bins = 2;
	const int hist_size[] = { r_bins, g_bins, b_bins };

	float r_range[] = { 0, 255 };
	float g_range[] = { 0, 255 };
	float b_range[] = { 0, 255 };
	const float *hist_range[] = { r_range, g_range, b_range };

	cv::Mat histos;

	bool uniform = true;
	bool accumulate = false;
	int channels[] = { 0, 1, 2 };
	// Check if channels and dims is correct
	calcHist(&src, 1, channels, Mat(), histos, 3, hist_size, hist_range, uniform, accumulate);

	//cout << "size" << histos.size[0] << endl;
	//cout << " x " << histos.size[1] << endl;
	//cout << " x " << histos.size[2] << endl;

	for (int i = 0; i < 2; i++)
	{
		for (int j = 0; j < 2; j++)
		{
			for (int k = 0; k < 2; k++)
			{
				cout << "B: " << i << endl;
				cout << "G: " << j << endl;
				cout << "R: " << k << endl;
				cout << histos.at<Vec3b>(i, j, k) << " " << endl;
			}
		}

	}
	*/

	system("pause");
	return 0;
}<commit_msg>Testing different histogram format<commit_after>#include <iostream>
#include <opencv2/opencv.hpp>

#include "DB.hpp"
#include "Image.hpp"
#include "Mosaic.hpp"

int main()
{
	// Setup directory and folder paths, no recursive solution yet
	string image_name = "zlatan_blue_background_1920x1080.jpg";

	// ----> Directory for: KRISTOFER <-----
	//string mainDirectory = "C:/Users/StoffesBok/Bilddatabaser_TNM025/dataset/";
	//cv::Mat image_temp = imread("C:/Users/StoffesBok/Bilddatabaser_TNM025/dataset/zlatan/zlatan_blue_background_1920x1080.jpg", 1);

	// ----> Directory for: GABRIEL <-----
	string mainDirectory = "C:/Users/Gabriel/Desktop/Bildatabaser/Bilddatabaser_TNM025/dataset/";
	cv::Mat image_temp = imread("C:/Users/Gabriel/Desktop/Bildatabaser/Bilddatabaser_TNM025/dataset/zlatan/" + image_name, 1);

	if (!image_temp.data){
		cout << "Zlatan is too big!" << endl; return -1;
	}

	//vector<string> inputFolders = { "animal2", "beach2", "cat2", "colorful2",
	//							    "doll2", "elegant2", "flower2", "food2", "formal2", "garden2" };
	//vector<string> animalFolder = { "animal2" };

	// Initilize the database
	//DB database = DB();
	//database.loadImages(mainDirectory, inputFolders);
	//
	//DB zlatan_DB = DB(image_temp, 32);
	//zlatan_DB.reconstructImageFromDB(zlatan_DB, image_name);

	// A test for color histogram
	Mat src = imread("test.png", 1);

	int r_bins = 4;
	int g_bins = 4;
	int b_bins = 4;
	const int hist_size[] = { r_bins, g_bins, b_bins };

	float r_range[] = { 0, 255 };
	float g_range[] = { 0, 255 };
	float b_range[] = { 0, 255 };
	const float *hist_range[] = { r_range, g_range, b_range };

	cv::Mat histos;
	histos.create(3, hist_size, CV_32F);
	bool uniform = true;
	bool accumulate = false;
	int channels[] = { 0, 1, 2 };
	// Check if channels and dims is correct
	calcHist(&src, 1, channels, Mat(), histos, 3, hist_size, hist_range, uniform, accumulate);

	//cout << "size" << histos.size[0] << endl;
	//cout << " x " << histos.size[1] << endl;
	//cout << " x " << histos.size[2] << endl;
	vector<Mat> histoVec;
	split(histos, histoVec);

	cout << histoVec[0].size();
	for (int i = 0; i < r_bins; i++)
	{
		for (int j = 0; j < g_bins; j++)
		{
			cout << histoVec[0].data[histoVec[0].channels()*histoVec[0].cols*i + j] << " ";
		}
	}
	//for (int i = 0; i < r_bins; i++)
	//{
	//	for (int j = 0; j < g_bins; j++)
	//	{
	//		for (int k = 0; k < b_bins; k++)
	//		{
	//			cout << histoVec[0].at<float>(i, j, k) << " ";
	//		}
	//	}
	//}

	system("pause");
	return 0;
}<|endoftext|>


<commit_before>#include "Note.h"
#include <math.h>

namespace rparser
{

const char *kNoteTypesStr[] = {
  "NONE",
  "NOTE",
  "TOUCH",
  "KNOB",
  "BGM",
  "BGA",
  "TEMPO",
  "SPECIAL",
};

const char *kNoteSubTypesStr[] = {
  "NORMAL",
  "INVISIBLE",
  "LONGNOTE",
  "CHARGE",
  "HCHARGE",
  "MINE",
  "AUTO",
  "FAKE",
  "COMBO",
  "DRAG",
  "CHAIN",
  "REPEAT",
};

const char *kNoteTempoTypesStr[] = {
  "BPM",
  "STOP",
  "WARP",
  "SCROLL",
  "MEASURE",
  "TICK",
  "BMSBPM",
  "BMSSTOP",
};

const char *kNoteBgaTypesStr[] = {
  "MAINBGA",
  "MISSBGA",
  "LAYER1",
  "LAYER2",
  "LAYER3",
  "LAYER4",
  "LAYER5",
  "LAYER6",
  "LAYER7",
  "LAYER8",
  "LAYER9",
  "LAYER10",
};

const char *kNoteSpecialTypesStr[] = {
  "REST",
  "BMSKEYBIND",
  "BMSEXTCHR",
  "BMSTEXT",
  "BMSOPTION",
  "BMSARGBBASE",
  "BMSARGBMISS",
  "BGAARGBLAYER1",
  "BGAARGBLAYER2",
};

const char **pNoteSubtypeStr[] = {
  kNoteSubTypesStr,
  kNoteTempoTypesStr,
  kNoteBgaTypesStr,
  kNoteSpecialTypesStr,
};

NotePos::NotePos()
  : type(NotePosTypes::NullPos), time_msec(0), beat(0), measure(0), denominator(8) {}

void NotePos::SetRowPos(uint32_t measure, RowPos deno, RowPos num)
{
  if (deno == 0) SetRowPos(measure);
  else SetRowPos(measure + (double)num / deno);
}

void NotePos::SetRowPos(double barpos)
{
  type = NotePosTypes::Bar;
  this->measure = barpos;
}

void NotePos::SetBeatPos(double beat)
{
  type = NotePosTypes::Beat;
  this->beat = beat;
}

void NotePos::SetTimePos(double time_msec)
{
  type = NotePosTypes::Time;
  this->time_msec = time_msec;
}

void NotePos::SetDenominator(uint32_t denominator)
{
  this->denominator = denominator;
}

std::string NotePos::toString() const
{
  std::stringstream ss;
  int32_t num = 0;
  switch (type)
  {
  case NotePosTypes::NullPos:
    ss << "(No note pos set)" << std::endl;
    break;
  case NotePosTypes::Beat:
    ss << "Beat: " << beat << "(Deno " << denominator << ")" << std::endl;
    break;
  case NotePosTypes::Time:
    ss << "Time: " << time_msec << "(Deno " << denominator << ")" << std::endl;
    break;
  case NotePosTypes::Bar:
    // recalculate numerator of Row
    num = static_cast<int32_t>(lround(measure * denominator) % denominator);
    ss << "Row: " << (static_cast<int32_t>(measure) % 1) << " " << num << "/" << denominator << std::endl;
    break;
  }
  return ss.str();
}

std::string Note::toString() const
{
  std::stringstream ss;
  std::string sType, sSubtype;
  sType = kNoteTypesStr[type_];
  sSubtype = pNoteSubtypeStr[type_][subtype_];
  ss << "[Object Note]\n";
  ss << "type/subtype: " << sType << "," << sSubtype << std::endl;
  ss << NotePos::toString();
  ss << getValueAsString();
  return ss.str();
}

NotePos& NotePos::pos()
{
  return *this;
}

const NotePos& NotePos::pos() const
{
  return const_cast<NotePos*>(this)->pos();
}

NotePosTypes NotePos::postype() const
{
  return type;
}

double NotePos::GetBeatPos() const
{
  return beat;
}

double NotePos::GetTimePos() const
{
  return time_msec;
}

bool NotePos::operator<(const NotePos &other) const noexcept
{
  return beat < other.beat;
}

bool NotePos::operator==(const NotePos &other) const noexcept
{
  return beat == other.beat;
}

#if 0
bool NotePos::operator==(const NotePos &other) const noexcept
{
  if (type != other.type) return false;
  switch (type)
  {
  case NotePosTypes::Beat:
    return beat == other.beat;
  case NotePosTypes::Time:
    return time_msec == other.time_msec;
  default:
    ASSERT(0);
    return false;
  }
}
#endif

Note::Note()
  : NotePos(), type_(0), subtype_(0), is_conditional_object_(0)
{ }

NoteType Note::type() const
{
  return type_;
}

NoteType Note::subtype() const
{
  return subtype_;
}

void Note::set_type(NoteType t)
{
  type_ = t;
}

void Note::set_subtype(NoteType t)
{
  subtype_ = t;
}

bool Note::operator==(const Note &other) const noexcept
{
  return NotePos::operator==(other) && type() == other.type() && subtype() == other.subtype();
}

SoundNote::SoundNote() : value(0), channel_type(0), effect{ 0, 0, 1.0f, false }
{
  SetAsBGM(0);
}

void SoundNote::SetAsBGM(uint8_t col)
{
  set_type(NoteTypes::kBGM);
  track.lane.note.player = 0;
  track.lane.note.lane = col;
}

void SoundNote::SetAsTouchNote()
{
  set_type(NoteTypes::kTouch);
}

void SoundNote::SetAsTapNote(uint8_t player, uint8_t lane)
{
  set_type(NoteTypes::kTap);
  set_subtype(NoteSubTypes::kNormalNote);
  track.lane.note.player = player;
  track.lane.note.lane = lane;
}

void SoundNote::SetAsChainNote()
{
  set_subtype(NoteSubTypes::kLongNote);
}

void SoundNote::SetMidiNote(float duration_ms, int32_t key, float volume)
{
  effect.duration_ms = duration_ms;
  effect.key = key;
  effect.volume = volume;
  channel_type = 1; // mark source as MIDI
}

void SoundNote::SetLongnoteLength(double delta_value)
{
  ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch);
  if (!IsLongnote())
    chains.emplace_back(NoteChain{ track, *this, 0 });
  switch (postype())
  {
  case NotePosTypes::Beat:
    chains.back().pos.SetBeatPos(pos().beat + delta_value);
    break;
  case NotePosTypes::Bar:
    chains.back().pos.SetRowPos(pos().measure + delta_value);
    break;
  case NotePosTypes::Time:
    chains.back().pos.SetTimePos(pos().time_msec + delta_value);
    break;
  }
}

void SoundNote::SetLongnoteEndPos(const NotePos& row_pos)
{
  ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch);
  if (!IsLongnote())
    chains.emplace_back(NoteChain{ track, *this, 0 });
  chains.back().pos = row_pos;
}

void SoundNote::SetLongnoteEndValue(Channel v)
{
  ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch);
  if (!IsLongnote())
    chains.emplace_back(NoteChain{ track, *this, 0 });
  chains.back().value = v;
}

void SoundNote::AddChain(const NotePos& pos, uint8_t col)
{
  ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch);
  NoteTrack track;
  track.lane.note.player = 0;
  track.lane.note.lane = col;
  chains.emplace_back(NoteChain{ track, pos, 0 });
}

void SoundNote::AddTouch(const NotePos& pos, uint8_t x, uint8_t y)
{
  ASSERT(type() == NoteTypes::kTouch);
  NoteTrack track;
  track.lane.touch.x = x;
  track.lane.touch.y = y;
  chains.emplace_back(NoteChain{ track, pos, 0 });
}

void SoundNote::ClearChain()
{
  chains.clear();
}

bool SoundNote::IsLongnote() const
{
  return chains.size() > 0;
}

bool SoundNote::IsScoreable() const
{
  return type() == NoteTypes::kTap || type() == NoteTypes::kTouch;
}

uint8_t SoundNote::GetPlayer() const
{
  return track.lane.note.player;
}

uint8_t SoundNote::GetLane() const
{
  return track.lane.note.lane;
}

uint8_t SoundNote::GetBGMCol() const
{
  return track.lane.note.lane;
}

uint8_t SoundNote::GetX() const
{
  return track.lane.touch.x;
}

uint8_t SoundNote::GetY() const
{
  return track.lane.touch.y;
}

NotePos& SoundNote::endpos()
{
  if (!IsLongnote()) return pos();
  else return chains.back().pos;
}

const NotePos& SoundNote::endpos() const
{
  return const_cast<SoundNote*>(this)->endpos();
}

std::string SoundNote::getValueAsString() const
{
  std::stringstream ss;
  ss << "Track (note - player, lane): " << track.lane.note.player << "," << track.lane.note.lane << std::endl;
  ss << "Track (touch - x, y): " << track.lane.touch.x << "," << track.lane.touch.y << std::endl;
  ss << "Volume: " << effect.volume << std::endl;
  ss << "Key (Pitch): " << effect.key << std::endl;
  ss << "Restart (sound) ?: " << effect.restart << std::endl;
  return ss.str();
}

bool SoundNote::operator==(const SoundNote &other) const noexcept
{
  return Note::operator==(other) && value == other.value;
}

std::string EventNote::getValueAsString() const
{
  std::stringstream ss;
  ss << "Command: " << command_;
  if (arg1_) ss << ", arg1: " << arg1_;
  if (arg2_) ss << ", arg2: " << arg2_;
  ss << std::endl;
  return ss.str();
}

EventNote::EventNote() : command_(0), arg1_(0), arg2_(0)
{
  set_type(NoteTypes::kEvent);
}

void EventNote::SetBga(BgaTypes bgatype, Channel channel, uint8_t column)
{
  set_subtype(NoteEventTypes::kBGA);
  command_ = bgatype;
  arg1_ = static_cast<decltype(arg1_)>(channel);
  arg2_ = column;
}

void EventNote::SetMidiCommand(uint8_t command, uint8_t arg1, uint8_t arg2)
{
  set_subtype(NoteEventTypes::kMIDI);
  command_ = command;
  arg1_ = arg1;
  arg2_ = arg2;
}

void EventNote::SetBmsARGBCommand(BgaTypes bgatype, Channel channel)
{
  set_subtype(NoteEventTypes::kBmsARGBLAYER);
  command_ = bgatype;
  arg1_ = static_cast<decltype(arg1_)>(channel);
  arg2_ = 0;
}

void EventNote::GetMidiCommand(uint8_t &command, uint8_t &arg1, uint8_t &arg2) const
{
  ASSERT(type() == NoteEventTypes::kMIDI);
  command = (uint8_t)command_;
  arg1 = (uint8_t)arg1_;
  arg2 = (uint8_t)arg2_;
}

bool EventNote::operator==(const EventNote &other) const noexcept
{
  return Note::operator==(other) &&
         command_ == other.command_ &&
         arg1_ == other.arg1_ &&
         arg2_ == other.arg2_;
}

TempoNote::TempoNote()
{
  set_type(NoteTypes::kTempo);
}

void TempoNote::SetBpm(float bpm)
{
  set_subtype(NoteTempoTypes::kBpm);
  value.f = bpm;
}

void TempoNote::SetBmsBpm(Channel bms_channel)
{
  set_subtype(NoteTempoTypes::kBmsBpm);
  value.i = bms_channel;
}

void TempoNote::SetStop(float stop)
{
  set_subtype(NoteTempoTypes::kStop);
  value.f = stop;
}

void TempoNote::SetBmsStop(Channel bms_channel)
{
  set_subtype(NoteTempoTypes::kBmsStop);
  value.i = bms_channel;
}

void TempoNote::SetMeasure(float measure_length)
{
  set_subtype(NoteTempoTypes::kMeasure);
  value.f = measure_length;
}

void TempoNote::SetScroll(float scrollspeed)
{
  set_subtype(NoteTempoTypes::kScroll);
  value.f = scrollspeed;
}

void TempoNote::SetTick(int32_t tick)
{
  set_subtype(NoteTempoTypes::kTick);
  value.i = tick;
}

void TempoNote::SetWarp(float warp_to)
{
  set_subtype(NoteTempoTypes::kWarp);
  value.f = warp_to;
}

float TempoNote::GetFloatValue() const
{
  return value.f;
}

int32_t TempoNote::GetIntValue() const
{
  return value.i;
}

std::string TempoNote::getValueAsString() const
{
  std::stringstream ss;
  ss << "Value (float): " << value.f << std::endl;
  ss << "Value (int): " << value.i << std::endl;
  return ss.str();
}

bool TempoNote::operator==(const TempoNote &other) const noexcept
{
  return Note::operator==(other) &&
         value.i == other.value.i &&
         value.f == other.value.f;
}

}
<commit_msg>Bugfix: GetMidiCommand() sigsegv when fetching midi object<commit_after>#include "Note.h"
#include <math.h>

namespace rparser
{

const char *kNoteTypesStr[] = {
  "NONE",
  "NOTE",
  "TOUCH",
  "KNOB",
  "BGM",
  "BGA",
  "TEMPO",
  "SPECIAL",
};

const char *kNoteSubTypesStr[] = {
  "NORMAL",
  "INVISIBLE",
  "LONGNOTE",
  "CHARGE",
  "HCHARGE",
  "MINE",
  "AUTO",
  "FAKE",
  "COMBO",
  "DRAG",
  "CHAIN",
  "REPEAT",
};

const char *kNoteTempoTypesStr[] = {
  "BPM",
  "STOP",
  "WARP",
  "SCROLL",
  "MEASURE",
  "TICK",
  "BMSBPM",
  "BMSSTOP",
};

const char *kNoteBgaTypesStr[] = {
  "MAINBGA",
  "MISSBGA",
  "LAYER1",
  "LAYER2",
  "LAYER3",
  "LAYER4",
  "LAYER5",
  "LAYER6",
  "LAYER7",
  "LAYER8",
  "LAYER9",
  "LAYER10",
};

const char *kNoteSpecialTypesStr[] = {
  "REST",
  "BMSKEYBIND",
  "BMSEXTCHR",
  "BMSTEXT",
  "BMSOPTION",
  "BMSARGBBASE",
  "BMSARGBMISS",
  "BGAARGBLAYER1",
  "BGAARGBLAYER2",
};

const char **pNoteSubtypeStr[] = {
  kNoteSubTypesStr,
  kNoteTempoTypesStr,
  kNoteBgaTypesStr,
  kNoteSpecialTypesStr,
};

NotePos::NotePos()
  : type(NotePosTypes::NullPos), time_msec(0), beat(0), measure(0), denominator(8) {}

void NotePos::SetRowPos(uint32_t measure, RowPos deno, RowPos num)
{
  if (deno == 0) SetRowPos(measure);
  else SetRowPos(measure + (double)num / deno);
}

void NotePos::SetRowPos(double barpos)
{
  type = NotePosTypes::Bar;
  this->measure = barpos;
}

void NotePos::SetBeatPos(double beat)
{
  type = NotePosTypes::Beat;
  this->beat = beat;
}

void NotePos::SetTimePos(double time_msec)
{
  type = NotePosTypes::Time;
  this->time_msec = time_msec;
}

void NotePos::SetDenominator(uint32_t denominator)
{
  this->denominator = denominator;
}

std::string NotePos::toString() const
{
  std::stringstream ss;
  int32_t num = 0;
  switch (type)
  {
  case NotePosTypes::NullPos:
    ss << "(No note pos set)" << std::endl;
    break;
  case NotePosTypes::Beat:
    ss << "Beat: " << beat << "(Deno " << denominator << ")" << std::endl;
    break;
  case NotePosTypes::Time:
    ss << "Time: " << time_msec << "(Deno " << denominator << ")" << std::endl;
    break;
  case NotePosTypes::Bar:
    // recalculate numerator of Row
    num = static_cast<int32_t>(lround(measure * denominator) % denominator);
    ss << "Row: " << (static_cast<int32_t>(measure) % 1) << " " << num << "/" << denominator << std::endl;
    break;
  }
  return ss.str();
}

std::string Note::toString() const
{
  std::stringstream ss;
  std::string sType, sSubtype;
  sType = kNoteTypesStr[type_];
  sSubtype = pNoteSubtypeStr[type_][subtype_];
  ss << "[Object Note]\n";
  ss << "type/subtype: " << sType << "," << sSubtype << std::endl;
  ss << NotePos::toString();
  ss << getValueAsString();
  return ss.str();
}

NotePos& NotePos::pos()
{
  return *this;
}

const NotePos& NotePos::pos() const
{
  return const_cast<NotePos*>(this)->pos();
}

NotePosTypes NotePos::postype() const
{
  return type;
}

double NotePos::GetBeatPos() const
{
  return beat;
}

double NotePos::GetTimePos() const
{
  return time_msec;
}

bool NotePos::operator<(const NotePos &other) const noexcept
{
  return beat < other.beat;
}

bool NotePos::operator==(const NotePos &other) const noexcept
{
  return beat == other.beat;
}

#if 0
bool NotePos::operator==(const NotePos &other) const noexcept
{
  if (type != other.type) return false;
  switch (type)
  {
  case NotePosTypes::Beat:
    return beat == other.beat;
  case NotePosTypes::Time:
    return time_msec == other.time_msec;
  default:
    ASSERT(0);
    return false;
  }
}
#endif

Note::Note()
  : NotePos(), type_(0), subtype_(0), is_conditional_object_(0)
{ }

NoteType Note::type() const
{
  return type_;
}

NoteType Note::subtype() const
{
  return subtype_;
}

void Note::set_type(NoteType t)
{
  type_ = t;
}

void Note::set_subtype(NoteType t)
{
  subtype_ = t;
}

bool Note::operator==(const Note &other) const noexcept
{
  return NotePos::operator==(other) && type() == other.type() && subtype() == other.subtype();
}

SoundNote::SoundNote() : value(0), channel_type(0), effect{ 0, 0, 1.0f, false }
{
  SetAsBGM(0);
}

void SoundNote::SetAsBGM(uint8_t col)
{
  set_type(NoteTypes::kBGM);
  track.lane.note.player = 0;
  track.lane.note.lane = col;
}

void SoundNote::SetAsTouchNote()
{
  set_type(NoteTypes::kTouch);
}

void SoundNote::SetAsTapNote(uint8_t player, uint8_t lane)
{
  set_type(NoteTypes::kTap);
  set_subtype(NoteSubTypes::kNormalNote);
  track.lane.note.player = player;
  track.lane.note.lane = lane;
}

void SoundNote::SetAsChainNote()
{
  set_subtype(NoteSubTypes::kLongNote);
}

void SoundNote::SetMidiNote(float duration_ms, int32_t key, float volume)
{
  effect.duration_ms = duration_ms;
  effect.key = key;
  effect.volume = volume;
  channel_type = 1; // mark source as MIDI
}

void SoundNote::SetLongnoteLength(double delta_value)
{
  ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch);
  if (!IsLongnote())
    chains.emplace_back(NoteChain{ track, *this, 0 });
  switch (postype())
  {
  case NotePosTypes::Beat:
    chains.back().pos.SetBeatPos(pos().beat + delta_value);
    break;
  case NotePosTypes::Bar:
    chains.back().pos.SetRowPos(pos().measure + delta_value);
    break;
  case NotePosTypes::Time:
    chains.back().pos.SetTimePos(pos().time_msec + delta_value);
    break;
  }
}

void SoundNote::SetLongnoteEndPos(const NotePos& row_pos)
{
  ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch);
  if (!IsLongnote())
    chains.emplace_back(NoteChain{ track, *this, 0 });
  chains.back().pos = row_pos;
}

void SoundNote::SetLongnoteEndValue(Channel v)
{
  ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch);
  if (!IsLongnote())
    chains.emplace_back(NoteChain{ track, *this, 0 });
  chains.back().value = v;
}

void SoundNote::AddChain(const NotePos& pos, uint8_t col)
{
  ASSERT(type() == NoteTypes::kTap || type() == NoteTypes::kTouch);
  NoteTrack track;
  track.lane.note.player = 0;
  track.lane.note.lane = col;
  chains.emplace_back(NoteChain{ track, pos, 0 });
}

void SoundNote::AddTouch(const NotePos& pos, uint8_t x, uint8_t y)
{
  ASSERT(type() == NoteTypes::kTouch);
  NoteTrack track;
  track.lane.touch.x = x;
  track.lane.touch.y = y;
  chains.emplace_back(NoteChain{ track, pos, 0 });
}

void SoundNote::ClearChain()
{
  chains.clear();
}

bool SoundNote::IsLongnote() const
{
  return chains.size() > 0;
}

bool SoundNote::IsScoreable() const
{
  return type() == NoteTypes::kTap || type() == NoteTypes::kTouch;
}

uint8_t SoundNote::GetPlayer() const
{
  return track.lane.note.player;
}

uint8_t SoundNote::GetLane() const
{
  return track.lane.note.lane;
}

uint8_t SoundNote::GetBGMCol() const
{
  return track.lane.note.lane;
}

uint8_t SoundNote::GetX() const
{
  return track.lane.touch.x;
}

uint8_t SoundNote::GetY() const
{
  return track.lane.touch.y;
}

NotePos& SoundNote::endpos()
{
  if (!IsLongnote()) return pos();
  else return chains.back().pos;
}

const NotePos& SoundNote::endpos() const
{
  return const_cast<SoundNote*>(this)->endpos();
}

std::string SoundNote::getValueAsString() const
{
  std::stringstream ss;
  ss << "Track (note - player, lane): " << track.lane.note.player << "," << track.lane.note.lane << std::endl;
  ss << "Track (touch - x, y): " << track.lane.touch.x << "," << track.lane.touch.y << std::endl;
  ss << "Volume: " << effect.volume << std::endl;
  ss << "Key (Pitch): " << effect.key << std::endl;
  ss << "Restart (sound) ?: " << effect.restart << std::endl;
  return ss.str();
}

bool SoundNote::operator==(const SoundNote &other) const noexcept
{
  return Note::operator==(other) && value == other.value;
}

std::string EventNote::getValueAsString() const
{
  std::stringstream ss;
  ss << "Command: " << command_;
  if (arg1_) ss << ", arg1: " << arg1_;
  if (arg2_) ss << ", arg2: " << arg2_;
  ss << std::endl;
  return ss.str();
}

EventNote::EventNote() : command_(0), arg1_(0), arg2_(0)
{
  set_type(NoteTypes::kEvent);
}

void EventNote::SetBga(BgaTypes bgatype, Channel channel, uint8_t column)
{
  set_subtype(NoteEventTypes::kBGA);
  command_ = bgatype;
  arg1_ = static_cast<decltype(arg1_)>(channel);
  arg2_ = column;
}

void EventNote::SetMidiCommand(uint8_t command, uint8_t arg1, uint8_t arg2)
{
  set_subtype(NoteEventTypes::kMIDI);
  command_ = command;
  arg1_ = arg1;
  arg2_ = arg2;
}

void EventNote::SetBmsARGBCommand(BgaTypes bgatype, Channel channel)
{
  set_subtype(NoteEventTypes::kBmsARGBLAYER);
  command_ = bgatype;
  arg1_ = static_cast<decltype(arg1_)>(channel);
  arg2_ = 0;
}

void EventNote::GetMidiCommand(uint8_t &command, uint8_t &arg1, uint8_t &arg2) const
{
  ASSERT(subtype() == NoteEventTypes::kMIDI);
  command = (uint8_t)command_;
  arg1 = (uint8_t)arg1_;
  arg2 = (uint8_t)arg2_;
}

bool EventNote::operator==(const EventNote &other) const noexcept
{
  return Note::operator==(other) &&
         command_ == other.command_ &&
         arg1_ == other.arg1_ &&
         arg2_ == other.arg2_;
}

TempoNote::TempoNote()
{
  set_type(NoteTypes::kTempo);
}

void TempoNote::SetBpm(float bpm)
{
  set_subtype(NoteTempoTypes::kBpm);
  value.f = bpm;
}

void TempoNote::SetBmsBpm(Channel bms_channel)
{
  set_subtype(NoteTempoTypes::kBmsBpm);
  value.i = bms_channel;
}

void TempoNote::SetStop(float stop)
{
  set_subtype(NoteTempoTypes::kStop);
  value.f = stop;
}

void TempoNote::SetBmsStop(Channel bms_channel)
{
  set_subtype(NoteTempoTypes::kBmsStop);
  value.i = bms_channel;
}

void TempoNote::SetMeasure(float measure_length)
{
  set_subtype(NoteTempoTypes::kMeasure);
  value.f = measure_length;
}

void TempoNote::SetScroll(float scrollspeed)
{
  set_subtype(NoteTempoTypes::kScroll);
  value.f = scrollspeed;
}

void TempoNote::SetTick(int32_t tick)
{
  set_subtype(NoteTempoTypes::kTick);
  value.i = tick;
}

void TempoNote::SetWarp(float warp_to)
{
  set_subtype(NoteTempoTypes::kWarp);
  value.f = warp_to;
}

float TempoNote::GetFloatValue() const
{
  return value.f;
}

int32_t TempoNote::GetIntValue() const
{
  return value.i;
}

std::string TempoNote::getValueAsString() const
{
  std::stringstream ss;
  ss << "Value (float): " << value.f << std::endl;
  ss << "Value (int): " << value.i << std::endl;
  return ss.str();
}

bool TempoNote::operator==(const TempoNote &other) const noexcept
{
  return Note::operator==(other) &&
         value.i == other.value.i &&
         value.f == other.value.f;
}

}
<|endoftext|>