<commit_before>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2013, Luke Goddard. 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 Luke Goddard nor the names of any
//       other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <cstdlib>

#include "GanderImage/ChannelBrothers.h"
#include "GanderImageTest/ChannelBrothersTest.h"

#include "boost/test/floating_point_comparison.hpp"
#include "boost/test/test_tools.hpp"

using namespace Gander;
using namespace Gander::Image;
using namespace Gander::ImageTest;
using namespace boost;
using namespace boost::unit_test;

namespace Gander
{

namespace ImageTest
{

struct ChannelBrothersTest
{
	void testBrothersTraitsRegistry()
	{
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::numberOfBrothers( Brothers_RGB ) ), 3 );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::numberOfBrothers( Brothers_RGBA ) ), 4 );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::numberOfBrothers( Brothers_BGR ) ), 3 );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::numberOfBrothers( Brothers_BGRA ) ), 4 );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::numberOfBrothers( Brothers_UV ) ), 2 );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::numberOfBrothers( Brothers_VU ) ), 2 );

		BOOST_CHECK_EQUAL( int( BrotherTraits<>::brotherMask( Brothers_RGB ) ), int( BrotherTraits< Brothers_RGB >::BrothersMask ) );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::brotherMask( Brothers_RGBA ) ), int( BrotherTraits< Brothers_RGBA >::BrothersMask ) );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::brotherMask( Brothers_BGR ) ), int( BrotherTraits< Brothers_BGR >::BrothersMask ) );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::brotherMask( Brothers_BGRA ) ), int( BrotherTraits< Brothers_BGRA >::BrothersMask ) );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::brotherMask( Brothers_UV ) ), int( BrotherTraits< Brothers_UV >::BrothersMask ) );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::brotherMask( Brothers_VU ) ), int( BrotherTraits< Brothers_VU >::BrothersMask ) );
	}

	void testBrotherTraitsSpecialization()
	{
		/// Check that we can decalare a specialization of the ChannelBrothers class.
		/// If there was no specialization, a compilation error would occur.

		{
		typedef BrotherTraits< Brothers_RGB > Traits;
		BOOST_CHECK_EQUAL( int( Traits::NumberOfBrothers ), 3 );
		BOOST_CHECK_EQUAL( int( Traits::BrothersMask ), 7 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder1 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder2 ), 1 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder3 ), 2 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder4 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::OffsetsShiftedByChannelValue ), 36 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOfLowestValue ), int( Chan_Red ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothers ), int( Chan_Red ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothersMask ), int( Mask_Red ) );
		}

		{
		typedef BrotherTraits< Brothers_RGBA > Traits;
		BOOST_CHECK_EQUAL( int( Traits::NumberOfBrothers ), 4 );
		BOOST_CHECK_EQUAL( int( Traits::BrothersMask ), 15 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder1 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder2 ), 1 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder3 ), 2 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder4 ), 3 );
		BOOST_CHECK_EQUAL( int( Traits::OffsetsShiftedByChannelValue ), 228 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOfLowestValue ), int( Chan_Red ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothers ), int( Chan_Red ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothersMask ), int( Mask_Red ) );
		}

		{
		typedef BrotherTraits< Brothers_BGR > Traits;
		BOOST_CHECK_EQUAL( int( Traits::NumberOfBrothers ), 3 );
		BOOST_CHECK_EQUAL( int( Traits::BrothersMask ), 7 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder1 ), 2 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder2 ), 1 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder3 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder4 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::OffsetsShiftedByChannelValue ), 6 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOfLowestValue ), int( Chan_Red ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothers ), int( Chan_Blue ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothersMask ), int( Mask_Blue ) );
		}

		{
		typedef BrotherTraits< Brothers_BGRA > Traits;
		BOOST_CHECK_EQUAL( int( Traits::NumberOfBrothers ), 4 );
		BOOST_CHECK_EQUAL( int( Traits::BrothersMask ), 15 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder1 ), 2 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder2 ), 1 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder3 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder4 ), 3 );
		BOOST_CHECK_EQUAL( int( Traits::OffsetsShiftedByChannelValue ), 198 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOfLowestValue ), int( Chan_Red ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothers ), int( Chan_Blue ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothersMask ), int( Mask_Blue ) );
		}

		{
		typedef BrotherTraits< Brothers_UV > Traits;
		BOOST_CHECK_EQUAL( int( Traits::NumberOfBrothers ), 2 );
		BOOST_CHECK_EQUAL( int( Traits::BrothersMask ), 96 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder1 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder2 ), 1 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder3 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder4 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::OffsetsShiftedByChannelValue ), 4096 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOfLowestValue ), int( Chan_U ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothers ), int( Chan_U ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothersMask ), int( Mask_U ) );
		}

		{
		typedef BrotherTraits< Brothers_VU > Traits;
		BOOST_CHECK_EQUAL( int( Traits::NumberOfBrothers ), 2 );
		BOOST_CHECK_EQUAL( int( Traits::BrothersMask ), 96 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder1 ), 1 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder2 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder3 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder4 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::OffsetsShiftedByChannelValue ), 1024 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOfLowestValue ), int( Chan_U ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothers ), int( Chan_V ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothersMask ), int( Mask_V ) );
		}
	}
};

struct ChannelBrothersTestSuite : public boost::unit_test::test_suite
{
	ChannelBrothersTestSuite() : boost::unit_test::test_suite( "ChannelBrothersTestSuite" )
	{
		boost::shared_ptr<ChannelBrothersTest> instance( new ChannelBrothersTest() );
		add( BOOST_CLASS_TEST_CASE( &ChannelBrothersTest::testBrotherTraitsSpecialization, instance ) );
		add( BOOST_CLASS_TEST_CASE( &ChannelBrothersTest::testBrothersTraitsRegistry, instance ) );
	}
};

void addChannelBrothersTest( boost::unit_test::test_suite *test )
{
	test->add( new ChannelBrothersTestSuite( ) );
}

} // namespace ImageTest

} // namespace Gander

<commit_msg>Fixed a typo.<commit_after>//////////////////////////////////////////////////////////////////////////
//
//  Copyright (c) 2013-2014, Luke Goddard. 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 Luke Goddard nor the names of any
//       other contributors to this software 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.
//
//////////////////////////////////////////////////////////////////////////
#include <iostream>
#include <cstdlib>

#include "GanderImage/ChannelBrothers.h"
#include "GanderImageTest/ChannelBrothersTest.h"

#include "boost/test/floating_point_comparison.hpp"
#include "boost/test/test_tools.hpp"

using namespace Gander;
using namespace Gander::Image;
using namespace Gander::ImageTest;
using namespace boost;
using namespace boost::unit_test;

namespace Gander
{

namespace ImageTest
{

struct ChannelBrothersTest
{
	void testBrothersTraitsRegistry()
	{
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::numberOfBrothers( Brothers_RGB ) ), 3 );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::numberOfBrothers( Brothers_RGBA ) ), 4 );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::numberOfBrothers( Brothers_BGR ) ), 3 );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::numberOfBrothers( Brothers_BGRA ) ), 4 );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::numberOfBrothers( Brothers_UV ) ), 2 );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::numberOfBrothers( Brothers_VU ) ), 2 );

		BOOST_CHECK_EQUAL( int( BrotherTraits<>::brotherMask( Brothers_RGB ) ), int( BrotherTraits< Brothers_RGB >::BrothersMask ) );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::brotherMask( Brothers_RGBA ) ), int( BrotherTraits< Brothers_RGBA >::BrothersMask ) );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::brotherMask( Brothers_BGR ) ), int( BrotherTraits< Brothers_BGR >::BrothersMask ) );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::brotherMask( Brothers_BGRA ) ), int( BrotherTraits< Brothers_BGRA >::BrothersMask ) );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::brotherMask( Brothers_UV ) ), int( BrotherTraits< Brothers_UV >::BrothersMask ) );
		BOOST_CHECK_EQUAL( int( BrotherTraits<>::brotherMask( Brothers_VU ) ), int( BrotherTraits< Brothers_VU >::BrothersMask ) );
	}

	void testBrotherTraitsSpecialization()
	{
		/// Check that we can declare a specialization of the ChannelBrothers class.
		/// If there was no specialization, a compilation error would occur.

		{
		typedef BrotherTraits< Brothers_RGB > Traits;
		BOOST_CHECK_EQUAL( int( Traits::NumberOfBrothers ), 3 );
		BOOST_CHECK_EQUAL( int( Traits::BrothersMask ), 7 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder1 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder2 ), 1 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder3 ), 2 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder4 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::OffsetsShiftedByChannelValue ), 36 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOfLowestValue ), int( Chan_Red ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothers ), int( Chan_Red ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothersMask ), int( Mask_Red ) );
		}

		{
		typedef BrotherTraits< Brothers_RGBA > Traits;
		BOOST_CHECK_EQUAL( int( Traits::NumberOfBrothers ), 4 );
		BOOST_CHECK_EQUAL( int( Traits::BrothersMask ), 15 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder1 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder2 ), 1 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder3 ), 2 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder4 ), 3 );
		BOOST_CHECK_EQUAL( int( Traits::OffsetsShiftedByChannelValue ), 228 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOfLowestValue ), int( Chan_Red ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothers ), int( Chan_Red ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothersMask ), int( Mask_Red ) );
		}

		{
		typedef BrotherTraits< Brothers_BGR > Traits;
		BOOST_CHECK_EQUAL( int( Traits::NumberOfBrothers ), 3 );
		BOOST_CHECK_EQUAL( int( Traits::BrothersMask ), 7 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder1 ), 2 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder2 ), 1 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder3 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder4 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::OffsetsShiftedByChannelValue ), 6 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOfLowestValue ), int( Chan_Red ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothers ), int( Chan_Blue ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothersMask ), int( Mask_Blue ) );
		}

		{
		typedef BrotherTraits< Brothers_BGRA > Traits;
		BOOST_CHECK_EQUAL( int( Traits::NumberOfBrothers ), 4 );
		BOOST_CHECK_EQUAL( int( Traits::BrothersMask ), 15 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder1 ), 2 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder2 ), 1 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder3 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder4 ), 3 );
		BOOST_CHECK_EQUAL( int( Traits::OffsetsShiftedByChannelValue ), 198 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOfLowestValue ), int( Chan_Red ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothers ), int( Chan_Blue ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothersMask ), int( Mask_Blue ) );
		}

		{
		typedef BrotherTraits< Brothers_UV > Traits;
		BOOST_CHECK_EQUAL( int( Traits::NumberOfBrothers ), 2 );
		BOOST_CHECK_EQUAL( int( Traits::BrothersMask ), 96 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder1 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder2 ), 1 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder3 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder4 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::OffsetsShiftedByChannelValue ), 4096 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOfLowestValue ), int( Chan_U ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothers ), int( Chan_U ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothersMask ), int( Mask_U ) );
		}

		{
		typedef BrotherTraits< Brothers_VU > Traits;
		BOOST_CHECK_EQUAL( int( Traits::NumberOfBrothers ), 2 );
		BOOST_CHECK_EQUAL( int( Traits::BrothersMask ), 96 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder1 ), 1 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder2 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder3 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOrder4 ), 0 );
		BOOST_CHECK_EQUAL( int( Traits::OffsetsShiftedByChannelValue ), 1024 );
		BOOST_CHECK_EQUAL( int( Traits::BrotherOfLowestValue ), int( Chan_U ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothers ), int( Chan_V ) );
		BOOST_CHECK_EQUAL( int( Traits::FirstBrotherInBrothersMask ), int( Mask_V ) );
		}
	}
};

struct ChannelBrothersTestSuite : public boost::unit_test::test_suite
{
	ChannelBrothersTestSuite() : boost::unit_test::test_suite( "ChannelBrothersTestSuite" )
	{
		boost::shared_ptr<ChannelBrothersTest> instance( new ChannelBrothersTest() );
		add( BOOST_CLASS_TEST_CASE( &ChannelBrothersTest::testBrotherTraitsSpecialization, instance ) );
		add( BOOST_CLASS_TEST_CASE( &ChannelBrothersTest::testBrothersTraitsRegistry, instance ) );
	}
};

void addChannelBrothersTest( boost::unit_test::test_suite *test )
{
	test->add( new ChannelBrothersTestSuite( ) );
}

} // namespace ImageTest

} // namespace Gander

<|endoftext|>


<commit_before>#include "Genes/Opponent_Pieces_Targeted_Gene.h"

#include <array>
#include <memory>

#include "Game/Board.h"
#include "Pieces/Piece.h"
#include "Pieces/Piece_Types.h"
#include "Moves/Move.h"
#include "Genes/Gene.h"
#include "Genes/Piece_Strength_Gene.h"

Opponent_Pieces_Targeted_Gene::Opponent_Pieces_Targeted_Gene(const Piece_Strength_Gene* piece_strength_gene) :
    piece_strenth_source(piece_strength_gene)
{
}

double Opponent_Pieces_Targeted_Gene::score_board(const Board& board, const Board&) const
{
    double score = 0.0;
    std::array<bool, 64> already_counted{};

    for(const auto& move : board.legal_moves())
    {
        if(move->is_en_passant())
        {
            score += piece_strenth_source->piece_value(board.get_piece(PAWN, opposite(board.whose_turn())));
            continue;
        }

        if( ! move->can_capture())
        {
            continue;
        }

        auto end_file = move->end_file();
        auto end_rank = move->end_rank();
        auto target_piece = board.piece_on_square(end_file, end_rank);
        auto target_index = Board::board_index(end_file, end_rank);
        if(target_piece && ! already_counted[target_index])
        {
            score += piece_strenth_source->piece_value(target_piece);
            already_counted[target_index] = true;
        }
    }

    return score;
}

std::unique_ptr<Gene> Opponent_Pieces_Targeted_Gene::duplicate() const
{
    return std::make_unique<Opponent_Pieces_Targeted_Gene>(*this);
}

std::string Opponent_Pieces_Targeted_Gene::name() const
{
    return "Opponent Pieces Targeted Gene";
}

void Opponent_Pieces_Targeted_Gene::reset_piece_strength_gene(const Piece_Strength_Gene* psg)
{
    piece_strenth_source = psg;
}
<commit_msg>Opponent Pieces Targeted Gene improvement<commit_after>#include "Genes/Opponent_Pieces_Targeted_Gene.h"

#include <array>
#include <memory>

#include "Game/Board.h"
#include "Pieces/Piece.h"
#include "Pieces/Piece_Types.h"
#include "Moves/Move.h"
#include "Genes/Gene.h"
#include "Genes/Piece_Strength_Gene.h"

Opponent_Pieces_Targeted_Gene::Opponent_Pieces_Targeted_Gene(const Piece_Strength_Gene* piece_strength_gene) :
    piece_strenth_source(piece_strength_gene)
{
}

double Opponent_Pieces_Targeted_Gene::score_board(const Board& board, const Board&) const
{
    double score = 0.0;
    auto squares_attacked = board.all_square_indices_attacked();

    for(char file = 'a'; file <= 'h'; ++file)
    {
        for(int rank = 1; rank <= 8; ++rank)
        {
            if(squares_attacked[board.board_index(file, rank)])
            {
                score += piece_strenth_source->piece_value(board.piece_on_square(file, rank));
            }
        }
    }

    return score;
}

std::unique_ptr<Gene> Opponent_Pieces_Targeted_Gene::duplicate() const
{
    return std::make_unique<Opponent_Pieces_Targeted_Gene>(*this);
}

std::string Opponent_Pieces_Targeted_Gene::name() const
{
    return "Opponent Pieces Targeted Gene";
}

void Opponent_Pieces_Targeted_Gene::reset_piece_strength_gene(const Piece_Strength_Gene* psg)
{
    piece_strenth_source = psg;
}
<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// materialization_executor.cpp
//
// Identification: src/backend/executor/materialization_executor.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "backend/executor/materialization_executor.h"

#include <cassert>
#include <memory>
#include <utility>

#include "backend/planner/materialization_plan.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/storage/tile.h"
#include "backend/storage/data_table.h"

namespace peloton {
namespace executor {

// Row-oriented materialization
void MaterializeRowAtAtATime(LogicalTile *source_tile,
                             const std::unordered_map<oid_t, oid_t> &old_to_new_cols,
                             const std::unordered_map<storage::Tile *, std::vector<oid_t>> &tile_to_cols,
                             storage::Tile *dest_tile);

// Column-oriented materialization
void MaterializeColumnAtATime(LogicalTile *source_tile,
                              const std::unordered_map<oid_t, oid_t> &old_to_new_cols,
                              const std::unordered_map<storage::Tile *, std::vector<oid_t>> &tile_to_cols,
                              storage::Tile *dest_tile);

/**
 * @brief Constructor for the materialization executor.
 * @param node Materialization node corresponding to this executor.
 */
MaterializationExecutor::MaterializationExecutor(
    planner::AbstractPlan *node, ExecutorContext *executor_context)
: AbstractExecutor(node, executor_context) {}

/**
 * @brief Nothing to init at the moment.
 * @return true on success, false otherwise.
 */
bool MaterializationExecutor::DInit() {
  assert(children_.size() == 1);

  return true;
}

/**
 * @brief Generates map from each base tile to columns originally from that
 *        base tile to be materialized.
 * @param column_ids Ids of columns to be materialized.
 * @param source_tile Logical tile that contains mapping from columns to
 *        base tiles.
 * @param tile_to_cols Map to be populated with mappings from tile to columns.
 *
 * We generate this mapping so that we can materialize columns tile by tile for
 * efficiency reasons.
 */
void MaterializationExecutor::GenerateTileToColMap(
    const std::unordered_map<oid_t, oid_t> &old_to_new_cols,
    LogicalTile *source_tile,
    std::unordered_map<storage::Tile *, std::vector<oid_t>> &
    cols_in_physical_tile) {
  for (const auto &kv : old_to_new_cols) {
    oid_t col = kv.first;

    // figure out base physical tile for column in logical tile
    storage::Tile *base_tile = source_tile->GetBaseTile(col);

    std::vector<oid_t> &cols_from_tile = cols_in_physical_tile[base_tile];
    cols_from_tile.push_back(col);
  }
}

/**
 * @brief Does the actual copying of data into the new physical tile.
 * @param source_tile Source tile to copy data from.
 * @param tile_to_cols Map from base tile to columns in that tile
 *        to be materialized.
 * @param dest_tile New tile to copy data into.
 */
void MaterializationExecutor::MaterializeByTiles(
    LogicalTile *source_tile,
    const std::unordered_map<oid_t, oid_t> &old_to_new_cols,
    const std::unordered_map<storage::Tile *, std::vector<oid_t>> &tile_to_cols,
    storage::Tile *dest_tile) {

  auto dest_tile_column_count = dest_tile->GetColumnCount();
  // TODO: Make this a parameter
  oid_t column_count_threshold = 20;
  bool row_wise_materialization = false;

  if(peloton_layout == LAYOUT_COLUMN)
    row_wise_materialization = true;

  if(peloton_layout == LAYOUT_HYBRID &&
      dest_tile_column_count > column_count_threshold)
    row_wise_materialization = true;

  // Materialize as needed
  if(row_wise_materialization == true) {
    MaterializeRowAtAtATime(source_tile, old_to_new_cols, tile_to_cols, dest_tile);
  }
  else {
    MaterializeColumnAtATime(source_tile, old_to_new_cols, tile_to_cols, dest_tile);
  }

}

void MaterializeRowAtAtATime(LogicalTile *source_tile,
                             const std::unordered_map<oid_t, oid_t> &old_to_new_cols,
                             const std::unordered_map<storage::Tile *, std::vector<oid_t>> &tile_to_cols,
                             storage::Tile *dest_tile) {

  ///////////////////////////
  // EACH PHYSICAL TILE
  ///////////////////////////
  // Copy over all data from each base tile.
  for (const auto &kv : tile_to_cols) {
    const std::vector<oid_t> &old_column_ids = kv.second;

    auto &schema = source_tile->GetSchema();
    oid_t new_tuple_id = 0;

    auto& column_position_lists = source_tile->GetPositionLists();

    // Get old column information
    std::vector<oid_t> old_column_position_idxs;
    std::vector<size_t> old_column_offsets;
    std::vector<ValueType> old_column_types;
    std::vector<bool> old_is_inlineds;
    std::vector<storage::Tile*> old_tiles;

    // Get new column information
    std::vector<size_t> new_column_offsets;
    std::vector<bool> new_is_inlineds;
    std::vector<size_t> new_column_lengths;

    // Amortize schema lookups once per column
    for (oid_t old_col_id : old_column_ids) {
      auto& column_info = schema[old_col_id];

      // Get the position list
      old_column_position_idxs.push_back(column_info.position_list_idx);

      // Get old column information
      storage::Tile *old_tile = column_info.base_tile;
      old_tiles.push_back(old_tile);
      auto old_schema = old_tile->GetSchema();
      oid_t old_column_id = column_info.origin_column_id;
      const size_t old_column_offset = old_schema->GetOffset(old_column_id);
      old_column_offsets.push_back(old_column_offset);
      const ValueType old_column_type = old_schema->GetType(old_column_id);
      old_column_types.push_back(old_column_type);
      const bool old_is_inlined = old_schema->IsInlined(old_column_id);
      old_is_inlineds.push_back(old_is_inlined);

      // Old to new column mapping
      auto it = old_to_new_cols.find(old_col_id);
      assert(it != old_to_new_cols.end());

      // Get new column information
      oid_t new_column_id = it->second;
      auto new_schema = dest_tile->GetSchema();
      const size_t new_column_offset = new_schema->GetOffset(new_column_id);
      new_column_offsets.push_back(new_column_offset);
      const bool new_is_inlined = new_schema->IsInlined(new_column_id);
      new_is_inlineds.push_back(new_is_inlined);
      const size_t new_column_length = new_schema->GetAppropriateLength(new_column_id);
      new_column_lengths.push_back(new_column_length);
    }

    assert(new_column_offsets.size() == old_column_ids.size());

    ///////////////////////////
    // EACH TUPLE
    ///////////////////////////
    // Copy all values in the tuple to the physical tile
    // This uses fast getter and setter functions
    for (oid_t old_tuple_id : *source_tile) {

      ///////////////////////////
      // EACH COLUMN
      ///////////////////////////
      // Go over each column in given base physical tile
      oid_t col_itr = 0;

      for (oid_t old_col_id : old_column_position_idxs) {

        auto& column_position_list = column_position_lists[old_col_id];

        oid_t base_tuple_id = column_position_list[old_tuple_id];

        auto value = old_tiles[col_itr]->GetValueFast(base_tuple_id,
                                                      old_column_offsets[col_itr],
                                                      old_column_types[col_itr],
                                                      old_is_inlineds[col_itr]);

        LOG_TRACE("Old Tuple : %u Column : %u \n", old_tuple_id, old_col_id);
        LOG_TRACE("New Tuple : %u Column : %u \n", new_tuple_id, new_column_id);

        dest_tile->SetValueFast(value, new_tuple_id,
                                new_column_offsets[col_itr],
                                new_is_inlineds[col_itr],
                                new_column_lengths[col_itr]);

        // Go to next column
        col_itr++;
      }

      // Go to next tuple
      new_tuple_id++;
    }

  }

}

void MaterializeColumnAtATime(LogicalTile *source_tile,
                              const std::unordered_map<oid_t, oid_t> &old_to_new_cols,
                              const std::unordered_map<storage::Tile *, std::vector<oid_t>> &tile_to_cols,
                              storage::Tile *dest_tile) {

  ///////////////////////////
  // EACH PHYSICAL TILE
  ///////////////////////////
  // Copy over all data from each base tile.
  for (const auto &kv : tile_to_cols) {
    const std::vector<oid_t> &old_column_ids = kv.second;

    ///////////////////////////
    // EACH COLUMN
    ///////////////////////////
    // Go over each column in given base physical tile
    for (oid_t old_col_id : old_column_ids) {
      auto &column_info = source_tile->GetColumnInfo(old_col_id);

      // Amortize schema lookups once per column
      storage::Tile *old_tile = column_info.base_tile;
      auto old_schema = old_tile->GetSchema();

      // Get old column information
      oid_t old_column_id = column_info.origin_column_id;
      const size_t old_column_offset = old_schema->GetOffset(old_column_id);
      const ValueType old_column_type = old_schema->GetType(old_column_id);
      const bool old_is_inlined = old_schema->IsInlined(old_column_id);

      // Old to new column mapping
      auto it = old_to_new_cols.find(old_col_id);
      assert(it != old_to_new_cols.end());

      // Get new column information
      oid_t new_column_id = it->second;
      auto new_schema = dest_tile->GetSchema();
      const size_t new_column_offset = new_schema->GetOffset(new_column_id);
      const bool new_is_inlined = new_schema->IsInlined(new_column_id);
      const size_t new_column_length = new_schema->GetAppropriateLength(new_column_id);

      // Get the position list
      auto& column_position_list = source_tile->GetPositionList(column_info.position_list_idx);
      oid_t new_tuple_id = 0;

      // Copy all values in the column to the physical tile
      // This uses fast getter and setter functions
      ///////////////////////////
      // EACH TUPLE
      ///////////////////////////
      for (oid_t old_tuple_id : *source_tile) {
        oid_t base_tuple_id = column_position_list[old_tuple_id];
        auto value = old_tile->GetValueFast(base_tuple_id,
                                            old_column_offset,
                                            old_column_type,
                                            old_is_inlined);

        LOG_TRACE("Old Tuple : %u Column : %u \n", old_tuple_id, old_col_id);
        LOG_TRACE("New Tuple : %u Column : %u \n", new_tuple_id, new_column_id);

        dest_tile->SetValueFast(value, new_tuple_id,
                                new_column_offset,
                                new_is_inlined,
                                new_column_length);

        // Go to next tuple
        new_tuple_id++;
      }

    }

  }

}

std::unordered_map<oid_t, oid_t> MaterializationExecutor::BuildIdentityMapping(
    const catalog::Schema *schema) {
  std::unordered_map<oid_t, oid_t> old_to_new_cols;
  oid_t column_count = schema->GetColumnCount();
  for (oid_t col = 0; col < column_count; col++) {
    old_to_new_cols[col] = col;
  }

  return old_to_new_cols;
}

/**
 * @brief Create a physical tile for the given logical tile
 * @param source_tile Source tile from which the physical tile is created
 * @return a logical tile wrapper for the created physical tile
 */
LogicalTile *MaterializationExecutor::Physify(LogicalTile *source_tile) {
  std::unique_ptr<catalog::Schema> source_tile_schema(
      source_tile->GetPhysicalSchema());
  const int num_tuples = source_tile->GetTupleCount();
  const catalog::Schema *output_schema;
  std::unordered_map<oid_t, oid_t> old_to_new_cols;
  auto node = GetRawNode();

  // Create a default identity mapping node if we did not get one
  if (node == nullptr) {
    assert(source_tile_schema.get());
    output_schema = source_tile_schema.get();

    old_to_new_cols = BuildIdentityMapping(output_schema);
  }
  // Else use the mapping in the given plan node
  else {
    const planner::MaterializationPlan &node =
        GetPlanNode<planner::MaterializationPlan>();
    if (node.GetSchema()) {
      output_schema = node.GetSchema();
      old_to_new_cols = node.old_to_new_cols();
    } else {
      output_schema = source_tile_schema.get();
      old_to_new_cols = BuildIdentityMapping(output_schema);
    }
  }

  // Generate mappings.
  std::unordered_map<storage::Tile *, std::vector<oid_t>> tile_to_cols;
  GenerateTileToColMap(old_to_new_cols, source_tile, tile_to_cols);

  // Create new physical tile.
  std::unique_ptr<storage::Tile> dest_tile(
      storage::TileFactory::GetTempTile(*output_schema, num_tuples));

  // Proceed to materialize logical tile by physical tile at a time.
  MaterializeByTiles(source_tile, old_to_new_cols, tile_to_cols,
                     dest_tile.get());

  bool own_base_tile = true;

  // Wrap physical tile in logical tile.
  return LogicalTileFactory::WrapTiles({dest_tile.release()}, own_base_tile);
}

/**
 * @brief Creates materialized physical tile from logical tile and wraps it
 *        in a new logical tile.
 *
 * @return true on success, false otherwise.
 */
bool MaterializationExecutor::DExecute() {
  // Retrieve child tile.
  const bool success = children_[0]->Execute();
  if (!success) {
    return false;
  }

  std::unique_ptr<LogicalTile> source_tile(children_[0]->GetOutput());
  LogicalTile *output_tile = nullptr;

  // Check the number of tuples in input logical tile
  // If none, then just return false
  const int num_tuples = source_tile->GetTupleCount();
  if (num_tuples == 0) {
    return false;
  }

  auto node = GetRawNode();
  bool physify_flag = true;  // by default, we create a physical tile

  if (node != nullptr) {
    const planner::MaterializationPlan &node =
        GetPlanNode<planner::MaterializationPlan>();
    physify_flag = node.GetPhysifyFlag();
  }

  if (physify_flag) {
    /* create a physical tile and a logical tile wrapper to be the output */
    output_tile = Physify(source_tile.get());
  } else {
    /* just pass thru the underlying logical tile */
    output_tile = source_tile.release();
  }

  SetOutput(output_tile);

  return true;
}

}  // namespace executor
}  // namespace peloton
<commit_msg>Checkpoint<commit_after>//===----------------------------------------------------------------------===//
//
//                         PelotonDB
//
// materialization_executor.cpp
//
// Identification: src/backend/executor/materialization_executor.cpp
//
// Copyright (c) 2015, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//

#include "backend/executor/materialization_executor.h"

#include <cassert>
#include <memory>
#include <utility>

#include "backend/planner/materialization_plan.h"
#include "backend/executor/logical_tile.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/storage/tile.h"
#include "backend/storage/data_table.h"

namespace peloton {
namespace executor {

// Row-oriented materialization
void MaterializeRowAtAtATime(LogicalTile *source_tile,
                             const std::unordered_map<oid_t, oid_t> &old_to_new_cols,
                             const std::unordered_map<storage::Tile *, std::vector<oid_t>> &tile_to_cols,
                             storage::Tile *dest_tile);

// Column-oriented materialization
void MaterializeColumnAtATime(LogicalTile *source_tile,
                              const std::unordered_map<oid_t, oid_t> &old_to_new_cols,
                              const std::unordered_map<storage::Tile *, std::vector<oid_t>> &tile_to_cols,
                              storage::Tile *dest_tile);

/**
 * @brief Constructor for the materialization executor.
 * @param node Materialization node corresponding to this executor.
 */
MaterializationExecutor::MaterializationExecutor(
    planner::AbstractPlan *node, ExecutorContext *executor_context)
: AbstractExecutor(node, executor_context) {}

/**
 * @brief Nothing to init at the moment.
 * @return true on success, false otherwise.
 */
bool MaterializationExecutor::DInit() {
  assert(children_.size() == 1);

  return true;
}

/**
 * @brief Generates map from each base tile to columns originally from that
 *        base tile to be materialized.
 * @param column_ids Ids of columns to be materialized.
 * @param source_tile Logical tile that contains mapping from columns to
 *        base tiles.
 * @param tile_to_cols Map to be populated with mappings from tile to columns.
 *
 * We generate this mapping so that we can materialize columns tile by tile for
 * efficiency reasons.
 */
void MaterializationExecutor::GenerateTileToColMap(
    const std::unordered_map<oid_t, oid_t> &old_to_new_cols,
    LogicalTile *source_tile,
    std::unordered_map<storage::Tile *, std::vector<oid_t>> &
    cols_in_physical_tile) {
  for (const auto &kv : old_to_new_cols) {
    oid_t col = kv.first;

    // figure out base physical tile for column in logical tile
    storage::Tile *base_tile = source_tile->GetBaseTile(col);

    std::vector<oid_t> &cols_from_tile = cols_in_physical_tile[base_tile];
    cols_from_tile.push_back(col);
  }
}

/**
 * @brief Does the actual copying of data into the new physical tile.
 * @param source_tile Source tile to copy data from.
 * @param tile_to_cols Map from base tile to columns in that tile
 *        to be materialized.
 * @param dest_tile New tile to copy data into.
 */
void MaterializationExecutor::MaterializeByTiles(
    LogicalTile *source_tile,
    const std::unordered_map<oid_t, oid_t> &old_to_new_cols,
    const std::unordered_map<storage::Tile *, std::vector<oid_t>> &tile_to_cols,
    storage::Tile *dest_tile) {

  auto dest_tile_column_count = dest_tile->GetColumnCount();
  // TODO: Make this a parameter
  oid_t column_count_threshold = 20;
  bool row_wise_materialization = true;

  if(peloton_layout == LAYOUT_COLUMN)
    row_wise_materialization = false;

  if(peloton_layout == LAYOUT_HYBRID &&
      dest_tile_column_count < column_count_threshold)
    row_wise_materialization = false;

  // Materialize as needed
  if(row_wise_materialization == true) {
    MaterializeRowAtAtATime(source_tile, old_to_new_cols, tile_to_cols, dest_tile);
  }
  else {
    MaterializeColumnAtATime(source_tile, old_to_new_cols, tile_to_cols, dest_tile);
  }

}

void MaterializeRowAtAtATime(LogicalTile *source_tile,
                             const std::unordered_map<oid_t, oid_t> &old_to_new_cols,
                             const std::unordered_map<storage::Tile *, std::vector<oid_t>> &tile_to_cols,
                             storage::Tile *dest_tile) {

  ///////////////////////////
  // EACH PHYSICAL TILE
  ///////////////////////////
  // Copy over all data from each base tile.
  for (const auto &kv : tile_to_cols) {
    const std::vector<oid_t> &old_column_ids = kv.second;

    auto &schema = source_tile->GetSchema();
    oid_t new_tuple_id = 0;

    auto& column_position_lists = source_tile->GetPositionLists();

    // Get old column information
    std::vector<oid_t> old_column_position_idxs;
    std::vector<size_t> old_column_offsets;
    std::vector<ValueType> old_column_types;
    std::vector<bool> old_is_inlineds;
    std::vector<storage::Tile*> old_tiles;

    // Get new column information
    std::vector<size_t> new_column_offsets;
    std::vector<bool> new_is_inlineds;
    std::vector<size_t> new_column_lengths;

    // Amortize schema lookups once per column
    for (oid_t old_col_id : old_column_ids) {
      auto& column_info = schema[old_col_id];

      // Get the position list
      old_column_position_idxs.push_back(column_info.position_list_idx);

      // Get old column information
      storage::Tile *old_tile = column_info.base_tile;
      old_tiles.push_back(old_tile);
      auto old_schema = old_tile->GetSchema();
      oid_t old_column_id = column_info.origin_column_id;
      const size_t old_column_offset = old_schema->GetOffset(old_column_id);
      old_column_offsets.push_back(old_column_offset);
      const ValueType old_column_type = old_schema->GetType(old_column_id);
      old_column_types.push_back(old_column_type);
      const bool old_is_inlined = old_schema->IsInlined(old_column_id);
      old_is_inlineds.push_back(old_is_inlined);

      // Old to new column mapping
      auto it = old_to_new_cols.find(old_col_id);
      assert(it != old_to_new_cols.end());

      // Get new column information
      oid_t new_column_id = it->second;
      auto new_schema = dest_tile->GetSchema();
      const size_t new_column_offset = new_schema->GetOffset(new_column_id);
      new_column_offsets.push_back(new_column_offset);
      const bool new_is_inlined = new_schema->IsInlined(new_column_id);
      new_is_inlineds.push_back(new_is_inlined);
      const size_t new_column_length = new_schema->GetAppropriateLength(new_column_id);
      new_column_lengths.push_back(new_column_length);
    }

    assert(new_column_offsets.size() == old_column_ids.size());

    ///////////////////////////
    // EACH TUPLE
    ///////////////////////////
    // Copy all values in the tuple to the physical tile
    // This uses fast getter and setter functions
    for (oid_t old_tuple_id : *source_tile) {

      ///////////////////////////
      // EACH COLUMN
      ///////////////////////////
      // Go over each column in given base physical tile
      oid_t col_itr = 0;

      for (oid_t old_col_id : old_column_position_idxs) {

        auto& column_position_list = column_position_lists[old_col_id];

        oid_t base_tuple_id = column_position_list[old_tuple_id];

        auto value = old_tiles[col_itr]->GetValueFast(base_tuple_id,
                                                      old_column_offsets[col_itr],
                                                      old_column_types[col_itr],
                                                      old_is_inlineds[col_itr]);

        LOG_TRACE("Old Tuple : %u Column : %u \n", old_tuple_id, old_col_id);
        LOG_TRACE("New Tuple : %u Column : %u \n", new_tuple_id, new_column_id);

        dest_tile->SetValueFast(value, new_tuple_id,
                                new_column_offsets[col_itr],
                                new_is_inlineds[col_itr],
                                new_column_lengths[col_itr]);

        // Go to next column
        col_itr++;
      }

      // Go to next tuple
      new_tuple_id++;
    }

  }

}

void MaterializeColumnAtATime(LogicalTile *source_tile,
                              const std::unordered_map<oid_t, oid_t> &old_to_new_cols,
                              const std::unordered_map<storage::Tile *, std::vector<oid_t>> &tile_to_cols,
                              storage::Tile *dest_tile) {

  ///////////////////////////
  // EACH PHYSICAL TILE
  ///////////////////////////
  // Copy over all data from each base tile.
  for (const auto &kv : tile_to_cols) {
    const std::vector<oid_t> &old_column_ids = kv.second;

    ///////////////////////////
    // EACH COLUMN
    ///////////////////////////
    // Go over each column in given base physical tile
    for (oid_t old_col_id : old_column_ids) {
      auto &column_info = source_tile->GetColumnInfo(old_col_id);

      // Amortize schema lookups once per column
      storage::Tile *old_tile = column_info.base_tile;
      auto old_schema = old_tile->GetSchema();

      // Get old column information
      oid_t old_column_id = column_info.origin_column_id;
      const size_t old_column_offset = old_schema->GetOffset(old_column_id);
      const ValueType old_column_type = old_schema->GetType(old_column_id);
      const bool old_is_inlined = old_schema->IsInlined(old_column_id);

      // Old to new column mapping
      auto it = old_to_new_cols.find(old_col_id);
      assert(it != old_to_new_cols.end());

      // Get new column information
      oid_t new_column_id = it->second;
      auto new_schema = dest_tile->GetSchema();
      const size_t new_column_offset = new_schema->GetOffset(new_column_id);
      const bool new_is_inlined = new_schema->IsInlined(new_column_id);
      const size_t new_column_length = new_schema->GetAppropriateLength(new_column_id);

      // Get the position list
      auto& column_position_list = source_tile->GetPositionList(column_info.position_list_idx);
      oid_t new_tuple_id = 0;

      // Copy all values in the column to the physical tile
      // This uses fast getter and setter functions
      ///////////////////////////
      // EACH TUPLE
      ///////////////////////////
      for (oid_t old_tuple_id : *source_tile) {
        oid_t base_tuple_id = column_position_list[old_tuple_id];
        auto value = old_tile->GetValueFast(base_tuple_id,
                                            old_column_offset,
                                            old_column_type,
                                            old_is_inlined);

        LOG_TRACE("Old Tuple : %u Column : %u \n", old_tuple_id, old_col_id);
        LOG_TRACE("New Tuple : %u Column : %u \n", new_tuple_id, new_column_id);

        dest_tile->SetValueFast(value, new_tuple_id,
                                new_column_offset,
                                new_is_inlined,
                                new_column_length);

        // Go to next tuple
        new_tuple_id++;
      }

    }

  }

}

std::unordered_map<oid_t, oid_t> MaterializationExecutor::BuildIdentityMapping(
    const catalog::Schema *schema) {
  std::unordered_map<oid_t, oid_t> old_to_new_cols;
  oid_t column_count = schema->GetColumnCount();
  for (oid_t col = 0; col < column_count; col++) {
    old_to_new_cols[col] = col;
  }

  return old_to_new_cols;
}

/**
 * @brief Create a physical tile for the given logical tile
 * @param source_tile Source tile from which the physical tile is created
 * @return a logical tile wrapper for the created physical tile
 */
LogicalTile *MaterializationExecutor::Physify(LogicalTile *source_tile) {
  std::unique_ptr<catalog::Schema> source_tile_schema(
      source_tile->GetPhysicalSchema());
  const int num_tuples = source_tile->GetTupleCount();
  const catalog::Schema *output_schema;
  std::unordered_map<oid_t, oid_t> old_to_new_cols;
  auto node = GetRawNode();

  // Create a default identity mapping node if we did not get one
  if (node == nullptr) {
    assert(source_tile_schema.get());
    output_schema = source_tile_schema.get();

    old_to_new_cols = BuildIdentityMapping(output_schema);
  }
  // Else use the mapping in the given plan node
  else {
    const planner::MaterializationPlan &node =
        GetPlanNode<planner::MaterializationPlan>();
    if (node.GetSchema()) {
      output_schema = node.GetSchema();
      old_to_new_cols = node.old_to_new_cols();
    } else {
      output_schema = source_tile_schema.get();
      old_to_new_cols = BuildIdentityMapping(output_schema);
    }
  }

  // Generate mappings.
  std::unordered_map<storage::Tile *, std::vector<oid_t>> tile_to_cols;
  GenerateTileToColMap(old_to_new_cols, source_tile, tile_to_cols);

  // Create new physical tile.
  std::unique_ptr<storage::Tile> dest_tile(
      storage::TileFactory::GetTempTile(*output_schema, num_tuples));

  // Proceed to materialize logical tile by physical tile at a time.
  MaterializeByTiles(source_tile, old_to_new_cols, tile_to_cols,
                     dest_tile.get());

  bool own_base_tile = true;

  // Wrap physical tile in logical tile.
  return LogicalTileFactory::WrapTiles({dest_tile.release()}, own_base_tile);
}

/**
 * @brief Creates materialized physical tile from logical tile and wraps it
 *        in a new logical tile.
 *
 * @return true on success, false otherwise.
 */
bool MaterializationExecutor::DExecute() {
  // Retrieve child tile.
  const bool success = children_[0]->Execute();
  if (!success) {
    return false;
  }

  std::unique_ptr<LogicalTile> source_tile(children_[0]->GetOutput());
  LogicalTile *output_tile = nullptr;

  // Check the number of tuples in input logical tile
  // If none, then just return false
  const int num_tuples = source_tile->GetTupleCount();
  if (num_tuples == 0) {
    return false;
  }

  auto node = GetRawNode();
  bool physify_flag = true;  // by default, we create a physical tile

  if (node != nullptr) {
    const planner::MaterializationPlan &node =
        GetPlanNode<planner::MaterializationPlan>();
    physify_flag = node.GetPhysifyFlag();
  }

  if (physify_flag) {
    /* create a physical tile and a logical tile wrapper to be the output */
    output_tile = Physify(source_tile.get());
  } else {
    /* just pass thru the underlying logical tile */
    output_tile = source_tile.release();
  }

  SetOutput(output_tile);

  return true;
}

}  // namespace executor
}  // namespace peloton
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2010-2011 Dmitry Marakasov
 *
 * This file is part of glosm.
 *
 * glosm is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * glosm is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with glosm.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "GlosmViewer.hh"

#include <SDL/SDL.h>
#include <SDL/SDL_keysym.h>

#if defined(WITH_GLES)
#	include <GLES/gl.h>
#	include <SDL_gles.h>
#else
#	if defined(__APPLE__)
#		include <OpenGL/gl.h>
#	else
#		include <GL/gl.h>
#	endif
#	include <SDL/SDL_opengl.h>
#endif

#include <cstdio>

class GlosmViewerImpl : public GlosmViewer {
protected:
	bool ignoremouse_;

public:
	GlosmViewerImpl() : ignoremouse_(true) {
	}

	virtual void MouseMove(int x, int y) {
		if (!ignoremouse_)
			GlosmViewer::MouseMove(x, y);
	}

protected:
	virtual void WarpCursor(int x, int y) {
		ignoremouse_ = true;
		SDL_WarpMouse(x, y);
		ignoremouse_ = false;
	}

	virtual void Flip() {
#if defined(WITH_GLES)
		SDL_GLES_SwapBuffers();
#else
		SDL_GL_SwapBuffers();
#endif
	}
};

#if defined(WITH_GLES)
SDL_GLES_Context* gles_context = 0;
#endif

GlosmViewerImpl app;

void Reshape(int w, int h) {
#if !defined(WITH_GLES)
	SDL_SetVideoMode(w, h, 0, SDL_OPENGL | SDL_RESIZABLE | SDL_HWSURFACE);
#endif

	app.Resize(w, h);
}

void KeyDown(SDLKey key) {
	if (key < 0x100)
		app.KeyDown(key);
	else
		switch(key) {
		case SDLK_UP: app.KeyDown(GlosmViewer::UP); break;
		case SDLK_DOWN: app.KeyDown(GlosmViewer::DOWN); break;
		case SDLK_LEFT: app.KeyDown(GlosmViewer::LEFT); break;
		case SDLK_RIGHT: app.KeyDown(GlosmViewer::RIGHT); break;
		case SDLK_KP_PLUS: app.KeyDown('+'); break;
		case SDLK_KP_MINUS: app.KeyDown('-'); break;
		case SDLK_LSHIFT: case SDLK_RSHIFT: app.KeyDown(GlosmViewer::SHIFT); break;
		case SDLK_LCTRL: case SDLK_RCTRL: app.KeyDown(GlosmViewer::CTRL); break;
		default: break;
		}
}

void KeyUp(SDLKey key) {
	if (key < 0x100)
		app.KeyUp(key);
	else
		switch(key) {
		case SDLK_UP: app.KeyUp(GlosmViewer::UP); break;
		case SDLK_DOWN: app.KeyUp(GlosmViewer::DOWN); break;
		case SDLK_LEFT: app.KeyUp(GlosmViewer::LEFT); break;
		case SDLK_RIGHT: app.KeyUp(GlosmViewer::RIGHT); break;
		case SDLK_KP_PLUS: app.KeyUp('+'); break;
		case SDLK_KP_MINUS: app.KeyUp('-'); break;
		case SDLK_LSHIFT: case SDLK_RSHIFT: app.KeyUp(GlosmViewer::SHIFT); break;
		case SDLK_LCTRL: case SDLK_RCTRL: app.KeyUp(GlosmViewer::CTRL); break;
		default: break;
		}
}

void Cleanup() {
#if defined(WITH_GLES)
	if (gles_context)
		SDL_GLES_DeleteContext(gles_context);
#endif
	SDL_Quit();
}

int GetEvents() {
	SDL_Event event;

	while (SDL_PollEvent(&event)) {
		int ret = 1;
		switch(event.type) {
		case SDL_QUIT:
			return 0;
		case SDL_KEYDOWN:
			KeyDown(event.key.keysym.sym);
			break;
		case SDL_KEYUP:
			KeyUp(event.key.keysym.sym);
			break;
		case SDL_MOUSEMOTION:
			app.MouseMove(event.motion.x, event.motion.y);
			break;
		case SDL_VIDEORESIZE:
			Reshape(event.resize.w, event.resize.h);
			break;
		default:
			break;
		}

		if (ret == 0)
			return 0;
	}

	return 1;
}

int real_main(int argc, char** argv) {
	app.Init(argc, argv);

	/* glut init */
	if (SDL_Init(SDL_INIT_VIDEO) != 0)
		throw Exception() << "Couldn't initialize SDL: " << (const char*)SDL_GetError();

	atexit(Cleanup);

#if !defined(WITH_GLES)
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	Reshape(800, 600);
#else
	/* Using fixed resolution for N900
	 * it should be detected on the fly instead */
	SDL_SetVideoMode(800, 480, 0, SDL_SWSURFACE | SDL_FULLSCREEN);

	SDL_GLES_Init(SDL_GLES_VERSION_1_1);

	gles_context = SDL_GLES_CreateContext();

	SDL_GLES_MakeCurrent(gles_context);

	Reshape(800, 480);
#endif

	SDL_ShowCursor(SDL_DISABLE);
	SDL_EnableKeyRepeat(0, 0);

	app.InitGL();

	/* main loop */
	while (GetEvents())
		app.Render();

	return 0;
}

int main(int argc, char** argv) {
	try {
		return real_main(argc, argv);
	} catch (std::exception &e) {
		fprintf(stderr, "Exception: %s\n", e.what());
	} catch (...) {
		fprintf(stderr, "Unknown exception\n");
	}

	return 1;
}
<commit_msg>Enable depth buffer<commit_after>/*
 * Copyright (C) 2010-2011 Dmitry Marakasov
 *
 * This file is part of glosm.
 *
 * glosm is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * glosm is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with glosm.  If not, see <http://www.gnu.org/licenses/>.
 */

#include "GlosmViewer.hh"

#include <SDL/SDL.h>
#include <SDL/SDL_keysym.h>

#if defined(WITH_GLES)
#	include <GLES/gl.h>
#	include <SDL_gles.h>
#else
#	if defined(__APPLE__)
#		include <OpenGL/gl.h>
#	else
#		include <GL/gl.h>
#	endif
#	include <SDL/SDL_opengl.h>
#endif

#include <cstdio>

class GlosmViewerImpl : public GlosmViewer {
protected:
	bool ignoremouse_;

public:
	GlosmViewerImpl() : ignoremouse_(true) {
	}

	virtual void MouseMove(int x, int y) {
		if (!ignoremouse_)
			GlosmViewer::MouseMove(x, y);
	}

protected:
	virtual void WarpCursor(int x, int y) {
		ignoremouse_ = true;
		SDL_WarpMouse(x, y);
		ignoremouse_ = false;
	}

	virtual void Flip() {
#if defined(WITH_GLES)
		SDL_GLES_SwapBuffers();
#else
		SDL_GL_SwapBuffers();
#endif
	}
};

#if defined(WITH_GLES)
SDL_GLES_Context* gles_context = 0;
#endif

GlosmViewerImpl app;

void Reshape(int w, int h) {
#if !defined(WITH_GLES)
	SDL_SetVideoMode(w, h, 0, SDL_OPENGL | SDL_RESIZABLE | SDL_HWSURFACE);
#endif

	app.Resize(w, h);
}

void KeyDown(SDLKey key) {
	if (key < 0x100)
		app.KeyDown(key);
	else
		switch(key) {
		case SDLK_UP: app.KeyDown(GlosmViewer::UP); break;
		case SDLK_DOWN: app.KeyDown(GlosmViewer::DOWN); break;
		case SDLK_LEFT: app.KeyDown(GlosmViewer::LEFT); break;
		case SDLK_RIGHT: app.KeyDown(GlosmViewer::RIGHT); break;
		case SDLK_KP_PLUS: app.KeyDown('+'); break;
		case SDLK_KP_MINUS: app.KeyDown('-'); break;
		case SDLK_LSHIFT: case SDLK_RSHIFT: app.KeyDown(GlosmViewer::SHIFT); break;
		case SDLK_LCTRL: case SDLK_RCTRL: app.KeyDown(GlosmViewer::CTRL); break;
		default: break;
		}
}

void KeyUp(SDLKey key) {
	if (key < 0x100)
		app.KeyUp(key);
	else
		switch(key) {
		case SDLK_UP: app.KeyUp(GlosmViewer::UP); break;
		case SDLK_DOWN: app.KeyUp(GlosmViewer::DOWN); break;
		case SDLK_LEFT: app.KeyUp(GlosmViewer::LEFT); break;
		case SDLK_RIGHT: app.KeyUp(GlosmViewer::RIGHT); break;
		case SDLK_KP_PLUS: app.KeyUp('+'); break;
		case SDLK_KP_MINUS: app.KeyUp('-'); break;
		case SDLK_LSHIFT: case SDLK_RSHIFT: app.KeyUp(GlosmViewer::SHIFT); break;
		case SDLK_LCTRL: case SDLK_RCTRL: app.KeyUp(GlosmViewer::CTRL); break;
		default: break;
		}
}

void Cleanup() {
#if defined(WITH_GLES)
	if (gles_context)
		SDL_GLES_DeleteContext(gles_context);
#endif
	SDL_Quit();
}

int GetEvents() {
	SDL_Event event;

	while (SDL_PollEvent(&event)) {
		int ret = 1;
		switch(event.type) {
		case SDL_QUIT:
			return 0;
		case SDL_KEYDOWN:
			KeyDown(event.key.keysym.sym);
			break;
		case SDL_KEYUP:
			KeyUp(event.key.keysym.sym);
			break;
		case SDL_MOUSEMOTION:
			app.MouseMove(event.motion.x, event.motion.y);
			break;
		case SDL_VIDEORESIZE:
			Reshape(event.resize.w, event.resize.h);
			break;
		default:
			break;
		}

		if (ret == 0)
			return 0;
	}

	return 1;
}

int real_main(int argc, char** argv) {
	app.Init(argc, argv);

	/* glut init */
	if (SDL_Init(SDL_INIT_VIDEO) != 0)
		throw Exception() << "Couldn't initialize SDL: " << (const char*)SDL_GetError();

	atexit(Cleanup);

#if !defined(WITH_GLES)
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLEBUFFERS, 1);
	SDL_GL_SetAttribute(SDL_GL_MULTISAMPLESAMPLES, 4);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);

	Reshape(800, 600);
#else
	/* Using fixed resolution for N900
	 * it should be detected on the fly instead */
	SDL_SetVideoMode(800, 480, 0, SDL_SWSURFACE | SDL_FULLSCREEN);

	SDL_GLES_Init(SDL_GLES_VERSION_1_1);

	SDL_GLES_SetAttribute(SDL_GLES_DEPTH_SIZE, 24);

	gles_context = SDL_GLES_CreateContext();

	SDL_GLES_MakeCurrent(gles_context);

	Reshape(800, 480);
#endif

	SDL_ShowCursor(SDL_DISABLE);
	SDL_EnableKeyRepeat(0, 0);

	app.InitGL();

	/* main loop */
	while (GetEvents())
		app.Render();

	return 0;
}

int main(int argc, char** argv) {
	try {
		return real_main(argc, argv);
	} catch (std::exception &e) {
		fprintf(stderr, "Exception: %s\n", e.what());
	} catch (...) {
		fprintf(stderr, "Unknown exception\n");
	}

	return 1;
}
<|endoftext|>


<commit_before>// Copyright (c) 2014, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
//    conditions and the following disclaimer.
//
// 2. 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.
//
// 3. Neither the name of the copyright holder 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 HOLDER 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.

#include "include_base_utils.h"
#include "common/util.h"
#include "warnings.h"
#include "crypto/crypto.h"
#include "cryptonote_config.h"
#include "cryptonote_core/cryptonote_format_utils.h"
#include "misc_language.h"
#include "cryptonote_core/blockchain_storage.h"
#include "cryptonote_core/blockchain_db.h"
#include "cryptonote_core/blockchain.h"
#include "cryptonote_core/BlockchainDB_impl/db_lmdb.h"
#include "cryptonote_core/tx_pool.h"
#include <iostream>

using namespace cryptonote;

struct fake_core
{
  tx_memory_pool m_pool;
  Blockchain dummy;

  blockchain_storage m_storage;

  fake_core() : m_pool(dummy), dummy(m_pool), m_storage(&m_pool)
  {
    boost::filesystem::path default_data_path {tools::get_default_data_dir()};
    m_pool.init(default_data_path.string());
    m_storage.init(default_data_path.string(), false);
  }
};

int main(int argc, char* argv[])
{
  fake_core c;
  boost::filesystem::path default_data_path {tools::get_default_data_dir()};

  BlockchainDB *blockchain;

  blockchain = new BlockchainLMDB();

  blockchain->open(default_data_path.string());

  for (uint64_t i = 0; i < c.m_storage.get_current_blockchain_height(); ++i)
  {
    if (i % 10 == 0) std::cout << "block " << i << std::endl;
    block b = c.m_storage.get_block(i);
    size_t bsize = c.m_storage.get_block_size(i);
    difficulty_type bdiff = c.m_storage.get_block_cumulative_difficulty(i);
    uint64_t bcoins = c.m_storage.get_block_coins_generated(i);
    std::vector<transaction> txs;
    std::vector<crypto::hash> missed;

    c.m_storage.get_transactions(b.tx_hashes, txs, missed);
    if (missed.size())
    {
      std::cerr << "Missed transaction(s) for block at height " << i << ", exiting" << std::endl;
      delete blockchain;
      return 1;
    }

    try
    {
      blockchain->add_block(b, bsize, bdiff, bcoins, txs);
    }
    catch (const std::exception& e)
    {
      std::cerr << "Error adding block to new blockchain: " << e.what() << std::endl;
      delete blockchain;
      return 2;
    }
  }

  return 0;
}
<commit_msg>blockchain_converter: delete blockchain on succesful exit<commit_after>// Copyright (c) 2014, The Monero Project
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification, are
// permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this list of
//    conditions and the following disclaimer.
//
// 2. 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.
//
// 3. Neither the name of the copyright holder 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 HOLDER 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.

#include "include_base_utils.h"
#include "common/util.h"
#include "warnings.h"
#include "crypto/crypto.h"
#include "cryptonote_config.h"
#include "cryptonote_core/cryptonote_format_utils.h"
#include "misc_language.h"
#include "cryptonote_core/blockchain_storage.h"
#include "cryptonote_core/blockchain_db.h"
#include "cryptonote_core/blockchain.h"
#include "cryptonote_core/BlockchainDB_impl/db_lmdb.h"
#include "cryptonote_core/tx_pool.h"
#include <iostream>

using namespace cryptonote;

struct fake_core
{
  tx_memory_pool m_pool;
  Blockchain dummy;

  blockchain_storage m_storage;

  fake_core() : m_pool(dummy), dummy(m_pool), m_storage(&m_pool)
  {
    boost::filesystem::path default_data_path {tools::get_default_data_dir()};
    m_pool.init(default_data_path.string());
    m_storage.init(default_data_path.string(), false);
  }
};

int main(int argc, char* argv[])
{
  fake_core c;
  boost::filesystem::path default_data_path {tools::get_default_data_dir()};

  BlockchainDB *blockchain;

  blockchain = new BlockchainLMDB();

  blockchain->open(default_data_path.string());

  for (uint64_t i = 0; i < c.m_storage.get_current_blockchain_height(); ++i)
  {
    if (i % 10 == 0) std::cout << "block " << i << std::endl;
    block b = c.m_storage.get_block(i);
    size_t bsize = c.m_storage.get_block_size(i);
    difficulty_type bdiff = c.m_storage.get_block_cumulative_difficulty(i);
    uint64_t bcoins = c.m_storage.get_block_coins_generated(i);
    std::vector<transaction> txs;
    std::vector<crypto::hash> missed;

    c.m_storage.get_transactions(b.tx_hashes, txs, missed);
    if (missed.size())
    {
      std::cerr << "Missed transaction(s) for block at height " << i << ", exiting" << std::endl;
      delete blockchain;
      return 1;
    }

    try
    {
      blockchain->add_block(b, bsize, bdiff, bcoins, txs);
    }
    catch (const std::exception& e)
    {
      std::cerr << "Error adding block to new blockchain: " << e.what() << std::endl;
      delete blockchain;
      return 2;
    }
  }

  delete blockchain;
  return 0;
}
<|endoftext|>


<commit_before>#include "Game.hpp"

namespace swift
{
	const std::string errorLog = "./data/log.txt";
	const std::string defaultFontFile = "./data/fonts/DejaVuSansMono.ttf";

	enum class GameState
	{
		Play,
		MainMenu
	};

	Game::Game()
		:	logger("Alpha", errorLog),
			console(500, 200, defaultFont, "[swift2]:")
	{
		graphics = Quality::Medium;
		smoothing = false;
		verticalSync = true;
		fullScreen = false;
		resolution.x = 800;
		resolution.y = 600;
		running = false;

		// engine integral settings
		ticksPerSecond = 60;

		defaultFont.loadFromFile(defaultFontFile);
	}

	Game::~Game()
	{
		delete currentState;
		currentState = nullptr;
	}

	// Do any pre-game data loading
	// Such as setting up the scripting virtual machine
	// and setting game quality settings.
	// That's about it
	void Game::Start(int c, char** args)
	{
		// c is the total arguments
		// args is the arguments

		// loads settings from the settings file
		loadSettings("./data/settings/settings.ini");

		handleLaunchOps(c, args);

		// Window set up.
		if(fullScreen)
			window.create(sf::VideoMode(resolution.x, resolution.y, 32), "Swift Engine", sf::Style::Fullscreen, contextSettings);
		else
			window.create(sf::VideoMode(resolution.x, resolution.y, 32), "Swift Engine", sf::Style::Titlebar | sf::Style::Close, contextSettings);

		//window.setIcon(SwiftEngineIcon.width, SwiftEngineIcon.height, SwiftEngineIcon.pixel_data);
		window.setVerticalSyncEnabled(verticalSync);
		window.setKeyRepeatEnabled(false);

		assets.setSmooth(smoothing);
		assets.loadResourceFolder("./data/fonts");
		assets.loadResourceFolder("./data/textures");
		assets.loadResourceFolder("./data/music");
		assets.loadResourceFolder("./data/scripts");
		assets.loadResourceFolder("./data/skeletons");
		assets.loadResourceFolder("./data/sounds");

		mods.loadMods("./data/mods");

		for(auto &m : mods.getMods())
		{
			assets.loadMod(m.second.mod);
		}

		// add some default keybindings
		keyboard.newBinding("toggleTerminal", sf::Keyboard::BackSlash, [&]()
		{
			console.activate(!console.isActivated());
		});

		keyboard.newBinding("exit", sf::Keyboard::Escape, [&]()
		{
			running = false;
		});

		// add some console commands
		console.addCommand("hello", [](ArgVec args)
		{
			return "Hello to you too!";
		});

		console.addCommand("exit", [&](ArgVec args)
		{
			running = false;
			return "Exiting";
		});

		running = true;

		// fps display
		if(debug)
		{
			FPS.setFont(defaultFont);
			FPS.setScale(0.7, 0.7);
			FPS.setString("00");
			FPS.setPosition(window.getSize().x - (FPS.getGlobalBounds().width + 2), 0);
		}

		// setup Script static variables
		Script::setWindow(window);

		// state setup
		currentState = new MainMenu(window, assets, defaultFont);
		currentState->setup();
		currentState->switchTo();
	}

	void Game::GameLoop()
	{
		const sf::Time dt = sf::seconds(1 / ticksPerSecond);

		sf::Time currentTime = GameTime.getElapsedTime();
		sf::Time lag = sf::seconds(0);

		while(running)
		{
			sf::Time newTime = GameTime.getElapsedTime();
			sf::Time frameTime = newTime - currentTime;

			if(frameTime > sf::seconds(0.25))
				frameTime = sf::seconds(0.25);

			currentTime = newTime;

			lag += frameTime;

			while(lag >= dt)
			{
				Update(dt);
				lag -= dt;
			}

			Draw(lag.asSeconds() / dt.asSeconds());
		}
	}

	void Game::Update(sf::Time dt)
	{
		sf::Event event;
		while(window.pollEvent(event))
		{
			keyboard(event);
			mouse(event);

			// avoid having the console type the key that toggles it
			if(event.type == sf::Event::TextEntered && event.text.unicode != '\\')
				console.update(event);

			if(event.type == sf::Event::Closed)
				running = false;

			currentState->handleEvent(event);
		}

		if(debug)
			FPS.setString(std::to_string(1 / dt.asSeconds()).substr(0, 2));

		currentState->update(dt);
	}

	void Game::manageStates()
	{

	}

	void Game::Draw(float e)
	{
		/* clear display */
		window.clear();

		/* state drawing */
		currentState->draw(e);

		/* other drawing */
		window.draw(console);
		if(debug)
			window.draw(FPS);

		/* display drawing */
		window.display();
	}

	// Finish cleaning up memory, close cleanly, etc
	void Game::Finish()
	{
		window.close();
	}

	void Game::handleLaunchOps(int c, char** args)
	{
		// launch options
		editor = false;
		debug = false;
		fullScreen = false;

		// loop through options
		int arg = 1;	// we skip arg 0 because arg 0 is the executable
		while(arg < c)
		{
			if(args[arg] == std::string("editor"))
			{
				editor = true;
			}
			else if(args[arg] == std::string("debug"))
			{
				debug = true;
			}
			else if(args[arg] == std::string("fullscreen"))
			{
				fullScreen = true;
			}
			else if(args[arg] == std::string("res"))
			{
				resolution.x = std::stoi(args[arg + 1]);
				resolution.y = std::stoi(args[arg + 1]);
				arg += 2;
			}
			else if(args[arg] == std::string("videoModes"))
			{
				logger << Logger::LogType::INFO << "Supported Fullscreen Video Modes:";

				std::vector<sf::VideoMode> modes = sf::VideoMode::getFullscreenModes();
				for(std::size_t i = 0; i < modes.size(); ++i)
				{
					sf::VideoMode mode = modes[i];
					logger 	<< Logger::LogType::INFO
					        << "Mode #" + std::to_string(i) + ": " + std::to_string(mode.width) + "x" + std::to_string(mode.height)
					        + " - " + std::to_string(mode.bitsPerPixel) + " bpp";
					// ex: "Mode #0: 1920x1080 - 32 bbp"
				}
			}
			else
			{
				logger << "\nUnknown launch option: " + std::string(args[arg]) + '\n';
			}

			arg++;
		}
	}

	void Game::loadSettings(const std::string& file)
	{
		// settings file settings
		if(!settings.loadFile(file))
			logger << Logger::LogType::WARNING << "Could not open settings file, default settings will be used\n";

		settings.get("quality", graphics);
		settings.get("fullScreen", fullScreen);
		settings.get("vertSync", verticalSync);
		settings.get("res.x", resolution.x);
		settings.get("res.y", resolution.y);
		settings.get("sound", soundLevel);
		settings.get("music", musicLevel);
	}
}
<commit_msg>General Cleaning<commit_after>#include "Game.hpp"

namespace swift
{
	const std::string errorLog = "./data/log.txt";
	const std::string defaultFontFile = "./data/fonts/DejaVuSansMono.ttf";

	enum class GameState
	{
	    Play,
	    MainMenu
	};

	Game::Game()
		:	logger("Alpha", errorLog),
		    console(500, 200, defaultFont, "[swift2]:")
	{
		graphics = Quality::Medium;
		smoothing = false;
		verticalSync = true;
		fullScreen = false;
		resolution.x = 800;
		resolution.y = 600;
		running = false;

		// engine integral settings
		ticksPerSecond = 60;

		defaultFont.loadFromFile(defaultFontFile);
	}

	Game::~Game()
	{
		if(currentState)
			delete currentState;
	}

	// Do any pre-game data loading
	// Such as setting up the scripting virtual machine
	// and setting game quality settings.
	// That's about it
	void Game::Start(int c, char** args)
	{
		// c is the total arguments
		// args is the arguments

		// loads settings from the settings file
		loadSettings("./data/settings/settings.ini");

		handleLaunchOps(c, args);

		// Window set up.
		if(fullScreen)
			window.create(sf::VideoMode(resolution.x, resolution.y, 32), "Swift Engine", sf::Style::Fullscreen, contextSettings);
		else
			window.create(sf::VideoMode(resolution.x, resolution.y, 32), "Swift Engine", sf::Style::Titlebar | sf::Style::Close, contextSettings);

		//window.setIcon(SwiftEngineIcon.width, SwiftEngineIcon.height, SwiftEngineIcon.pixel_data);
		window.setVerticalSyncEnabled(verticalSync);
		window.setKeyRepeatEnabled(false);

		assets.setSmooth(smoothing);
		assets.loadResourceFolder("./data/fonts");
		assets.loadResourceFolder("./data/textures");
		assets.loadResourceFolder("./data/music");
		assets.loadResourceFolder("./data/scripts");
		assets.loadResourceFolder("./data/skeletons");
		assets.loadResourceFolder("./data/sounds");

		mods.loadMods("./data/mods");

		for(auto &m : mods.getMods())
		{
			assets.loadMod(m.second.mod);
		}

		// add some default keybindings
		keyboard.newBinding("toggleTerminal", sf::Keyboard::BackSlash, [&]()
		{
			console.activate(!console.isActivated());
		});

		keyboard.newBinding("exit", sf::Keyboard::Escape, [&]()
		{
			running = false;
		});

		// add some console commands
		console.addCommand("hello", [](ArgVec args)
		{
			return "Hello to you too!";
		});

		console.addCommand("exit", [&](ArgVec args)
		{
			running = false;
			return "Exiting";
		});

		running = true;

		// fps display
		if(debug)
		{
			FPS.setFont(defaultFont);
			FPS.setScale(0.7, 0.7);
			FPS.setString("00");
			FPS.setPosition(window.getSize().x - (FPS.getGlobalBounds().width + 2), 0);
		}

		// setup Script static variables
		Script::setWindow(window);

		// state setup
		currentState = new MainMenu(window, assets);
		currentState->setup();
	}

	void Game::GameLoop()
	{
		const sf::Time dt = sf::seconds(1 / ticksPerSecond);

		sf::Time currentTime = GameTime.getElapsedTime();
		sf::Time lag = sf::seconds(0);

		while(running)
		{
			sf::Time newTime = GameTime.getElapsedTime();
			sf::Time frameTime = newTime - currentTime;

			if(frameTime > sf::seconds(0.25))
				frameTime = sf::seconds(0.25);

			currentTime = newTime;

			lag += frameTime;

			while(lag >= dt)
			{
				Update(dt);
				lag -= dt;
			}

			Draw(lag.asSeconds() / dt.asSeconds());
		}
	}

	void Game::Update(sf::Time dt)
	{
		sf::Event event;
		while(window.pollEvent(event))
		{
			keyboard(event);
			mouse(event);

			// avoid having the console type the key that toggles it
			if(event.type == sf::Event::TextEntered && event.text.unicode != '\\')
				console.update(event);

			if(event.type == sf::Event::Closed)
				running = false;

			currentState->handleEvent(event);
		}

		if(debug)
			FPS.setString(std::to_string(1 / dt.asSeconds()).substr(0, 2));

		currentState->update(dt);
		manageStates();
	}

	void Game::manageStates()
	{
		if(currentState->switchFrom())
		{
			State::Type nextState = currentState->finish();
			delete currentState;
			currentState = nullptr;

			switch(nextState)
			{
				case State::Type::MainMenu:
					currentState = new MainMenu(window, assets);
					currentState->setup();
					break;
				case State::Type::Play:
					currentState = new Play(window, assets);
					currentState->setup();
					break;
				case State::Type::Exit:
					running = false;
					break;
			}
		}
	}

	void Game::Draw(float e)
	{
		if(running)
		{
			/* clear display */
			window.clear();

			/* state drawing */
			currentState->draw(e);

			/* other drawing */
			window.draw(console);
			if(debug)
				window.draw(FPS);

			/* display drawing */
			window.display();
		}
	}

	// Finish cleaning up memory, close cleanly, etc
	void Game::Finish()
	{
		window.close();
	}

	void Game::handleLaunchOps(int c, char** args)
	{
		// launch options
		editor = false;
		debug = false;
		fullScreen = false;

		// loop through options
		int arg = 1;	// we skip arg 0 because arg 0 is the executable
		while(arg < c)
		{
			if(args[arg] == std::string("editor"))
			{
				editor = true;
			}
			else if(args[arg] == std::string("debug"))
			{
				debug = true;
			}
			else if(args[arg] == std::string("fullscreen"))
			{
				fullScreen = true;
			}
			else if(args[arg] == std::string("res"))
			{
				resolution.x = std::stoi(args[arg + 1]);
				resolution.y = std::stoi(args[arg + 1]);
				arg += 2;
			}
			else if(args[arg] == std::string("videoModes"))
			{
				logger << Logger::LogType::INFO << "Supported Fullscreen Video Modes:";

				std::vector<sf::VideoMode> modes = sf::VideoMode::getFullscreenModes();
				for(std::size_t i = 0; i < modes.size(); ++i)
				{
					sf::VideoMode mode = modes[i];
					logger 	<< Logger::LogType::INFO
					        << "Mode #" + std::to_string(i) + ": " + std::to_string(mode.width) + "x" + std::to_string(mode.height)
					        + " - " + std::to_string(mode.bitsPerPixel) + " bpp";
					// ex: "Mode #0: 1920x1080 - 32 bbp"
				}
			}
			else
			{
				logger << "\nUnknown launch option: " + std::string(args[arg]) + '\n';
			}

			arg++;
		}
	}

	void Game::loadSettings(const std::string& file)
	{
		// settings file settings
		if(!settings.loadFile(file))
			logger << Logger::LogType::WARNING << "Could not open settings file, default settings will be used\n";

		settings.get("quality", graphics);
		settings.get("fullScreen", fullScreen);
		settings.get("vertSync", verticalSync);
		settings.get("res.x", resolution.x);
		settings.get("res.y", resolution.y);
		settings.get("sound", soundLevel);
		settings.get("music", musicLevel);
	}
}
<|endoftext|>