<commit_before>#include "Moves/Threat_Iterator.h"

#include "Game/Board.h"
#include "Game/Square.h"
#include "Game/Color.h"
#include "Game/Piece.h"

Threat_Iterator::Threat_Iterator(char target_file_in,
                                 int  target_rank_in,
                                 Color attack_color,
                                 const Board& reference_board) :
    target_file(target_file_in),
    target_rank(target_rank_in),
    file_step(-1),
    rank_step(-2),
    on_knight_moves(false),
    hit_count(0),
    max_hit_count(3),
    attacking_color(attack_color),
    board(reference_board),
    target_king(reference_board.piece_instance(KING, opposite(attack_color)))
{
    next_threat();
}

void Threat_Iterator::operator++()
{
    next_threat();
}

Square Threat_Iterator::operator*() const
{
    return {attacking_file(), attacking_rank()};
}

bool Threat_Iterator::operator==(const Threat_Iterator& other) const
{
    return hit_count == other.hit_count;
}

bool Threat_Iterator::operator!=(const Threat_Iterator& other) const
{
    return ! (*this == other);
}

char Threat_Iterator::attacking_file() const
{
    return attack_file;
}

int Threat_Iterator::attacking_rank() const
{
    return attack_rank;
}

void Threat_Iterator::next_threat()
{
    if(++hit_count == max_hit_count)
    {
        return;
    }

    ++rank_step;

    for( ; ! on_knight_moves && file_step <= 1; ++file_step)
    {
        for( ; rank_step <= 1; ++rank_step)
        {
            // Filter non-moves
            if(file_step == 0 && rank_step == 0)
            {
                continue;
            }

            for(int step_size = 1 ; step_size <= 7; ++step_size)
            {
                attack_file = target_file + file_step*step_size;
                attack_rank = target_rank + rank_step*step_size;

                if( ! board.inside_board(attack_file, attack_rank))
                {
                    break; // go to next direction
                }

                auto piece = board.piece_on_square(attack_file, attack_rank);
                if(( ! piece) || piece == target_king)
                {
                    continue;
                }

                if(piece->color() != attacking_color)
                {
                    break;
                }

                if(piece->type() == QUEEN)
                {
                    return;
                }

                if(piece->type() == KING && step_size == 1)
                {
                    return;
                }

                if(rank_step == 0 || file_step == 0)
                {
                    if(piece->type() == ROOK)
                    {
                        return;
                    }
                }
                else
                {
                    if(piece->type() == BISHOP)
                    {
                        return;
                    }

                    if(piece->type() == PAWN && step_size == 1 && rank_step == (attacking_color == WHITE ? -1 : 1))
                    {
                        return;
                    }
                }

                break; // Piece on square blocks farther movements
            }
        }

        rank_step = -1;
    }

    on_knight_moves = true;

    for(file_step = 1 ; file_step <= 2; ++file_step)
    {
        rank_step = 3 - file_step;
        for(int file_direction = -1 ; file_direction <= 1; file_direction += 2)
        {
            attack_file = target_file + file_step*file_direction;
            if( ! Board::inside_board(attack_file))
            {
                continue;
            }

            for(int rank_direction = -1; rank_direction <= 1; rank_direction += 2)
            {
                attack_rank = target_rank + rank_step*rank_direction;
                if( ! Board::inside_board(attack_rank))
                {
                    continue;
                }

                auto knight = Board::piece_instance(KNIGHT, attacking_color);
                if(board.piece_on_square(attack_file, attack_rank) == knight)
                {
                    // Cannot have more than one knight checking the king
                    hit_count = max_hit_count - 1;
                    return;
                }
            }
        }
    }

    convert_to_end_iterator();
}

Threat_Iterator Threat_Iterator::make_end_iterator() const
{
    auto end = *this;
    end.convert_to_end_iterator();
    return end;
}

void Threat_Iterator::convert_to_end_iterator()
{
    hit_count = max_hit_count;
}
<commit_msg>Only call methods once<commit_after>#include "Moves/Threat_Iterator.h"

#include "Game/Board.h"
#include "Game/Square.h"
#include "Game/Color.h"
#include "Game/Piece.h"

Threat_Iterator::Threat_Iterator(char target_file_in,
                                 int  target_rank_in,
                                 Color attack_color,
                                 const Board& reference_board) :
    target_file(target_file_in),
    target_rank(target_rank_in),
    file_step(-1),
    rank_step(-2),
    on_knight_moves(false),
    hit_count(0),
    max_hit_count(3),
    attacking_color(attack_color),
    board(reference_board),
    target_king(reference_board.piece_instance(KING, opposite(attack_color)))
{
    next_threat();
}

void Threat_Iterator::operator++()
{
    next_threat();
}

Square Threat_Iterator::operator*() const
{
    return {attacking_file(), attacking_rank()};
}

bool Threat_Iterator::operator==(const Threat_Iterator& other) const
{
    return hit_count == other.hit_count;
}

bool Threat_Iterator::operator!=(const Threat_Iterator& other) const
{
    return ! (*this == other);
}

char Threat_Iterator::attacking_file() const
{
    return attack_file;
}

int Threat_Iterator::attacking_rank() const
{
    return attack_rank;
}

void Threat_Iterator::next_threat()
{
    if(++hit_count == max_hit_count)
    {
        return;
    }

    ++rank_step;

    for( ; ! on_knight_moves && file_step <= 1; ++file_step)
    {
        for( ; rank_step <= 1; ++rank_step)
        {
            // Filter non-moves
            if(file_step == 0 && rank_step == 0)
            {
                continue;
            }

            for(int step_size = 1 ; step_size <= 7; ++step_size)
            {
                attack_file = target_file + file_step*step_size;
                attack_rank = target_rank + rank_step*step_size;

                if( ! board.inside_board(attack_file, attack_rank))
                {
                    break; // go to next direction
                }

                auto piece = board.piece_on_square(attack_file, attack_rank);
                if(( ! piece) || piece == target_king)
                {
                    continue;
                }

                if(piece->color() != attacking_color)
                {
                    break;
                }

                auto piece_type = piece->type();
                if(piece_type == QUEEN)
                {
                    return;
                }

                if(piece_type == KING && step_size == 1)
                {
                    return;
                }

                if(rank_step == 0 || file_step == 0)
                {
                    if(piece_type == ROOK)
                    {
                        return;
                    }
                }
                else
                {
                    if(piece_type == BISHOP)
                    {
                        return;
                    }

                    if(piece_type == PAWN && step_size == 1 && rank_step == (attacking_color == WHITE ? -1 : 1))
                    {
                        return;
                    }
                }

                break; // Piece on square blocks farther movements
            }
        }

        rank_step = -1;
    }

    on_knight_moves = true;

    for(file_step = 1 ; file_step <= 2; ++file_step)
    {
        rank_step = 3 - file_step;
        for(int file_direction = -1 ; file_direction <= 1; file_direction += 2)
        {
            attack_file = target_file + file_step*file_direction;
            if( ! Board::inside_board(attack_file))
            {
                continue;
            }

            for(int rank_direction = -1; rank_direction <= 1; rank_direction += 2)
            {
                attack_rank = target_rank + rank_step*rank_direction;
                if( ! Board::inside_board(attack_rank))
                {
                    continue;
                }

                auto knight = Board::piece_instance(KNIGHT, attacking_color);
                if(board.piece_on_square(attack_file, attack_rank) == knight)
                {
                    // Cannot have more than one knight checking the king
                    hit_count = max_hit_count - 1;
                    return;
                }
            }
        }
    }

    convert_to_end_iterator();
}

Threat_Iterator Threat_Iterator::make_end_iterator() const
{
    auto end = *this;
    end.convert_to_end_iterator();
    return end;
}

void Threat_Iterator::convert_to_end_iterator()
{
    hit_count = max_hit_count;
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2013 PX4 Development Team. 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 PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

 /**
  * @file px4io_i2c.cpp
  *
  * I2C interface for PX4IO
  */

/* XXX trim includes */
#include <nuttx/config.h>

#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
#include <debug.h>
#include <errno.h>
#include <unistd.h>

#include <arch/board/board.h>

#include <drivers/device/i2c.h>

#ifdef PX4_I2C_OBDEV_PX4IO

device::Device	*PX4IO_i2c_interface();

class PX4IO_I2C : public device::I2C
{
public:
	PX4IO_I2C(int bus, uint8_t address);
	virtual ~PX4IO_I2C();

	virtual int	init();
	virtual int	read(unsigned offset, void *data, unsigned count = 1);
	virtual int	write(unsigned address, void *data, unsigned count = 1);
	virtual int	ioctl(unsigned operation, unsigned &arg);

private:

};

device::Device
*PX4IO_i2c_interface()
{
	return new PX4IO_I2C(PX4_I2C_BUS_ONBOARD, PX4_I2C_OBDEV_PX4IO);
}

PX4IO_I2C::PX4IO_I2C(int bus, uint8_t address) :
	I2C("PX4IO_i2c", nullptr, bus, address, 320000)
{
	_retries = 3;
}

PX4IO_I2C::~PX4IO_I2C()
{
}

int
PX4IO_I2C::init()
{
	int ret;

	ret = I2C::init();
	if (ret != OK)
		goto out;

	/* XXX really should do something more here */

out:
	return 0;
}

int
PX4IO_I2C::ioctl(unsigned operation, unsigned &arg)
{
	return 0;
}

int
PX4IO_I2C::write(unsigned address, void *data, unsigned count)
{
	uint8_t page = address >> 8;
	uint8_t offset = address & 0xff;
	const uint16_t *values = reinterpret_cast<const uint16_t *>(data);

	/* set up the transfer */
	uint8_t 	addr[2] = {
		page,
		offset
	};

	i2c_msg_s	msgv[2];

	msgv[0].flags = 0;
	msgv[0].buffer = addr;
	msgv[0].length = 2;

	msgv[1].flags = I2C_M_NORESTART;
	msgv[1].buffer = (uint8_t *)values;
	msgv[1].length = 2 * count;

	int ret = transfer(msgv, 2);
	if (ret == OK)
		ret = count;
	return ret;
}

int
PX4IO_I2C::read(unsigned address, void *data, unsigned count)
{
	uint8_t page = address >> 8;
	uint8_t offset = address & 0xff;
	const uint16_t *values = reinterpret_cast<const uint16_t *>(data);

	/* set up the transfer */
	uint8_t		addr[2] = {
		page,
		offset
	};
	i2c_msg_s	msgv[2];

	msgv[0].flags = 0;
	msgv[0].buffer = addr;
	msgv[0].length = 2;

	msgv[1].flags = I2C_M_READ;
	msgv[1].buffer = (uint8_t *)values;
	msgv[1].length = 2 * count;

	int ret = transfer(msgv, 2);
	if (ret == OK)
		ret = count;
	return ret;
}

#endif /* PX4_I2C_OBDEV_PX4IO */<commit_msg>px4io: include board_config.h<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2013 PX4 Development Team. 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 PX4 nor the names of its contributors may be
 *    used to endorse or promote products derived from this software
 *    without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
 * OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGE.
 *
 ****************************************************************************/

 /**
  * @file px4io_i2c.cpp
  *
  * I2C interface for PX4IO
  */

/* XXX trim includes */
#include <nuttx/config.h>

#include <sys/types.h>
#include <stdint.h>
#include <stdbool.h>
#include <assert.h>
#include <debug.h>
#include <errno.h>
#include <unistd.h>

#include <arch/board/board.h>
#include <board_config.h>

#include <drivers/device/i2c.h>

#ifdef PX4_I2C_OBDEV_PX4IO

device::Device	*PX4IO_i2c_interface();

class PX4IO_I2C : public device::I2C
{
public:
	PX4IO_I2C(int bus, uint8_t address);
	virtual ~PX4IO_I2C();

	virtual int	init();
	virtual int	read(unsigned offset, void *data, unsigned count = 1);
	virtual int	write(unsigned address, void *data, unsigned count = 1);
	virtual int	ioctl(unsigned operation, unsigned &arg);

private:

};

device::Device
*PX4IO_i2c_interface()
{
	return new PX4IO_I2C(PX4_I2C_BUS_ONBOARD, PX4_I2C_OBDEV_PX4IO);
}

PX4IO_I2C::PX4IO_I2C(int bus, uint8_t address) :
	I2C("PX4IO_i2c", nullptr, bus, address, 320000)
{
	_retries = 3;
}

PX4IO_I2C::~PX4IO_I2C()
{
}

int
PX4IO_I2C::init()
{
	int ret;

	ret = I2C::init();
	if (ret != OK)
		goto out;

	/* XXX really should do something more here */

out:
	return 0;
}

int
PX4IO_I2C::ioctl(unsigned operation, unsigned &arg)
{
	return 0;
}

int
PX4IO_I2C::write(unsigned address, void *data, unsigned count)
{
	uint8_t page = address >> 8;
	uint8_t offset = address & 0xff;
	const uint16_t *values = reinterpret_cast<const uint16_t *>(data);

	/* set up the transfer */
	uint8_t 	addr[2] = {
		page,
		offset
	};

	i2c_msg_s	msgv[2];

	msgv[0].flags = 0;
	msgv[0].buffer = addr;
	msgv[0].length = 2;

	msgv[1].flags = I2C_M_NORESTART;
	msgv[1].buffer = (uint8_t *)values;
	msgv[1].length = 2 * count;

	int ret = transfer(msgv, 2);
	if (ret == OK)
		ret = count;
	return ret;
}

int
PX4IO_I2C::read(unsigned address, void *data, unsigned count)
{
	uint8_t page = address >> 8;
	uint8_t offset = address & 0xff;
	const uint16_t *values = reinterpret_cast<const uint16_t *>(data);

	/* set up the transfer */
	uint8_t		addr[2] = {
		page,
		offset
	};
	i2c_msg_s	msgv[2];

	msgv[0].flags = 0;
	msgv[0].buffer = addr;
	msgv[0].length = 2;

	msgv[1].flags = I2C_M_READ;
	msgv[1].buffer = (uint8_t *)values;
	msgv[1].length = 2 * count;

	int ret = transfer(msgv, 2);
	if (ret == OK)
		ret = count;
	return ret;
}

#endif /* PX4_I2C_OBDEV_PX4IO */
<|endoftext|>


<commit_before>/*
 * AscEmu Framework based on ArcEmu MMORPG Server
 * Copyright (C) 2014-2016 AscEmu Team <http://www.ascemu.org/>
 * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/>
 * Copyright (C) 2005-2007 Ascent Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "CObjectFactory.h"
#include "ObjectStorage.h"

GameObject* CObjectFactory::CreateGameObject(uint32 Id, uint32 LowGUID)
{
    GameObjectInfo* gameobject_info = GameObjectNameStorage.LookupEntry(Id);
    if (gameobject_info == NULL)
        return NULL;

    GameObject* gameobject = nullptr;

    uint64 GUID = uint64((uint64(HIGHGUID_TYPE_GAMEOBJECT) << 32) | LowGUID);

    switch (gameobject_info->type)
    {

        case GAMEOBJECT_TYPE_DOOR:
            gameobject = new GameObject_Door(GUID);
            break;

        case GAMEOBJECT_TYPE_BUTTON:
            gameobject = new GameObject_Button(GUID);
            break;

        case GAMEOBJECT_TYPE_QUESTGIVER:
            gameobject = new GameObject_QuestGiver(GUID);
            break;

        case GAMEOBJECT_TYPE_CHEST:
            gameobject = new GameObject_Chest(GUID);
            break;

        case GAMEOBJECT_TYPE_TRAP:
            gameobject = new GameObject_Trap(GUID);
            break;

        case GAMEOBJECT_TYPE_SPELL_FOCUS:
            gameobject = new GameObject_SpellFocus(GUID);
            break;

        case GAMEOBJECT_TYPE_GOOBER:
            gameobject = new GameObject_Goober(GUID);
            break;

        case GAMEOBJECT_TYPE_FISHINGNODE:
            gameobject = new GameObject_FishingNode(GUID);
            break;

        case GAMEOBJECT_TYPE_RITUAL:
            gameobject = new GameObject_Ritual(GUID);
            break;

        case GAMEOBJECT_TYPE_SPELLCASTER:
            gameobject = new GameObject_SpellCaster(GUID);
            break;

        case GAMEOBJECT_TYPE_FISHINGHOLE:
            gameobject = new GameObject_FishingHole(GUID);
            break;

        case GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING:
            gameobject = new GameObject_Destructible(GUID);
            break;

        default:
            gameobject = new GameObject(GUID);
            break;
    }

    gameobject->SetInfo(gameobject_info);

    return gameobject;
}

void CObjectFactory::DisposeOf(Object* obj)
{
    delete obj;
}
<commit_msg>Travis: Header includes<commit_after>/*
 * AscEmu Framework based on ArcEmu MMORPG Server
 * Copyright (C) 2014-2016 AscEmu Team <http://www.ascemu.org/>
 * Copyright (C) 2008-2012 ArcEmu Team <http://www.ArcEmu.org/>
 * Copyright (C) 2005-2007 Ascent Team
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 *
 */

#include "CObjectFactory.h"
#include "Object.h"
#include "ObjectStorage.h"

GameObject* CObjectFactory::CreateGameObject(uint32 Id, uint32 LowGUID)
{
    GameObjectInfo* gameobject_info = GameObjectNameStorage.LookupEntry(Id);
    if (gameobject_info == NULL)
        return NULL;

    GameObject* gameobject = nullptr;

    uint64 GUID = uint64((uint64(HIGHGUID_TYPE_GAMEOBJECT) << 32) | LowGUID);

    switch (gameobject_info->type)
    {

        case GAMEOBJECT_TYPE_DOOR:
            gameobject = new GameObject_Door(GUID);
            break;

        case GAMEOBJECT_TYPE_BUTTON:
            gameobject = new GameObject_Button(GUID);
            break;

        case GAMEOBJECT_TYPE_QUESTGIVER:
            gameobject = new GameObject_QuestGiver(GUID);
            break;

        case GAMEOBJECT_TYPE_CHEST:
            gameobject = new GameObject_Chest(GUID);
            break;

        case GAMEOBJECT_TYPE_TRAP:
            gameobject = new GameObject_Trap(GUID);
            break;

        case GAMEOBJECT_TYPE_SPELL_FOCUS:
            gameobject = new GameObject_SpellFocus(GUID);
            break;

        case GAMEOBJECT_TYPE_GOOBER:
            gameobject = new GameObject_Goober(GUID);
            break;

        case GAMEOBJECT_TYPE_FISHINGNODE:
            gameobject = new GameObject_FishingNode(GUID);
            break;

        case GAMEOBJECT_TYPE_RITUAL:
            gameobject = new GameObject_Ritual(GUID);
            break;

        case GAMEOBJECT_TYPE_SPELLCASTER:
            gameobject = new GameObject_SpellCaster(GUID);
            break;

        case GAMEOBJECT_TYPE_FISHINGHOLE:
            gameobject = new GameObject_FishingHole(GUID);
            break;

        case GAMEOBJECT_TYPE_DESTRUCTIBLE_BUILDING:
            gameobject = new GameObject_Destructible(GUID);
            break;

        default:
            gameobject = new GameObject(GUID);
            break;
    }

    gameobject->SetInfo(gameobject_info);

    return gameobject;
}

void CObjectFactory::DisposeOf(Object* obj)
{
    delete obj;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: insys.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2006-04-07 14:37:42 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#if defined( WNT )

#include "inwnt.cxx"

#elif defined( MAC )

#include "inmac.cxx"

#elif defined( UNX )

#include "inunx.cxx"

#else

#error unknown platform

#endif
<commit_msg>INTEGRATION: CWS pchfix02 (1.2.38); FILE MERGED 2006/09/01 17:30:44 kaib 1.2.38.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: insys.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 09:20:22 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_i18npool.hxx"

#if defined( WNT )

#include "inwnt.cxx"

#elif defined( MAC )

#include "inmac.cxx"

#elif defined( UNX )

#include "inunx.cxx"

#else

#error unknown platform

#endif
<|endoftext|>


<commit_before>#include "BitFunnel/Allocators/IAllocator.h"
// #include "BitFunnel/CompiledFunction.h"
#include "BitFunnel/IDiagnosticStream.h"
#include "BitFunnel/Plan/IPlanRows.h"
// #include "BitFunnel/IThreadResources.h"
#include "BitFunnel/Plan/QueryPlanner.h"
#include "BitFunnel/Plan/RowPlan.h"
#include "BitFunnel/Plan/TermMatchNode.h"
#include "BitFunnel/Plan/TermPlan.h"
#include "BitFunnel/Plan/TermPlanConverter.h"
#include "BitFunnel/Utilities/Factories.h"
#include "BitFunnel/Utilities/IObjectFormatter.h"
#include "CompileNode.h"
#include "LoggerInterfaces/Logging.h"
// #include "MatchTreeCodeGenerator.h"
#include "MatchTreeRewriter.h"
#include "RankDownCompiler.h"
#include "RegisterAllocator.h"

namespace BitFunnel
{
    // QueryPlanner::X64FunctionGeneratorWrapper::X64FunctionGeneratorWrapper(IThreadResources& threadResources)
    //     : m_code(threadResources.AllocateFunctionGenerator()),
    //       m_threadResources(threadResources)
    // {
    // }

    // QueryPlanner::X64FunctionGeneratorWrapper::~X64FunctionGeneratorWrapper()
    // {
    //     m_threadResources.ReleaseFunctionGenerator(m_code);
    // }

    // QueryPlanner::X64FunctionGeneratorWrapper::operator X64::X64FunctionGenerator&() const
    // {
    //     return m_code;
    // }

    unsigned const c_targetCrossProductTermCount = 180;

    QueryPlanner::QueryPlanner(TermPlan const & termPlan,
                               unsigned targetRowCount,
                               ISimpleIndex const & index,
                               // IThreadResources& threadResources,
                               IAllocator& allocator,
                               IDiagnosticStream* diagnosticStream)
                               // bool generateNonBodyPlan,
                               // unsigned maxIterationsScannedBetweenTerminationChecks)
    // : // m_x64FunctionGeneratorWrapper(threadResources),
    //   m_maxIterationsScannedBetweenTerminationChecks(maxIterationsScannedBetweenTerminationChecks)
    {
        if (diagnosticStream != nullptr && diagnosticStream->IsEnabled("planning/term"))
        {
            std::ostream& out = diagnosticStream->GetStream();
            // TODO: why is this an auto_ptr?
            std::auto_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream->GetStream()));

            out << "--------------------" << std::endl;
            out << "Term Plan:" << std::endl;
            termPlan.GetMatchTree().Format(*formatter);
            out << std::endl;
        }

        RowPlan const & rowPlan =
            TermPlanConverter::BuildRowPlan(termPlan.GetMatchTree(),
                                            index,
                                            // generateNonBodyPlan,
                                            allocator);

        if (diagnosticStream != nullptr && diagnosticStream->IsEnabled("planning/row"))
        {
            std::ostream& out = diagnosticStream->GetStream();
            // TODO: why is this an auto_ptr?
            std::auto_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream->GetStream()));

            out << "--------------------" << std::endl;
            out << "Row Plan:" << std::endl;
            rowPlan.Format(*formatter);
            out << std::endl;
        }

        m_planRows = &rowPlan.GetPlanRows();

        if (diagnosticStream != nullptr && diagnosticStream->IsEnabled("planning/planrows"))
        {
            std::ostream& out = diagnosticStream->GetStream();
            std::auto_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream->GetStream()));

            out << "--------------------" << std::endl;
            out << "IPlanRows:" << std::endl;
            for (ShardId shard = 0 ; shard < m_planRows->GetShardCount(); ++shard)
            {
                for (unsigned id = 0 ; id < m_planRows->GetRowCount(); ++id)
                {
                    RowId row = m_planRows->PhysicalRow(shard, id);

                    out << "(" << shard << ", " << id << "): ";
                    out << "RowId(" << row.GetShard();
                    out << ", " << row.GetRank();
                    out << ", " << row.GetIndex() << ")" << std::endl;
                }
            }
        }

        // Rewrite match tree to optimal form for the RankDownCompiler.
        RowMatchNode const & rewritten =
            MatchTreeRewriter::Rewrite(rowPlan.GetMatchTree(),
                                       targetRowCount,
                                       c_targetCrossProductTermCount,
                                       allocator);

        if (diagnosticStream != nullptr && diagnosticStream->IsEnabled("planning/rewrite"))
        {
            std::ostream& out = diagnosticStream->GetStream();
            std::auto_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream->GetStream()));

            out << "--------------------" << std::endl;
            out << "Rewritten Plan:" << std::endl;
            rewritten.Format(*formatter);
            out << std::endl;
        }

        // Compile the match tree into CompileNodes.
        RankDownCompiler compiler(allocator);
        compiler.Compile(rewritten);
        CompileNode const & compileTree = compiler.CreateTree(c_maxRankValue);

        if (diagnosticStream != nullptr && diagnosticStream->IsEnabled("planning/compile"))
        {
            std::ostream& out = diagnosticStream->GetStream();
            std::auto_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream->GetStream()));

            out << "--------------------" << std::endl;
            out << "Compile Nodes:" << std::endl;
            compileTree.Format(*formatter);
            out << std::endl;
        }

        // Perform register allocation on the compile tree.
        RegisterAllocator const registers(compileTree,
                                          rowPlan.GetPlanRows().GetRowCount(),
                                          c_registerBase,
                                          c_registerCount,
                                          allocator);

        // Finally, translate compile tree to X64 machine code.
        // MatchTreeCodeGenerator generator(registers,
        //                                  m_x64FunctionGeneratorWrapper,
        //                                  m_maxIterationsScannedBetweenTerminationChecks);
        // generator.GenerateX64Code(compileTree);
    }

//     const CompiledFunction QueryPlanner::GetMatchingFunction() const
// OA    {
//         // TODO: Don't like how call to GetMatchingFunction() finalizes jumps. This should be explicit.
//         return CompiledFunction((X64::X64FunctionGenerator&)m_x64FunctionGeneratorWrapper);
//     }

    IPlanRows const & QueryPlanner::GetPlanRows() const
    {
        return *m_planRows;
    }
}
<commit_msg>Remove auto_ptr. Fixes #222.<commit_after>#include "BitFunnel/Allocators/IAllocator.h"
// #include "BitFunnel/CompiledFunction.h"
#include "BitFunnel/IDiagnosticStream.h"
#include "BitFunnel/Plan/IPlanRows.h"
// #include "BitFunnel/IThreadResources.h"
#include "BitFunnel/Plan/QueryPlanner.h"
#include "BitFunnel/Plan/RowPlan.h"
#include "BitFunnel/Plan/TermMatchNode.h"
#include "BitFunnel/Plan/TermPlan.h"
#include "BitFunnel/Plan/TermPlanConverter.h"
#include "BitFunnel/Utilities/Factories.h"
#include "BitFunnel/Utilities/IObjectFormatter.h"
#include "CompileNode.h"
#include "LoggerInterfaces/Logging.h"
// #include "MatchTreeCodeGenerator.h"
#include "MatchTreeRewriter.h"
#include "RankDownCompiler.h"
#include "RegisterAllocator.h"

namespace BitFunnel
{
    // QueryPlanner::X64FunctionGeneratorWrapper::X64FunctionGeneratorWrapper(IThreadResources& threadResources)
    //     : m_code(threadResources.AllocateFunctionGenerator()),
    //       m_threadResources(threadResources)
    // {
    // }

    // QueryPlanner::X64FunctionGeneratorWrapper::~X64FunctionGeneratorWrapper()
    // {
    //     m_threadResources.ReleaseFunctionGenerator(m_code);
    // }

    // QueryPlanner::X64FunctionGeneratorWrapper::operator X64::X64FunctionGenerator&() const
    // {
    //     return m_code;
    // }

    unsigned const c_targetCrossProductTermCount = 180;

    QueryPlanner::QueryPlanner(TermPlan const & termPlan,
                               unsigned targetRowCount,
                               ISimpleIndex const & index,
                               // IThreadResources& threadResources,
                               IAllocator& allocator,
                               IDiagnosticStream* diagnosticStream)
                               // bool generateNonBodyPlan,
                               // unsigned maxIterationsScannedBetweenTerminationChecks)
    // : // m_x64FunctionGeneratorWrapper(threadResources),
    //   m_maxIterationsScannedBetweenTerminationChecks(maxIterationsScannedBetweenTerminationChecks)
    {
        if (diagnosticStream != nullptr && diagnosticStream->IsEnabled("planning/term"))
        {
            std::ostream& out = diagnosticStream->GetStream();
            std::unique_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream->GetStream()));

            out << "--------------------" << std::endl;
            out << "Term Plan:" << std::endl;
            termPlan.GetMatchTree().Format(*formatter);
            out << std::endl;
        }

        RowPlan const & rowPlan =
            TermPlanConverter::BuildRowPlan(termPlan.GetMatchTree(),
                                            index,
                                            // generateNonBodyPlan,
                                            allocator);

        if (diagnosticStream != nullptr && diagnosticStream->IsEnabled("planning/row"))
        {
            std::ostream& out = diagnosticStream->GetStream();
            std::unique_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream->GetStream()));

            out << "--------------------" << std::endl;
            out << "Row Plan:" << std::endl;
            rowPlan.Format(*formatter);
            out << std::endl;
        }

        m_planRows = &rowPlan.GetPlanRows();

        if (diagnosticStream != nullptr && diagnosticStream->IsEnabled("planning/planrows"))
        {
            std::ostream& out = diagnosticStream->GetStream();
            std::unique_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream->GetStream()));

            out << "--------------------" << std::endl;
            out << "IPlanRows:" << std::endl;
            for (ShardId shard = 0 ; shard < m_planRows->GetShardCount(); ++shard)
            {
                for (unsigned id = 0 ; id < m_planRows->GetRowCount(); ++id)
                {
                    RowId row = m_planRows->PhysicalRow(shard, id);

                    out << "(" << shard << ", " << id << "): ";
                    out << "RowId(" << row.GetShard();
                    out << ", " << row.GetRank();
                    out << ", " << row.GetIndex() << ")" << std::endl;
                }
            }
        }

        // Rewrite match tree to optimal form for the RankDownCompiler.
        RowMatchNode const & rewritten =
            MatchTreeRewriter::Rewrite(rowPlan.GetMatchTree(),
                                       targetRowCount,
                                       c_targetCrossProductTermCount,
                                       allocator);

        if (diagnosticStream != nullptr && diagnosticStream->IsEnabled("planning/rewrite"))
        {
            std::ostream& out = diagnosticStream->GetStream();
            std::unique_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream->GetStream()));

            out << "--------------------" << std::endl;
            out << "Rewritten Plan:" << std::endl;
            rewritten.Format(*formatter);
            out << std::endl;
        }

        // Compile the match tree into CompileNodes.
        RankDownCompiler compiler(allocator);
        compiler.Compile(rewritten);
        CompileNode const & compileTree = compiler.CreateTree(c_maxRankValue);

        if (diagnosticStream != nullptr && diagnosticStream->IsEnabled("planning/compile"))
        {
            std::ostream& out = diagnosticStream->GetStream();
            std::unique_ptr<IObjectFormatter>
                formatter(Factories::CreateObjectFormatter(diagnosticStream->GetStream()));

            out << "--------------------" << std::endl;
            out << "Compile Nodes:" << std::endl;
            compileTree.Format(*formatter);
            out << std::endl;
        }

        // Perform register allocation on the compile tree.
        RegisterAllocator const registers(compileTree,
                                          rowPlan.GetPlanRows().GetRowCount(),
                                          c_registerBase,
                                          c_registerCount,
                                          allocator);

        // Finally, translate compile tree to X64 machine code.
        // MatchTreeCodeGenerator generator(registers,
        //                                  m_x64FunctionGeneratorWrapper,
        //                                  m_maxIterationsScannedBetweenTerminationChecks);
        // generator.GenerateX64Code(compileTree);
    }

//     const CompiledFunction QueryPlanner::GetMatchingFunction() const
// OA    {
//         // TODO: Don't like how call to GetMatchingFunction() finalizes jumps. This should be explicit.
//         return CompiledFunction((X64::X64FunctionGenerator&)m_x64FunctionGeneratorWrapper);
//     }

    IPlanRows const & QueryPlanner::GetPlanRows() const
    {
        return *m_planRows;
    }
}
<|endoftext|>


<commit_before>/*
 * This file is part of Clockwork.
 *
 * Copyright (c) 2014-2016 Jeremy Othieno.
 *
 * The MIT License (MIT)
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include "Scene.hh"
#include "Suzanne.hh"

using clockwork::Scene;

Scene::Scene() :
viewer_(nullptr) {
	//TODO Remove this when done debugging.
	addNode(&asset::Suzanne::getInstance());
}

clockwork::SceneNode*
Scene::getNode(const QString& name) {
	return findChild<SceneNode*>(name, Qt::FindDirectChildrenOnly);
}

void
Scene::addNode(SceneNode* const node) {
	if (node != nullptr && node->parent() != this) {
		node->setParent(this);
	}
}

void
Scene::removeNode(const QString&) {
	qFatal("[Scene::removeNode] Implement me!");
}
<commit_msg>Correctly instantiate Suzanne<commit_after>/*
 * This file is part of Clockwork.
 *
 * Copyright (c) 2014-2016 Jeremy Othieno.
 *
 * The MIT License (MIT)
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 */
#include "Scene.hh"
#include "Suzanne.hh"

using clockwork::Scene;

Scene::Scene() :
viewer_(nullptr) {
	//TODO Remove this when done debugging.
	addNode(new asset::Suzanne());
}

clockwork::SceneNode*
Scene::getNode(const QString& name) {
	return findChild<SceneNode*>(name, Qt::FindDirectChildrenOnly);
}

void
Scene::addNode(SceneNode* const node) {
	if (node != nullptr && node->parent() != this) {
		node->setParent(this);
	}
}

void
Scene::removeNode(const QString&) {
	qFatal("[Scene::removeNode] Implement me!");
}
<|endoftext|>


<commit_before>// -*- Mode:C++ -*-

/**************************************************************************************************/
/*                                                                                */
/* Copyright (C) 2016 University of Hull                                                          */
/*                                                                                */
/**************************************************************************************************/
/*                                                                                */
/*  module     :  hugh/platform/window/base.inl                                                   */
/*  project    :                                                                                */
/*  description:                                                                                */
/*                                                                                */
/**************************************************************************************************/

#if !defined(HUGH_PLATFORM_WINDOW_BASE_INL)

#define HUGH_PLATFORM_WINDOW_BASE_INL

// includes, system

#include <glm/gtx/io.hpp> // glm::operator<<
#include <stdexcept>      // std::runtime_error

// includes, project

#include <hugh/platform/window/manager.hpp>

#define HUGH_USE_TRACE
#undef HUGH_USE_TRACE
#include <hugh/support/trace.hpp>
#if defined(HUGH_USE_TRACE) || defined(HUGH_ALL_TRACE)
#  include <typeinfo>
#  include <hugh/support/type_info.hpp>
#endif

namespace hugh {

  namespace platform {

    namespace window {

      // functions, inlined (inline)

#if defined(__GNUC__)
#  pragma GCC diagnostic push
#  pragma GCC diagnostic ignored "-Wterminate"
#elif defined(_MSC_VER)
#  pragma warning(push)
      // warning C4297: 'd'tor': function assumed not to throw an exception but does
#  pragma warning(disable:4297)
#endif

      template <typename C>
      inline /* virtual */
      base<C>::~base()
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::~base");

        if (!window::manager<C>::sub(&context_)) {
          // only throw if no other exception is being processed
          if (!std::uncaught_exception()) {
            throw std::runtime_error("hugh::platform::window::base<" +
                                     support::demangle(typeid(C)) +
                                     ">::~base: unable to deregister window context");
          }
        }
      }

#if defined(__GNUC__)
#  pragma GCC diagnostic pop
#elif defined(_MSC_VER)
#  pragma warning(pop)
#endif

      template <typename C>
      inline /* virtual */ void
      base<C>::print_on(std::ostream& os) const
      {
        TRACE_NEVER("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::print_on");

        field::container::print_on(os);

        os << hugh::support::ostream::remove(1) << ',' << context_ << ']';
      }

      template <typename C>
      inline /* explicit */
      base<C>::base(std::string const& a, rect const& b, std::string const& c)
        : boost::noncopyable(),
          field::container  (),
          title             (*this, "title",
                             std::bind(&base::cb_get_title,    this),
                             std::bind(&base::cb_set_title,    this, std::placeholders::_1)),
          position          (*this, "position",
                             std::bind(&base::cb_get_position, this),
                             std::bind(&base::cb_set_position, this, std::placeholders::_1)),
          size              (*this, "size",
                             std::bind(&base::cb_get_size,     this),
                             std::bind(&base::cb_set_size,     this, std::placeholders::_1)),
          context_          (a, b, c)
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::base");

        if (!window::manager<C>::add(&context_)) {
          throw std::runtime_error("hugh::platform::window::base<" + support::demangle(typeid(C)) +
                                   ">::base: unable to register window context");
        }
      }

      template <typename C>
      inline std::string const&
      base<C>::cb_get_title() const
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::cb_get_title");

        return context_.title();
      }

      template <typename C>
      inline std::string
      base<C>::cb_set_title(std::string const& a)
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::cb_set_title");

        return context_.title(a);
      }

      template <typename C>
      inline glm::uvec2 const&
      base<C>::cb_get_position() const
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::cb_get_position");

        return context_.position();
      }

      template <typename C>
      inline glm::uvec2
      base<C>::cb_set_position(glm::uvec2 const& a)
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::cb_set_position");

        return context_.position(a);
      }

      template <typename C>
      inline glm::uvec2 const&
      base<C>::cb_get_size() const
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::cb_get_size");

        return context_.size();
      }

      template <typename C>
      inline glm::uvec2
      base<C>::cb_set_size(glm::uvec2 const& a)
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::cb_get_size");

        return context_.size(a);
      }

    } // namespace window {

  } // namespace platform {

} // namespace hugh {

#if defined(HUGH_USE_TRACE)
#  undef HUGH_USE_TRACE
#endif

#endif // #if !defined(HUGH_PLATFORM_WINDOW_BASE_INL)
<commit_msg>fixed: gcc/clang diagnostic pragma handling<commit_after>// -*- Mode:C++ -*-

/**************************************************************************************************/
/*                                                                                */
/* Copyright (C) 2016 University of Hull                                                          */
/*                                                                                */
/**************************************************************************************************/
/*                                                                                */
/*  module     :  hugh/platform/window/base.inl                                                   */
/*  project    :                                                                                */
/*  description:                                                                                */
/*                                                                                */
/**************************************************************************************************/

#if !defined(HUGH_PLATFORM_WINDOW_BASE_INL)

#define HUGH_PLATFORM_WINDOW_BASE_INL

// includes, system

#include <glm/gtx/io.hpp> // glm::operator<<
#include <stdexcept>      // std::runtime_error

// includes, project

#include <hugh/platform/window/manager.hpp>

#define HUGH_USE_TRACE
#undef HUGH_USE_TRACE
#include <hugh/support/trace.hpp>
#if defined(HUGH_USE_TRACE) || defined(HUGH_ALL_TRACE)
#  include <typeinfo>
#  include <hugh/support/type_info.hpp>
#endif

namespace hugh {

  namespace platform {

    namespace window {

      // functions, inlined (inline)

#if defined(__GNUC__) && !defined(__clang__)
#  pragma GCC diagnostic push
#  pragma GCC diagnostic ignored "-Wterminate"
      //#elif defined(__clang__)
      //#  pragma clang diagnostic push
      //#  pragma clang diagnostic ignored "-Wterminate"
#elif defined(_MSC_VER)
#  pragma warning(push)
      // warning C4297: 'd'tor': function assumed not to throw an exception but does
#  pragma warning(disable:4297)
#endif

      template <typename C>
      inline /* virtual */
      base<C>::~base()
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::~base");

        if (!window::manager<C>::sub(&context_)) {
          // only throw if no other exception is being processed
          if (!std::uncaught_exception()) {
            throw std::runtime_error("hugh::platform::window::base<" +
                                     support::demangle(typeid(C)) +
                                     ">::~base: unable to deregister window context");
          }
        }
      }

#if defined(__GNUC__) && !defined(__clang__)
#  pragma GCC diagnostic pop
      //#elif defined(__clang__)
      //#  pragma clang diagnostic pop
#elif defined(_MSC_VER)
#  pragma warning(pop)
#endif

      template <typename C>
      inline /* virtual */ void
      base<C>::print_on(std::ostream& os) const
      {
        TRACE_NEVER("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::print_on");

        field::container::print_on(os);

        os << hugh::support::ostream::remove(1) << ',' << context_ << ']';
      }

      template <typename C>
      inline /* explicit */
      base<C>::base(std::string const& a, rect const& b, std::string const& c)
        : boost::noncopyable(),
          field::container  (),
          title             (*this, "title",
                             std::bind(&base::cb_get_title,    this),
                             std::bind(&base::cb_set_title,    this, std::placeholders::_1)),
          position          (*this, "position",
                             std::bind(&base::cb_get_position, this),
                             std::bind(&base::cb_set_position, this, std::placeholders::_1)),
          size              (*this, "size",
                             std::bind(&base::cb_get_size,     this),
                             std::bind(&base::cb_set_size,     this, std::placeholders::_1)),
          context_          (a, b, c)
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::base");

        if (!window::manager<C>::add(&context_)) {
          throw std::runtime_error("hugh::platform::window::base<" + support::demangle(typeid(C)) +
                                   ">::base: unable to register window context");
        }
      }

      template <typename C>
      inline std::string const&
      base<C>::cb_get_title() const
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::cb_get_title");

        return context_.title();
      }

      template <typename C>
      inline std::string
      base<C>::cb_set_title(std::string const& a)
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::cb_set_title");

        return context_.title(a);
      }

      template <typename C>
      inline glm::uvec2 const&
      base<C>::cb_get_position() const
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::cb_get_position");

        return context_.position();
      }

      template <typename C>
      inline glm::uvec2
      base<C>::cb_set_position(glm::uvec2 const& a)
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::cb_set_position");

        return context_.position(a);
      }

      template <typename C>
      inline glm::uvec2 const&
      base<C>::cb_get_size() const
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::cb_get_size");

        return context_.size();
      }

      template <typename C>
      inline glm::uvec2
      base<C>::cb_set_size(glm::uvec2 const& a)
      {
        TRACE("hugh::platform::window::base<" + support::demangle(typeid(C)) + ">::cb_get_size");

        return context_.size(a);
      }

    } // namespace window {

  } // namespace platform {

} // namespace hugh {

#if defined(HUGH_USE_TRACE)
#  undef HUGH_USE_TRACE
#endif

#endif // #if !defined(HUGH_PLATFORM_WINDOW_BASE_INL)
<|endoftext|>


<commit_before><commit_msg>updated warper<commit_after><|endoftext|>


<commit_before>/*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
// todo r2m adaptation : remove this
#include "t_kv.h"
#include "codec/encode.h"
#include "codec/decode.h"

int SSDBImpl::SetGeneric(const std::string &key, const std::string &val, int flags, const int64_t expire, char log_type){
	if (expire < 0){
		return -1;
	}

	std::string key_type;
	if (type(key, &key_type) == -1){
		return -1;
	}

	if ((flags & OBJ_SET_NX) && (key_type != "none")){
		return -1;
	} else if ((flags & OBJ_SET_XX) && (key_type == "none")){
		return -1;
	}

	Transaction trans(binlogs);

	if (key_type != "none"){
		DelKeyByType(key, key_type);
	}

	if (expire > 0){
        expiration->set_ttl_internal(key, expire);
	}

	std::string meta_key = encode_meta_key(key);
	std::string meta_val = encode_kv_val(val);
	binlogs->Put(meta_key, meta_val);
	binlogs->add_log(log_type, BinlogCommand::KSET, meta_key);
	leveldb::Status s = binlogs->commit();
	if (!s.ok()){
        //todo 时间戳排序回滚fast_keys first_timeout
		return -1;
	}
    return 0;
}

int SSDBImpl::multi_set(const std::vector<Bytes> &kvs, int offset, char log_type){
	Transaction trans(binlogs);

	std::vector<Bytes>::const_iterator it;
	it = kvs.begin() + offset;
	for(; it != kvs.end(); it += 2){
		const Bytes &key = *it;
		if(key.empty()){
			log_error("empty key!");
			return 0;
			//return -1;
		}
		const Bytes &val = *(it + 1);
// todo r2m adaptation
		std::string buf = encode_kv_key(key);
		binlogs->Put(buf, slice(val));
		binlogs->add_log(log_type, BinlogCommand::KSET, buf);
	}
	leveldb::Status s = binlogs->commit();
	if(!s.ok()){
		log_error("multi_set error: %s", s.ToString().c_str());
		return -1;
	}
	return (kvs.size() - offset)/2;
}

int SSDBImpl::multi_del(const std::vector<Bytes> &keys, int offset, char log_type){
	Transaction trans(binlogs);

	std::vector<Bytes>::const_iterator it;
	it = keys.begin() + offset;
	for(; it != keys.end(); it++){
		const Bytes &key = *it;
// todo r2m adaptation
		std::string buf = encode_kv_key(key);
		binlogs->Delete(buf);
		binlogs->add_log(log_type, BinlogCommand::KDEL, buf);
	}
	leveldb::Status s = binlogs->commit();
	if(!s.ok()){
		log_error("multi_del error: %s", s.ToString().c_str());
		return -1;
	}
	return keys.size() - offset;
}

int SSDBImpl::set(const Bytes &key, const Bytes &val, char log_type){
    return SetGeneric(key.String(), val.String(), OBJ_SET_NO_FLAGS, 0);
}

int SSDBImpl::setnx(const Bytes &key, const Bytes &val, char log_type){
    return SetGeneric(key.String(), val.String(), OBJ_SET_NX, 0);
}

int SSDBImpl::getset(const Bytes &key, std::string *val, const Bytes &newval, char log_type){
    std::string key_type;
    int ret = type(key.String(), &key_type);
    if (ret == -1){
        return -1;
    } else if (ret == 1 && key_type != "string"){
        return -1;
    } else if (ret == 1 && key_type == "string"){
        get(key.String(), val);
    }

	Transaction trans(binlogs);

	std::string buf = encode_meta_key(key.String());
    std::string meta_val = encode_kv_val(newval.String());
	binlogs->Put(buf, meta_val);
	binlogs->add_log(log_type, BinlogCommand::KSET, buf);
	leveldb::Status s = binlogs->commit();
	if(!s.ok()){
		log_error("set error: %s", s.ToString().c_str());
		return -1;
	}
	return ret;
}

int SSDBImpl::del(const Bytes &key, char log_type){
    std::string key_type;
    int ret = type(key.String(), &key_type);
    if (ret == -1){
        return -1;
    }
    if (key_type == "string"){
        KDel(key);
    } else if (key_type == "hash"){
        hclear(key);
    } else if (key_type == "set"){
        //todo
    } else if (key_type == "zset"){
        //todo
    } else if (key_type == "list"){
        //todo
    }

/*	Transaction trans(binlogs);

// todo r2m adaptation
	std::string buf = encode_kv_key(key);
	binlogs->Delete(buf);
	binlogs->add_log(log_type, BinlogCommand::KDEL, buf);
	leveldb::Status s = binlogs->commit();
	if(!s.ok()){
		log_error("del error: %s", s.ToString().c_str());
		return -1;
	}*/
	return 1;
}

int SSDBImpl::incr(const Bytes &key, int64_t by, int64_t *new_val, char log_type){
	Transaction trans(binlogs);

	std::string old;
	int ret = this->get(key, &old);
	if(ret == -1){
		return -1;
	}else if(ret == 0){
		*new_val = by;
	}else{
		*new_val = str_to_int64(old) + by;
		if(errno != 0){
			return 0;
		}
	}

// todo r2m adaptation
	std::string buf = encode_kv_key(key);
	binlogs->Put(buf, str(*new_val));
	binlogs->add_log(log_type, BinlogCommand::KSET, buf);

	leveldb::Status s = binlogs->commit();
	if(!s.ok()){
		log_error("del error: %s", s.ToString().c_str());
		return -1;
	}
	return 1;
}

int SSDBImpl::get(const Bytes &key, std::string *val){
	std::string buf = encode_meta_key(key.String());
    std::string en_val;

	leveldb::Status s = ldb->Get(leveldb::ReadOptions(), buf, &en_val);
	if(s.IsNotFound()){
		return 0;
	}
	if(!s.ok()){
		log_error("get error: %s", s.ToString().c_str());
		return -1;
	}
    KvMetaVal kv;
    if (kv.DecodeMetaVal(en_val) == -1){
        return -1;
    } else{
        *val = kv.value;
    }
	return 1;
}

// todo r2m adaptation
KIterator* SSDBImpl::scan(const Bytes &start, const Bytes &end, uint64_t limit){
	std::string key_start, key_end;
	key_start = encode_kv_key(start);
	if(end.empty()){
		key_end = "";
	}else{
		key_end = encode_kv_key(end);
	}
	//dump(key_start.data(), key_start.size(), "scan.start");
	//dump(key_end.data(), key_end.size(), "scan.end");

	return new KIterator(this->iterator(key_start, key_end, limit));
}

// todo r2m adaptation
KIterator* SSDBImpl::rscan(const Bytes &start, const Bytes &end, uint64_t limit){
	std::string key_start, key_end;

	key_start = encode_kv_key(start);
	if(start.empty()){
		key_start.append(1, 255);
	}
	if(!end.empty()){
		key_end = encode_kv_key(end);
	}
	//dump(key_start.data(), key_start.size(), "scan.start");
	//dump(key_end.data(), key_end.size(), "scan.end");

	return new KIterator(this->rev_iterator(key_start, key_end, limit));
}

int SSDBImpl::setbit(const Bytes &key, int bitoffset, int on, char log_type){
	if(key.empty()){
		log_error("empty key!");
		return 0;
	}
	Transaction trans(binlogs);

	std::string val;
	int ret = this->get(key, &val);
	if(ret == -1){
		return -1;
	}

	int len = bitoffset / 8;
	int bit = bitoffset % 8;
	if(len >= val.size()){
		val.resize(len + 1, 0);
	}
	int orig = val[len] & (1 << bit);
	if(on == 1){
		val[len] |= (1 << bit);
	}else{
		val[len] &= ~(1 << bit);
	}

// todo r2m adaptation
	std::string buf = encode_kv_key(key);
	binlogs->Put(buf, val);
	binlogs->add_log(log_type, BinlogCommand::KSET, buf);
	leveldb::Status s = binlogs->commit();
	if(!s.ok()){
		log_error("set error: %s", s.ToString().c_str());
		return -1;
	}
	return orig;
}

int SSDBImpl::getbit(const Bytes &key, int bitoffset){
	std::string val;
	int ret = this->get(key, &val);
	if(ret == -1){
		return -1;
	}

	int len = bitoffset / 8;
	int bit = bitoffset % 8;
	if(len >= val.size()){
		return 0;
	}
	return (val[len] & (1 << bit)) == 0? 0 : 1;
}

/*
 * private API
 */
int SSDBImpl::DelKeyByType(const std::string &key, const std::string &type){
	//todo 内部接口，保证操作的原子性，调用No Commit接口
	int ret = 0;
	if ("string" == type){
		ret = KDelNoLock(key);
	} else if ("hash" == type){
//		s = HDelKeyNoLock(key, &res);
	} else if ("list" == type){
//		s = LDelKeyNoLock(key, &res);
	} else if ("set" == type){
//		s = SDelKeyNoLock(key, &res);
	} else if ("zset" == type){
//		s = ZDelKeyNoLock(key, &res);
	}

	return 0;
}

int SSDBImpl::KDel(const Bytes &key, char log_type){
    Transaction trans(binlogs);

    std::string buf = encode_meta_key(key.String());
    binlogs->Delete(buf);
    binlogs->add_log(log_type, BinlogCommand::KDEL, buf);

    leveldb::Status s = binlogs->commit();
    if(!s.ok()){
        log_error("set error: %s", s.ToString().c_str());
        return -1;
    }
    return 1;
}

int SSDBImpl::KDelNoLock(const Bytes &key, char log_type){
	std::string buf = encode_meta_key(key.String());
	binlogs->Delete(buf);
	binlogs->add_log(log_type, BinlogCommand::KDEL, buf);
	return 0;
}

/*
 * General API
 */
int SSDBImpl::type(const Bytes &key, std::string *type){
	*type = "none";
    int ret = 0;
	std::string val;
	std::string meta_key = encode_meta_key(key.String());
	leveldb::Status s = ldb->Get(leveldb::ReadOptions(), meta_key, &val);
	if(s.IsNotFound()){
		return 0;
	}
	if(!s.ok()){
		log_error("get error: %s", s.ToString().c_str());
		return -1;
	}

	if (val[0] == DataType::KV){
		*type = "string";
        ret = 1;
	} else if (val[0] == DataType::HSIZE){
		HashMetaVal hv;
		if (hv.DecodeMetaVal(val) == -1){
			return -1;
		}
		if (hv.del == KEY_ENABLED_MASK){
			*type = "hash";
            ret = 1;
		}
	} else if (val[0] == DataType::SSIZE){
		SetMetaVal sv;
		if (sv.DecodeMetaVal(val) == -1){
			return -1;
		}
		if (sv.del == KEY_ENABLED_MASK){
			*type = "set";
            ret = 1;
		}
	} else if (val[0] == DataType::ZSIZE){
		ZSetMetaVal zs;
		if (zs.DecodeMetaVal(val) == -1){
			return -1;
		}
		if (zs.del == KEY_ENABLED_MASK){
			*type = "zset";
            ret = 1;
		}
	} else if (val[0] == DataType::LSZIE){
		ListMetaVal ls;
		if (ls.DecodeMetaVal(val) == -1){
			return -1;
		}
		if (ls.del == KEY_ENABLED_MASK){
			*type = "list";
            ret = 1;
		}
	} else{
		return -1;
	}

	return ret;
}
<commit_msg>实现kv multi_set API<commit_after>/*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
// todo r2m adaptation : remove this
#include "t_kv.h"
#include "codec/encode.h"
#include "codec/decode.h"

int SSDBImpl::SetGeneric(const std::string &key, const std::string &val, int flags, const int64_t expire, char log_type){
	if (expire < 0){
		return -1;
	}

	std::string key_type;
	if (type(key, &key_type) == -1){
		return -1;
	}

	if ((flags & OBJ_SET_NX) && (key_type != "none")){
		return -1;
	} else if ((flags & OBJ_SET_XX) && (key_type == "none")){
		return -1;
	}

	Transaction trans(binlogs);

	if (key_type != "none"){
		DelKeyByType(key, key_type);
	}

	if (expire > 0){
        expiration->set_ttl_internal(key, expire);
	}

	std::string meta_key = encode_meta_key(key);
	std::string meta_val = encode_kv_val(val);
	binlogs->Put(meta_key, meta_val);
	binlogs->add_log(log_type, BinlogCommand::KSET, meta_key);
	leveldb::Status s = binlogs->commit();
	if (!s.ok()){
        //todo 时间戳排序回滚fast_keys first_timeout
		return -1;
	}
    return 0;
}

int SSDBImpl::multi_set(const std::vector<Bytes> &kvs, int offset, char log_type){
	Transaction trans(binlogs);

	std::vector<Bytes>::const_iterator it;
	it = kvs.begin() + offset;
	for(; it != kvs.end(); it += 2){
		const Bytes &key = *it;
        std::string key_type;
        int ret = type(key.String(), &key_type);
        if (ret == -1){
            return  -1;
        } else if (ret == 1){
            DelKeyByType(key.String(), key_type);
        }

		const Bytes &val = *(it + 1);
		std::string buf = encode_meta_key(key.String());
        std::string meta_val = encode_kv_val(val.String());
		binlogs->Put(buf, meta_val);
		binlogs->add_log(log_type, BinlogCommand::KSET, buf);
	}
	leveldb::Status s = binlogs->commit();
	if(!s.ok()){
		log_error("multi_set error: %s", s.ToString().c_str());
		return -1;
	}
	return (kvs.size() - offset)/2;
}

int SSDBImpl::multi_del(const std::vector<Bytes> &keys, int offset, char log_type){
	Transaction trans(binlogs);

	std::vector<Bytes>::const_iterator it;
	it = keys.begin() + offset;
	for(; it != keys.end(); it++){
		const Bytes &key = *it;
// todo r2m adaptation
		std::string buf = encode_kv_key(key);
		binlogs->Delete(buf);
		binlogs->add_log(log_type, BinlogCommand::KDEL, buf);
	}
	leveldb::Status s = binlogs->commit();
	if(!s.ok()){
		log_error("multi_del error: %s", s.ToString().c_str());
		return -1;
	}
	return keys.size() - offset;
}

int SSDBImpl::set(const Bytes &key, const Bytes &val, char log_type){
    return SetGeneric(key.String(), val.String(), OBJ_SET_NO_FLAGS, 0);
}

int SSDBImpl::setnx(const Bytes &key, const Bytes &val, char log_type){
    return SetGeneric(key.String(), val.String(), OBJ_SET_NX, 0);
}

int SSDBImpl::getset(const Bytes &key, std::string *val, const Bytes &newval, char log_type){
    std::string key_type;
    int ret = type(key.String(), &key_type);
    if (ret == -1){
        return -1;
    } else if (ret == 1 && key_type != "string"){
        return -1;
    } else if (ret == 1 && key_type == "string"){
        get(key.String(), val);
    }

	Transaction trans(binlogs);

	std::string buf = encode_meta_key(key.String());
    std::string meta_val = encode_kv_val(newval.String());
	binlogs->Put(buf, meta_val);
	binlogs->add_log(log_type, BinlogCommand::KSET, buf);
	leveldb::Status s = binlogs->commit();
	if(!s.ok()){
		log_error("set error: %s", s.ToString().c_str());
		return -1;
	}
	return ret;
}

int SSDBImpl::del(const Bytes &key, char log_type){
    std::string key_type;
    int ret = type(key.String(), &key_type);
    if (ret == -1){
        return -1;
    }
    if (key_type == "string"){
        KDel(key);
    } else if (key_type == "hash"){
        hclear(key);
    } else if (key_type == "set"){
        //todo
    } else if (key_type == "zset"){
        //todo
    } else if (key_type == "list"){
        //todo
    }

/*	Transaction trans(binlogs);

// todo r2m adaptation
	std::string buf = encode_kv_key(key);
	binlogs->Delete(buf);
	binlogs->add_log(log_type, BinlogCommand::KDEL, buf);
	leveldb::Status s = binlogs->commit();
	if(!s.ok()){
		log_error("del error: %s", s.ToString().c_str());
		return -1;
	}*/
	return 1;
}

int SSDBImpl::incr(const Bytes &key, int64_t by, int64_t *new_val, char log_type){
	Transaction trans(binlogs);

	std::string old;
	int ret = this->get(key, &old);
	if(ret == -1){
		return -1;
	}else if(ret == 0){
		*new_val = by;
	}else{
		*new_val = str_to_int64(old) + by;
		if(errno != 0){
			return 0;
		}
	}

// todo r2m adaptation
	std::string buf = encode_kv_key(key);
	binlogs->Put(buf, str(*new_val));
	binlogs->add_log(log_type, BinlogCommand::KSET, buf);

	leveldb::Status s = binlogs->commit();
	if(!s.ok()){
		log_error("del error: %s", s.ToString().c_str());
		return -1;
	}
	return 1;
}

int SSDBImpl::get(const Bytes &key, std::string *val){
	std::string buf = encode_meta_key(key.String());
    std::string en_val;

	leveldb::Status s = ldb->Get(leveldb::ReadOptions(), buf, &en_val);
	if(s.IsNotFound()){
		return 0;
	}
	if(!s.ok()){
		log_error("get error: %s", s.ToString().c_str());
		return -1;
	}
    KvMetaVal kv;
    if (kv.DecodeMetaVal(en_val) == -1){
        return -1;
    } else{
        *val = kv.value;
    }
	return 1;
}

// todo r2m adaptation
KIterator* SSDBImpl::scan(const Bytes &start, const Bytes &end, uint64_t limit){
	std::string key_start, key_end;
	key_start = encode_kv_key(start);
	if(end.empty()){
		key_end = "";
	}else{
		key_end = encode_kv_key(end);
	}
	//dump(key_start.data(), key_start.size(), "scan.start");
	//dump(key_end.data(), key_end.size(), "scan.end");

	return new KIterator(this->iterator(key_start, key_end, limit));
}

// todo r2m adaptation
KIterator* SSDBImpl::rscan(const Bytes &start, const Bytes &end, uint64_t limit){
	std::string key_start, key_end;

	key_start = encode_kv_key(start);
	if(start.empty()){
		key_start.append(1, 255);
	}
	if(!end.empty()){
		key_end = encode_kv_key(end);
	}
	//dump(key_start.data(), key_start.size(), "scan.start");
	//dump(key_end.data(), key_end.size(), "scan.end");

	return new KIterator(this->rev_iterator(key_start, key_end, limit));
}

int SSDBImpl::setbit(const Bytes &key, int bitoffset, int on, char log_type){
	if(key.empty()){
		log_error("empty key!");
		return 0;
	}
	Transaction trans(binlogs);

	std::string val;
	int ret = this->get(key, &val);
	if(ret == -1){
		return -1;
	}

	int len = bitoffset / 8;
	int bit = bitoffset % 8;
	if(len >= val.size()){
		val.resize(len + 1, 0);
	}
	int orig = val[len] & (1 << bit);
	if(on == 1){
		val[len] |= (1 << bit);
	}else{
		val[len] &= ~(1 << bit);
	}

// todo r2m adaptation
	std::string buf = encode_kv_key(key);
	binlogs->Put(buf, val);
	binlogs->add_log(log_type, BinlogCommand::KSET, buf);
	leveldb::Status s = binlogs->commit();
	if(!s.ok()){
		log_error("set error: %s", s.ToString().c_str());
		return -1;
	}
	return orig;
}

int SSDBImpl::getbit(const Bytes &key, int bitoffset){
	std::string val;
	int ret = this->get(key, &val);
	if(ret == -1){
		return -1;
	}

	int len = bitoffset / 8;
	int bit = bitoffset % 8;
	if(len >= val.size()){
		return 0;
	}
	return (val[len] & (1 << bit)) == 0? 0 : 1;
}

/*
 * private API
 */
int SSDBImpl::DelKeyByType(const std::string &key, const std::string &type){
	//todo 内部接口，保证操作的原子性，调用No Commit接口
	int ret = 0;
	if ("string" == type){
		ret = KDelNoLock(key);
	} else if ("hash" == type){
//		s = HDelKeyNoLock(key, &res);
	} else if ("list" == type){
//		s = LDelKeyNoLock(key, &res);
	} else if ("set" == type){
//		s = SDelKeyNoLock(key, &res);
	} else if ("zset" == type){
//		s = ZDelKeyNoLock(key, &res);
	}

	return 0;
}

int SSDBImpl::KDel(const Bytes &key, char log_type){
    Transaction trans(binlogs);

    std::string buf = encode_meta_key(key.String());
    binlogs->Delete(buf);
    binlogs->add_log(log_type, BinlogCommand::KDEL, buf);

    leveldb::Status s = binlogs->commit();
    if(!s.ok()){
        log_error("set error: %s", s.ToString().c_str());
        return -1;
    }
    return 1;
}

int SSDBImpl::KDelNoLock(const Bytes &key, char log_type){
	std::string buf = encode_meta_key(key.String());
	binlogs->Delete(buf);
	binlogs->add_log(log_type, BinlogCommand::KDEL, buf);
	return 0;
}

/*
 * General API
 */
int SSDBImpl::type(const Bytes &key, std::string *type){
	*type = "none";
    int ret = 0;
	std::string val;
	std::string meta_key = encode_meta_key(key.String());
	leveldb::Status s = ldb->Get(leveldb::ReadOptions(), meta_key, &val);
	if(s.IsNotFound()){
		return 0;
	}
	if(!s.ok()){
		log_error("get error: %s", s.ToString().c_str());
		return -1;
	}

	if (val[0] == DataType::KV){
		*type = "string";
        ret = 1;
	} else if (val[0] == DataType::HSIZE){
		HashMetaVal hv;
		if (hv.DecodeMetaVal(val) == -1){
			return -1;
		}
		if (hv.del == KEY_ENABLED_MASK){
			*type = "hash";
            ret = 1;
		}
	} else if (val[0] == DataType::SSIZE){
		SetMetaVal sv;
		if (sv.DecodeMetaVal(val) == -1){
			return -1;
		}
		if (sv.del == KEY_ENABLED_MASK){
			*type = "set";
            ret = 1;
		}
	} else if (val[0] == DataType::ZSIZE){
		ZSetMetaVal zs;
		if (zs.DecodeMetaVal(val) == -1){
			return -1;
		}
		if (zs.del == KEY_ENABLED_MASK){
			*type = "zset";
            ret = 1;
		}
	} else if (val[0] == DataType::LSZIE){
		ListMetaVal ls;
		if (ls.DecodeMetaVal(val) == -1){
			return -1;
		}
		if (ls.del == KEY_ENABLED_MASK){
			*type = "list";
            ret = 1;
		}
	} else{
		return -1;
	}

	return ret;
}
<|endoftext|>


<commit_before>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#pragma once

#ifndef NAZARA_ENUMS_RENDERER_HPP
#define NAZARA_ENUMS_RENDERER_HPP

enum nzAttachmentPoint
{
	nzAttachmentPoint_Color,
	nzAttachmentPoint_Depth,
	nzAttachmentPoint_DepthStencil,
	nzAttachmentPoint_Stencil,

	nzAttachmentPoint_Max = nzAttachmentPoint_Stencil
};

enum nzBlendFunc
{
	nzBlendFunc_DestAlpha,
	nzBlendFunc_DestColor,
	nzBlendFunc_SrcAlpha,
	nzBlendFunc_SrcColor,
	nzBlendFunc_InvDestAlpha,
	nzBlendFunc_InvDestColor,
	nzBlendFunc_InvSrcAlpha,
	nzBlendFunc_InvSrcColor,
	nzBlendFunc_One,
	nzBlendFunc_Zero,

	nzBlendFunc_Max = nzBlendFunc_Zero
};

enum nzFaceFilling
{
	nzFaceFilling_Point,
	nzFaceFilling_Line,
	nzFaceFilling_Fill,

	nzFaceFilling_Max = nzFaceFilling_Fill
};

enum nzFaceSide
{
	nzFaceSide_Back,
	nzFaceSide_Front,
	nzFaceSide_FrontAndBack,

	nzFaceSide_Max = nzFaceSide_FrontAndBack
};

enum nzGpuQueryCondition
{
	nzGpuQueryCondition_Region_NoWait,
	nzGpuQueryCondition_Region_Wait,
	nzGpuQueryCondition_NoWait,
	nzGpuQueryCondition_Wait,

	nzGpuQueryCondition_Max = nzGpuQueryCondition_Wait
};

enum nzGpuQueryMode
{
	nzGpuQueryMode_AnySamplesPassed,
	nzGpuQueryMode_AnySamplesPassedConservative,
	nzGpuQueryMode_PrimitiveGenerated,
	nzGpuQueryMode_SamplesPassed,
	nzGpuQueryMode_TimeElapsed,
	nzGpuQueryMode_TransformFeedbackPrimitivesWritten,

	nzGpuQueryMode_Max = nzGpuQueryMode_TransformFeedbackPrimitivesWritten
};

enum nzMatrixType
{
	// Matrices de base
	nzMatrixType_Projection,
	nzMatrixType_View,
	nzMatrixType_World,

	// Matrices combinées
	nzMatrixType_ViewProj,
	nzMatrixType_WorldView,
	nzMatrixType_WorldViewProj,

	// Matrice inversées
	nzMatrixType_InvProjection,
	nzMatrixType_InvView,
	nzMatrixType_InvViewProj,
	nzMatrixType_InvWorld,
	nzMatrixType_InvWorldView,
	nzMatrixType_InvWorldViewProj,

	nzMatrixType_Max = nzMatrixType_InvWorldViewProj
};

enum nzPixelBufferType
{
	nzPixelBufferType_Pack,
	nzPixelBufferType_Unpack,

	nzPixelBufferType_Max = nzPixelBufferType_Unpack
};

enum nzRendererCap
{
	nzRendererCap_AnisotropicFilter,
	nzRendererCap_ConditionalRendering,
	nzRendererCap_FP64,
	nzRendererCap_HardwareBuffer,
	nzRendererCap_Instancing,
	nzRendererCap_MultipleRenderTargets,
	nzRendererCap_OcclusionQuery,
	nzRendererCap_PixelBufferObject,
	nzRendererCap_RenderTexture,
	nzRendererCap_Texture3D,
	nzRendererCap_TextureCubemap,
	nzRendererCap_TextureMulti,
	nzRendererCap_TextureNPOT,

	nzRendererCap_Max = nzRendererCap_TextureNPOT
};

enum nzRendererBufferFlags
{
	nzRendererBuffer_Color   = 0x1,
	nzRendererBuffer_Depth   = 0x2,
	nzRendererBuffer_Stencil = 0x4,

	nzRendererBuffer_Max = nzRendererBuffer_Stencil*2-1
};

enum nzRendererComparison
{
	nzRendererComparison_Always,
	nzRendererComparison_Equal,
	nzRendererComparison_Greater,
	nzRendererComparison_GreaterOrEqual,
	nzRendererComparison_Less,
	nzRendererComparison_LessOrEqual,
	nzRendererComparison_Never,
	nzRendererComparison_NotEqual,

	nzRendererComparison_Max = nzRendererComparison_NotEqual
};

enum nzRendererParameter
{
	nzRendererParameter_Blend,
	nzRendererParameter_ColorWrite,
	nzRendererParameter_DepthBuffer,
	nzRendererParameter_DepthWrite,
	nzRendererParameter_FaceCulling,
	nzRendererParameter_ScissorTest,
	nzRendererParameter_StencilTest,

	nzRendererParameter_Max = nzRendererParameter_StencilTest
};

enum nzSamplerFilter
{
	nzSamplerFilter_Unknown = -1,

	nzSamplerFilter_Bilinear,
	nzSamplerFilter_Nearest,
	nzSamplerFilter_Trilinear,

	nzSamplerFilter_Default,

	nzSamplerFilter_Max = nzSamplerFilter_Default
};

enum nzSamplerWrap
{
	nzSamplerWrap_Unknown = -1,

	nzSamplerWrap_Clamp,
	nzSamplerWrap_MirroredRepeat,
	nzSamplerWrap_Repeat,

	nzSamplerWrap_Default,

	nzSamplerWrap_Max = nzSamplerWrap_Repeat
};

enum nzShaderUniform
{
	///FIXME: Virer EyePosition et SceneAmbient de l'énumération (ils n'ont rien à faire dans le module de rendu)
	nzShaderUniform_EyePosition,
	nzShaderUniform_InvProjMatrix,
	nzShaderUniform_InvTargetSize,
	nzShaderUniform_InvViewMatrix,
	nzShaderUniform_InvViewProjMatrix,
	nzShaderUniform_InvWorldMatrix,
	nzShaderUniform_InvWorldViewMatrix,
	nzShaderUniform_InvWorldViewProjMatrix,
	nzShaderUniform_ProjMatrix,
	nzShaderUniform_SceneAmbient,
	nzShaderUniform_TargetSize,
	nzShaderUniform_ViewMatrix,
	nzShaderUniform_ViewProjMatrix,
	nzShaderUniform_WorldMatrix,
	nzShaderUniform_WorldViewMatrix,
	nzShaderUniform_WorldViewProjMatrix,

	nzShaderUniform_Max = nzShaderUniform_WorldViewProjMatrix
};

enum nzShaderStage
{
	nzShaderStage_Fragment,
	nzShaderStage_Geometry,
	nzShaderStage_Vertex,

	nzShaderStage_Max = nzShaderStage_Vertex
};

enum nzStencilOperation
{
	nzStencilOperation_Decrement,
	nzStencilOperation_DecrementNoClamp,
	nzStencilOperation_Increment,
	nzStencilOperation_IncrementNoClamp,
	nzStencilOperation_Invert,
	nzStencilOperation_Keep,
	nzStencilOperation_Replace,
	nzStencilOperation_Zero,

	nzStencilOperation_Max = nzStencilOperation_Zero
};

#endif // NAZARA_ENUMS_RENDERER_HPP
<commit_msg>Alphabetical commit<commit_after>// Copyright (C) 2014 Jérôme Leclercq
// This file is part of the "Nazara Engine - Renderer module"
// For conditions of distribution and use, see copyright notice in Config.hpp

#pragma once

#ifndef NAZARA_ENUMS_RENDERER_HPP
#define NAZARA_ENUMS_RENDERER_HPP

enum nzAttachmentPoint
{
	nzAttachmentPoint_Color,
	nzAttachmentPoint_Depth,
	nzAttachmentPoint_DepthStencil,
	nzAttachmentPoint_Stencil,

	nzAttachmentPoint_Max = nzAttachmentPoint_Stencil
};

enum nzBlendFunc
{
	nzBlendFunc_DestAlpha,
	nzBlendFunc_DestColor,
	nzBlendFunc_SrcAlpha,
	nzBlendFunc_SrcColor,
	nzBlendFunc_InvDestAlpha,
	nzBlendFunc_InvDestColor,
	nzBlendFunc_InvSrcAlpha,
	nzBlendFunc_InvSrcColor,
	nzBlendFunc_One,
	nzBlendFunc_Zero,

	nzBlendFunc_Max = nzBlendFunc_Zero
};

enum nzFaceFilling
{
	nzFaceFilling_Fill,
	nzFaceFilling_Line,
	nzFaceFilling_Point,

	nzFaceFilling_Max = nzFaceFilling_Point
};

enum nzFaceSide
{
	nzFaceSide_Back,
	nzFaceSide_Front,
	nzFaceSide_FrontAndBack,

	nzFaceSide_Max = nzFaceSide_FrontAndBack
};

enum nzGpuQueryCondition
{
	nzGpuQueryCondition_Region_NoWait,
	nzGpuQueryCondition_Region_Wait,
	nzGpuQueryCondition_NoWait,
	nzGpuQueryCondition_Wait,

	nzGpuQueryCondition_Max = nzGpuQueryCondition_Wait
};

enum nzGpuQueryMode
{
	nzGpuQueryMode_AnySamplesPassed,
	nzGpuQueryMode_AnySamplesPassedConservative,
	nzGpuQueryMode_PrimitiveGenerated,
	nzGpuQueryMode_SamplesPassed,
	nzGpuQueryMode_TimeElapsed,
	nzGpuQueryMode_TransformFeedbackPrimitivesWritten,

	nzGpuQueryMode_Max = nzGpuQueryMode_TransformFeedbackPrimitivesWritten
};

enum nzMatrixType
{
	// Matrices de base
	nzMatrixType_Projection,
	nzMatrixType_View,
	nzMatrixType_World,

	// Matrices combinées
	nzMatrixType_ViewProj,
	nzMatrixType_WorldView,
	nzMatrixType_WorldViewProj,

	// Matrice inversées
	nzMatrixType_InvProjection,
	nzMatrixType_InvView,
	nzMatrixType_InvViewProj,
	nzMatrixType_InvWorld,
	nzMatrixType_InvWorldView,
	nzMatrixType_InvWorldViewProj,

	nzMatrixType_Max = nzMatrixType_InvWorldViewProj
};

enum nzPixelBufferType
{
	nzPixelBufferType_Pack,
	nzPixelBufferType_Unpack,

	nzPixelBufferType_Max = nzPixelBufferType_Unpack
};

enum nzRendererCap
{
	nzRendererCap_AnisotropicFilter,
	nzRendererCap_ConditionalRendering,
	nzRendererCap_FP64,
	nzRendererCap_HardwareBuffer,
	nzRendererCap_Instancing,
	nzRendererCap_MultipleRenderTargets,
	nzRendererCap_OcclusionQuery,
	nzRendererCap_PixelBufferObject,
	nzRendererCap_RenderTexture,
	nzRendererCap_Texture3D,
	nzRendererCap_TextureCubemap,
	nzRendererCap_TextureMulti,
	nzRendererCap_TextureNPOT,

	nzRendererCap_Max = nzRendererCap_TextureNPOT
};

enum nzRendererBufferFlags
{
	nzRendererBuffer_Color   = 0x1,
	nzRendererBuffer_Depth   = 0x2,
	nzRendererBuffer_Stencil = 0x4,

	nzRendererBuffer_Max = nzRendererBuffer_Stencil*2-1
};

enum nzRendererComparison
{
	nzRendererComparison_Always,
	nzRendererComparison_Equal,
	nzRendererComparison_Greater,
	nzRendererComparison_GreaterOrEqual,
	nzRendererComparison_Less,
	nzRendererComparison_LessOrEqual,
	nzRendererComparison_Never,
	nzRendererComparison_NotEqual,

	nzRendererComparison_Max = nzRendererComparison_NotEqual
};

enum nzRendererParameter
{
	nzRendererParameter_Blend,
	nzRendererParameter_ColorWrite,
	nzRendererParameter_DepthBuffer,
	nzRendererParameter_DepthWrite,
	nzRendererParameter_FaceCulling,
	nzRendererParameter_ScissorTest,
	nzRendererParameter_StencilTest,

	nzRendererParameter_Max = nzRendererParameter_StencilTest
};

enum nzSamplerFilter
{
	nzSamplerFilter_Unknown = -1,

	nzSamplerFilter_Bilinear,
	nzSamplerFilter_Nearest,
	nzSamplerFilter_Trilinear,

	nzSamplerFilter_Default,

	nzSamplerFilter_Max = nzSamplerFilter_Default
};

enum nzSamplerWrap
{
	nzSamplerWrap_Unknown = -1,

	nzSamplerWrap_Clamp,
	nzSamplerWrap_MirroredRepeat,
	nzSamplerWrap_Repeat,

	nzSamplerWrap_Default,

	nzSamplerWrap_Max = nzSamplerWrap_Repeat
};

enum nzShaderUniform
{
	///FIXME: Virer EyePosition et SceneAmbient de l'énumération (ils n'ont rien à faire dans le module de rendu)
	nzShaderUniform_EyePosition,
	nzShaderUniform_InvProjMatrix,
	nzShaderUniform_InvTargetSize,
	nzShaderUniform_InvViewMatrix,
	nzShaderUniform_InvViewProjMatrix,
	nzShaderUniform_InvWorldMatrix,
	nzShaderUniform_InvWorldViewMatrix,
	nzShaderUniform_InvWorldViewProjMatrix,
	nzShaderUniform_ProjMatrix,
	nzShaderUniform_SceneAmbient,
	nzShaderUniform_TargetSize,
	nzShaderUniform_ViewMatrix,
	nzShaderUniform_ViewProjMatrix,
	nzShaderUniform_WorldMatrix,
	nzShaderUniform_WorldViewMatrix,
	nzShaderUniform_WorldViewProjMatrix,

	nzShaderUniform_Max = nzShaderUniform_WorldViewProjMatrix
};

enum nzShaderStage
{
	nzShaderStage_Fragment,
	nzShaderStage_Geometry,
	nzShaderStage_Vertex,

	nzShaderStage_Max = nzShaderStage_Vertex
};

enum nzStencilOperation
{
	nzStencilOperation_Decrement,
	nzStencilOperation_DecrementNoClamp,
	nzStencilOperation_Increment,
	nzStencilOperation_IncrementNoClamp,
	nzStencilOperation_Invert,
	nzStencilOperation_Keep,
	nzStencilOperation_Replace,
	nzStencilOperation_Zero,

	nzStencilOperation_Max = nzStencilOperation_Zero
};

#endif // NAZARA_ENUMS_RENDERER_HPP
<|endoftext|>