<commit_before>#include "wasteland.hpp"
#include "character.hpp"
#include "object.hpp"
#include "utility.hpp"
#include <sstream>

#include <SFML/Window.hpp>

#include <iostream>
#include <cstdio>

Wasteland::Wasteland()
    : should_quit_(false)
    , player_(new Character())
    , turn_(0)
    , console_(false)
    , light_radius_(5)
{
    window_ = std::make_unique<sf::RenderWindow>(sf::VideoMode(800, 600), "Wasteland");

    //TODO: replace this debug art with something else
    auto red = std::make_shared<sf::Texture>();
    red->create(1,1);
    uint8_t red_b[] = { 255, 100, 100, 255 };
    red->update(red_b);
    red->setRepeated(true);
    textures_[0] = red;

    auto green = std::make_shared<sf::Texture>();
    green->create(1,1);
    uint8_t green_b[] = { 100, 255, 100, 255 };
    green->update(green_b);
    green->setRepeated(true);
    textures_[1] = green;

    auto blue = std::make_shared<sf::Texture>();
    blue->create(1,1);
    uint8_t blue_b[] = { 200, 200, 200, 255 };
    blue->update(blue_b);
    blue->setRepeated(true);
    textures_[2] = blue;

    auto reds = std::make_shared<sf::Sprite>();
    reds->setTexture(*red);
    reds->setScale(sf::Vector2f(32.0f, 32.0f));
    sprites_[0] = reds;

    auto blues = std::make_shared<sf::Sprite>();
    blues->setTexture(*blue);
    blues->setScale(sf::Vector2f(32.0f, 32.0f));
    sprites_[2] = blues;

    auto greens = std::make_shared<sf::Sprite>();
    greens->setTexture(*green);
    greens->setScale(sf::Vector2f(32.0f, 32.0f));
    sprites_[1] = greens;

    player_->SetPosition(sf::Vector2f(1.0, 1.0));

    view_.setCenter(player_->GetPosition());
    window_->setView(view_);

    zoom_ = 1.0f;

    font_.loadFromFile("data/font.ttf");

    //auto knife = Object::BuildFromString(std::string("4,1,10,1,Combat Knife"));
    //std::cerr<<knife->ToString()<<"\n";
    //player_->AddInventoryItem(knife);
}

void Wasteland::Run()
{
    while(!should_quit_)
    {
        ProcessInput();
        UpdateMap();
        Draw();
    }

    window_->close();
}

void Wasteland::ProcessInput()
{
    sf::Event event;
    while (window_->pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
        {
            should_quit_ = true;
        }

        if (event.type == sf::Event::KeyPressed)
        {
            if(console_)
            {
                //TODO: do this better
                switch(event.key.code)
                {
                    case sf::Keyboard::Tilde:
                        console_ = false;
                        console_command_ = "";
                        break;
                    case sf::Keyboard::Escape:
                        console_ = false;
                        break;
                    case sf::Keyboard::Period:
                        console_command_ += ".";
                        break;
                    case sf::Keyboard::Space:
                        console_command_ += " ";
                        break;
                    case sf::Keyboard::BackSpace:
                        console_command_ = console_command_.substr(0, console_command_.length()-1);
                        break;
                    case sf::Keyboard::Return:
                        DoCommand(console_command_);
                        break;
                    case sf::Keyboard::Dash:
                    case sf::Keyboard::Subtract:
                        console_command_ += "-";
                        break;

                    default:
                        if(event.key.code < sf::Keyboard::Num9 && event.key.code != sf::Keyboard::Unknown)
                        {
                            std::string letters = "abcdefghijklmnopqrstuvwxyz0123456789";
                            console_command_ += letters[event.key.code];
                        }
                        break;
                }
            }
            else
            {
                switch(event.key.code)
                {
                    case sf::Keyboard::Tilde:
                        console_ = true;
                        console_command_ = "";
                        break;

                    case sf::Keyboard::Numpad4:
                    case sf::Keyboard::A:
                        HandlePlayerMovement(Player_MoveWest);
                        break;
                    case sf::Keyboard::Numpad2:
                    case sf::Keyboard::S:
                        HandlePlayerMovement(Player_MoveSouth);
                        break;
                    case sf::Keyboard::Numpad6:
                    case sf::Keyboard::D:
                        HandlePlayerMovement(Player_MoveEast);
                        break;
                    case sf::Keyboard::Numpad8:
                    case sf::Keyboard::W:
                        HandlePlayerMovement(Player_MoveNorth);
                        break;
                    case sf::Keyboard::Numpad3:
                        HandlePlayerMovement(Player_MoveSouthEast);
                        break;
                    case sf::Keyboard::Numpad1:
                        HandlePlayerMovement(Player_MoveSouthWest);
                        break;
                    case sf::Keyboard::Numpad9:
                        HandlePlayerMovement(Player_MoveNorthEast);
                        break;
                    case sf::Keyboard::Numpad7:
                        HandlePlayerMovement(Player_MoveNorthWest);
                        break;
                    case sf::Keyboard::Add:
                        view_.zoom(0.9);
                        break;
                    case sf::Keyboard::Subtract:
                        view_.zoom(1.111);
                        break;
                    case sf::Keyboard::G:
                        // get/pick-up
                        HandlePickup();
                        break;
                    default:
                        {

                        }
                }

                //TODO: this is a hack
                player_->ChangeFood(-1);
            }
        }
    }
}

void Wasteland::Draw()
{
    if(!window_)
        return;

    window_->clear(sf::Color::Black);

    window_->setView(view_);

    if(map_)
    {
        UpdateVisited();

        for(uint32_t y = 0; y<map_->GetHeight(); ++y)
        {
            for(uint32_t x = 0; x<map_->GetWidth(); ++x)
            {
                auto &tile = map_->Get(x, y);
                if(tile.visited)
                {
                    auto sprite = sprites_[(uint32_t)tile.type];
                    //TODO: improve this
                    if(tile.objects.size()>0)
                    {
                        sprite = sprites_[(uint32_t)(*tile.objects.begin())->GetSprite()];
                    }
                    sprite->setPosition(sf::Vector2f(x*32, y*32));
                    if(!map_->GetLit(x,y))
                    {
                        sprite->setColor(sf::Color(100,100,100));
                    }
                    else
                    {
                        sprite->setColor(sf::Color(255,255,255));
                    }
                    window_->draw(*sprites_[(uint32_t)tile.type]);
                }
            }
        }
    }

    //TODO: draw characters from map as well
    //TODO: draw projectiles from world

    sprites_[0]->setPosition(player_->GetPosition() * 32.0f);
    window_->draw(*sprites_[0]);

    /// Print text elements
    window_->setView(text_view_);

    // Status line
    sf::Text position(GetStatusLine().c_str(), font_);
    position.setCharacterSize(20);
    window_->draw(position);

    // Console
    if(console_)
    {
        std::string print_console = "Console> ";
        print_console += console_command_;
        sf::Text console(print_console.c_str(), font_);
        console.setCharacterSize(20);
        console.setPosition(sf::Vector2f(0, 100));
        window_->draw(console);
    }

    window_->display();
}

void Wasteland::HandlePlayerMovement(PlayerMovement action)
{
    ++turn_;
    auto move_to_pos = player_->GetPosition();
    switch(action)
    {
        case Player_MoveNorth:
            move_to_pos += sf::Vector2f(0.0, -1.0);
            break;
        case Player_MoveEast:
            move_to_pos += sf::Vector2f(1.0, 0.0);
            break;
        case Player_MoveSouth:
            move_to_pos += sf::Vector2f(0.0, 1.0);
            break;
        case Player_MoveWest:
            move_to_pos += sf::Vector2f(-1.0, 0.0);
            break;
        case Player_MoveNorthWest:
            move_to_pos += sf::Vector2f(-1.0, -1.0);
            break;
        case Player_MoveNorthEast:
            move_to_pos += sf::Vector2f(1.0, -1.0);
            break;
        case Player_MoveSouthWest:
            move_to_pos += sf::Vector2f(-1.0, 1.0);
            break;
        case Player_MoveSouthEast:
            move_to_pos += sf::Vector2f(1.0, 1.0);
            break;
    }

    auto &tile = map_->Get(move_to_pos.x, move_to_pos.y);
    if(!tile.passable)
    {
        move_to_pos = player_->GetPosition();
    }
    else
    {
        tile.visited = true;
    }

    player_->SetPosition(move_to_pos);
    view_.setCenter(move_to_pos * 32.0f);
}

void Wasteland::HandlePickup()
{
    auto position = player_->GetPosition();
    auto &tile = map_->Get((uint32_t)position.x, (uint32_t)position.y);
    if(tile.objects.size() == 0)
    {
        return;
    }

    auto itr = tile.objects.begin();
    //while(itr != tile.objects.end())
    {
        tile.objects.erase(std::remove_if(tile.objects.begin(), tile.objects.end(), [this](ObjectPtr p)
        {
            return player_->AddInventoryObject(p);
        }));
    }
}

void Wasteland::UpdateMap()
{
    if(player_->GetFood() == 0)
    {
        std::cerr<<"Game Over!\n";
        should_quit_ = true;
    }

    if(map_)
    {
        auto characters = map_->GetCharacters();
        for(auto chr : characters)
        {

        }
    }
}

void Wasteland::UpdateVisited()
{
    auto pos = player_->GetPosition();
    map_->UpdateLighting(pos.x, pos.y, light_radius_);
}

void Wasteland::LoadMap(const std::string& filename)
{
    map_ = Map::Load(filename);
}

void Wasteland::LoadMap(std::shared_ptr<sf::Image> img)
{
    map_ = Map::Load(img);

    //testing
    map_->SetRadiation(10, 10, 0.5);
    map_->SetRadiation(11, 10, 0.25);
    map_->SetRadiation(12, 10, 0.1);
    map_->SetRadiation(10, 11, 0.5);
    map_->SetRadiation(11, 11, 0.25);
    map_->SetRadiation(12, 11, 0.1);
    map_->SetRadiation(10, 9, 0.5);
    map_->SetRadiation(11, 9, 0.25);
    map_->SetRadiation(12, 9, 0.1);

    auto obj = Object::BuildFromString(std::string("4,1,10,1,Combat Knife"));
    map_->Get(3,4).objects.push_back(obj);
}

std::string Wasteland::GetStatusLine()
{
    char buffer[1000];
    sprintf(buffer, "Turn:%5d Position:(%3d, %3d) HP:(%3d/%3d)",
        turn_,
        (uint32_t)player_->GetPosition().x,
        (uint32_t)player_->GetPosition().y,
        (uint32_t)player_->GetHealth(),
        (uint32_t)player_->GetMaxHealth()
    );

    std::string ret = buffer;

    if(player_->GetFood() < 500)
    {
        ret += " HUNGRY";
    }

    return ret;
}

//!\brief implements basic console commands for debugging
void Wasteland::DoCommand(const std::string& str)
{
    std::vector<std::string> strings = TokenizeString(str, ' ');
    if(strings[0] == "changefood")
    {
        std::stringstream ss;
        ss<<strings[1];
        int32_t qty = 0;
        ss>>qty;
        player_->ChangeFood(qty);

        console_command_ = "";
    }
    else if(strings[0] == "teleport")
    {
        sf::Vector2f position;
        std::stringstream ss;
        ss<<strings[1];
        ss>>position.x;
        ss.clear();
        ss<<strings[2];
        ss>>position.y;

        player_->SetPosition(position);

        console_command_ = "";
    }
    else if(strings[0] == "setlight")
    {
        std::stringstream ss;
        ss<<strings[1];
        uint32_t radius = light_radius_;
        ss>>radius;
        light_radius_ = radius;

        console_command_ = "";
    }
    else if(strings[0] == "quit")
    {
        should_quit_ = true;
    }
    else if(strings[0] == "savemap")
    {
        map_->Save(strings[1].c_str());
        console_command_ = "";
    }
    else if(strings[0] == "loadmap")
    {
        map_ = Map::Load(strings[1].c_str());
        console_command_ = "";
    }
}

int main(int argc, char** argv)
{
    std::unique_ptr<Wasteland> game(new Wasteland());
    //game->LoadMap("data/test.map");
    auto mapImg = std::make_shared<sf::Image>();
    mapImg->loadFromFile("data/map.png");
    game->LoadMap(mapImg);
    game->Run();
    return 0;
}
<commit_msg>cleanup<commit_after>#include "wasteland.hpp"
#include "character.hpp"
#include "object.hpp"
#include "utility.hpp"
#include <sstream>

#include <SFML/Window.hpp>

#include <iostream>
#include <cstdio>

Wasteland::Wasteland()
    : should_quit_(false)
    , player_(new Character())
    , turn_(0)
    , console_(false)
    , light_radius_(5)
{
    window_ = std::make_unique<sf::RenderWindow>(sf::VideoMode(800, 600), "Wasteland");

    //TODO: replace this debug art with something else
    auto red = std::make_shared<sf::Texture>();
    red->create(1,1);
    uint8_t red_b[] = { 255, 100, 100, 255 };
    red->update(red_b);
    red->setRepeated(true);
    textures_[0] = red;

    auto green = std::make_shared<sf::Texture>();
    green->create(1,1);
    uint8_t green_b[] = { 100, 255, 100, 255 };
    green->update(green_b);
    green->setRepeated(true);
    textures_[1] = green;

    auto blue = std::make_shared<sf::Texture>();
    blue->create(1,1);
    uint8_t blue_b[] = { 200, 200, 200, 255 };
    blue->update(blue_b);
    blue->setRepeated(true);
    textures_[2] = blue;

    auto reds = std::make_shared<sf::Sprite>();
    reds->setTexture(*red);
    reds->setScale(sf::Vector2f(32.0f, 32.0f));
    sprites_[0] = reds;

    auto blues = std::make_shared<sf::Sprite>();
    blues->setTexture(*blue);
    blues->setScale(sf::Vector2f(32.0f, 32.0f));
    sprites_[2] = blues;

    auto greens = std::make_shared<sf::Sprite>();
    greens->setTexture(*green);
    greens->setScale(sf::Vector2f(32.0f, 32.0f));
    sprites_[1] = greens;

    player_->SetPosition(sf::Vector2f(1.0, 1.0));

    view_.setCenter(player_->GetPosition());
    window_->setView(view_);

    zoom_ = 1.0f;

    font_.loadFromFile("data/font.ttf");

    //auto knife = Object::BuildFromString(std::string("4,1,10,1,Combat Knife"));
    //std::cerr<<knife->ToString()<<"\n";
    //player_->AddInventoryItem(knife);
}

void Wasteland::Run()
{
    while(!should_quit_)
    {
        ProcessInput();
        UpdateMap();
        Draw();
    }

    window_->close();
}

void Wasteland::ProcessInput()
{
    sf::Event event;
    while (window_->pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
        {
            should_quit_ = true;
        }

        if (event.type == sf::Event::KeyPressed)
        {
            if(console_)
            {
                //TODO: do this better
                switch(event.key.code)
                {
                    case sf::Keyboard::Tilde:
                        console_ = false;
                        console_command_ = "";
                        break;
                    case sf::Keyboard::Escape:
                        console_ = false;
                        break;
                    case sf::Keyboard::Period:
                        console_command_ += ".";
                        break;
                    case sf::Keyboard::Space:
                        console_command_ += " ";
                        break;
                    case sf::Keyboard::BackSpace:
                        console_command_ = console_command_.substr(0, console_command_.length()-1);
                        break;
                    case sf::Keyboard::Return:
                        DoCommand(console_command_);
                        break;
                    case sf::Keyboard::Dash:
                    case sf::Keyboard::Subtract:
                        console_command_ += "-";
                        break;

                    default:
                        if(event.key.code < sf::Keyboard::Num9 && event.key.code != sf::Keyboard::Unknown)
                        {
                            std::string letters = "abcdefghijklmnopqrstuvwxyz0123456789";
                            console_command_ += letters[event.key.code];
                        }
                        break;
                }
            }
            else
            {
                switch(event.key.code)
                {
                    case sf::Keyboard::Tilde:
                        console_ = true;
                        console_command_ = "";
                        break;

                    case sf::Keyboard::Numpad4:
                    case sf::Keyboard::A:
                        HandlePlayerMovement(Player_MoveWest);
                        break;
                    case sf::Keyboard::Numpad2:
                    case sf::Keyboard::S:
                        HandlePlayerMovement(Player_MoveSouth);
                        break;
                    case sf::Keyboard::Numpad6:
                    case sf::Keyboard::D:
                        HandlePlayerMovement(Player_MoveEast);
                        break;
                    case sf::Keyboard::Numpad8:
                    case sf::Keyboard::W:
                        HandlePlayerMovement(Player_MoveNorth);
                        break;
                    case sf::Keyboard::Numpad3:
                        HandlePlayerMovement(Player_MoveSouthEast);
                        break;
                    case sf::Keyboard::Numpad1:
                        HandlePlayerMovement(Player_MoveSouthWest);
                        break;
                    case sf::Keyboard::Numpad9:
                        HandlePlayerMovement(Player_MoveNorthEast);
                        break;
                    case sf::Keyboard::Numpad7:
                        HandlePlayerMovement(Player_MoveNorthWest);
                        break;
                    case sf::Keyboard::Add:
                        view_.zoom(0.9);
                        break;
                    case sf::Keyboard::Subtract:
                        view_.zoom(1.111);
                        break;
                    case sf::Keyboard::G:
                        // get/pick-up
                        HandlePickup();
                        break;
                    default:
                        {

                        }
                }

                //TODO: this is a hack
                player_->ChangeFood(-1);
            }
        }
    }
}

void Wasteland::Draw()
{
    if(!window_)
        return;

    window_->clear(sf::Color::Black);

    window_->setView(view_);

    if(map_)
    {
        UpdateVisited();

        for(uint32_t y = 0; y<map_->GetHeight(); ++y)
        {
            for(uint32_t x = 0; x<map_->GetWidth(); ++x)
            {
                auto &tile = map_->Get(x, y);
                if(tile.visited)
                {
                    auto sprite = sprites_[(uint32_t)tile.type];
                    //TODO: improve this
                    if(tile.objects.size()>0)
                    {
                        sprite = sprites_[(uint32_t)(*tile.objects.begin())->GetSprite()];
                    }
                    sprite->setPosition(sf::Vector2f(x*32, y*32));
                    if(!map_->GetLit(x,y))
                    {
                        sprite->setColor(sf::Color(100,100,100));
                    }
                    else
                    {
                        sprite->setColor(sf::Color(255,255,255));
                    }
                    window_->draw(*sprites_[(uint32_t)tile.type]);
                }
            }
        }
    }

    //TODO: draw characters from map as well
    //TODO: draw projectiles from world

    sprites_[0]->setPosition(player_->GetPosition() * 32.0f);
    window_->draw(*sprites_[0]);

    /// Print text elements
    window_->setView(text_view_);

    // Status line
    sf::Text position(GetStatusLine().c_str(), font_);
    position.setCharacterSize(20);
    window_->draw(position);

    // Console
    if(console_)
    {
        std::string print_console = "Console> ";
        print_console += console_command_;
        sf::Text console(print_console.c_str(), font_);
        console.setCharacterSize(20);
        console.setPosition(sf::Vector2f(0, 100));
        window_->draw(console);
    }

    window_->display();
}

void Wasteland::HandlePlayerMovement(PlayerMovement action)
{
    ++turn_;
    auto move_to_pos = player_->GetPosition();
    switch(action)
    {
        case Player_MoveNorth:
            move_to_pos += sf::Vector2f(0.0, -1.0);
            break;
        case Player_MoveEast:
            move_to_pos += sf::Vector2f(1.0, 0.0);
            break;
        case Player_MoveSouth:
            move_to_pos += sf::Vector2f(0.0, 1.0);
            break;
        case Player_MoveWest:
            move_to_pos += sf::Vector2f(-1.0, 0.0);
            break;
        case Player_MoveNorthWest:
            move_to_pos += sf::Vector2f(-1.0, -1.0);
            break;
        case Player_MoveNorthEast:
            move_to_pos += sf::Vector2f(1.0, -1.0);
            break;
        case Player_MoveSouthWest:
            move_to_pos += sf::Vector2f(-1.0, 1.0);
            break;
        case Player_MoveSouthEast:
            move_to_pos += sf::Vector2f(1.0, 1.0);
            break;
    }

    auto &tile = map_->Get(move_to_pos.x, move_to_pos.y);
    if(!tile.passable)
    {
        move_to_pos = player_->GetPosition();
    }
    else
    {
        tile.visited = true;
    }

    player_->SetPosition(move_to_pos);
    view_.setCenter(move_to_pos * 32.0f);
}

void Wasteland::HandlePickup()
{
    auto position = player_->GetPosition();
    auto &tile = map_->Get((uint32_t)position.x, (uint32_t)position.y);
    if(tile.objects.size() == 0)
    {
        return;
    }

    tile.objects.erase(std::remove_if(tile.objects.begin(), tile.objects.end(), [this](ObjectPtr p)
    {
        return player_->AddInventoryObject(p);
    }));
}

void Wasteland::UpdateMap()
{
    if(player_->GetFood() == 0)
    {
        std::cerr<<"Game Over!\n";
        should_quit_ = true;
    }

    if(map_)
    {
        auto characters = map_->GetCharacters();
        for(auto chr : characters)
        {

        }
    }
}

void Wasteland::UpdateVisited()
{
    auto pos = player_->GetPosition();
    map_->UpdateLighting(pos.x, pos.y, light_radius_);
}

void Wasteland::LoadMap(const std::string& filename)
{
    map_ = Map::Load(filename);
}

void Wasteland::LoadMap(std::shared_ptr<sf::Image> img)
{
    map_ = Map::Load(img);

    //testing
    map_->SetRadiation(10, 10, 0.5);
    map_->SetRadiation(11, 10, 0.25);
    map_->SetRadiation(12, 10, 0.1);
    map_->SetRadiation(10, 11, 0.5);
    map_->SetRadiation(11, 11, 0.25);
    map_->SetRadiation(12, 11, 0.1);
    map_->SetRadiation(10, 9, 0.5);
    map_->SetRadiation(11, 9, 0.25);
    map_->SetRadiation(12, 9, 0.1);

    auto obj = Object::BuildFromString(std::string("4,1,10,1,Combat Knife"));
    map_->Get(3,4).objects.push_back(obj);
}

std::string Wasteland::GetStatusLine()
{
    char buffer[1000];
    sprintf(buffer, "Turn:%5d Position:(%3d, %3d) HP:(%3d/%3d)",
        turn_,
        (uint32_t)player_->GetPosition().x,
        (uint32_t)player_->GetPosition().y,
        (uint32_t)player_->GetHealth(),
        (uint32_t)player_->GetMaxHealth()
    );

    std::string ret = buffer;

    if(player_->GetFood() < 500)
    {
        ret += " HUNGRY";
    }

    return ret;
}

//!\brief implements basic console commands for debugging
void Wasteland::DoCommand(const std::string& str)
{
    std::vector<std::string> strings = TokenizeString(str, ' ');
    if(strings[0] == "changefood")
    {
        std::stringstream ss;
        ss<<strings[1];
        int32_t qty = 0;
        ss>>qty;
        player_->ChangeFood(qty);

        console_command_ = "";
    }
    else if(strings[0] == "teleport")
    {
        sf::Vector2f position;
        std::stringstream ss;
        ss<<strings[1];
        ss>>position.x;
        ss.clear();
        ss<<strings[2];
        ss>>position.y;

        player_->SetPosition(position);

        console_command_ = "";
    }
    else if(strings[0] == "setlight")
    {
        std::stringstream ss;
        ss<<strings[1];
        uint32_t radius = light_radius_;
        ss>>radius;
        light_radius_ = radius;

        console_command_ = "";
    }
    else if(strings[0] == "quit")
    {
        should_quit_ = true;
    }
    else if(strings[0] == "savemap")
    {
        map_->Save(strings[1].c_str());
        console_command_ = "";
    }
    else if(strings[0] == "loadmap")
    {
        map_ = Map::Load(strings[1].c_str());
        console_command_ = "";
    }
}

int main(int argc, char** argv)
{
    std::unique_ptr<Wasteland> game(new Wasteland());
    //game->LoadMap("data/test.map");
    auto mapImg = std::make_shared<sf::Image>();
    mapImg->loadFromFile("data/map.png");
    game->LoadMap(mapImg);
    game->Run();
    return 0;
}
<|endoftext|>


<commit_before>#include "wave2data.h"

void showHelp() {
    std::cout << "Arguments:" << std::endl;
    std::cout << "\t-h           \t" << "show help" << std::endl;
    std::cout << "\t-v           \t" << "show version" << std::endl;
    std::cout << "\t-f <filename>\t" << "set input filename" << std::endl;
    std::cout << "\t-o <filename>\t" << "set output filename" << std::endl;
}

bool setopts(int argc, char* argv[], std::string &fn, std::string &output) {
    int result;
    auto odef = "output.dat";

    fn = "";
    output = odef;
    auto version = "wave2data 0.1.1";

    if (argc < 2) {
        return false;
    }

    while ((result=getopt(argc, argv, "hvf:o:"))!=-1) {
        switch (result) {
        case 'h':
            // help
            showHelp();
            break;
        case 'v':
            // version
            std::cout << version << std::endl;
            break;
        case 'f':
            fn = std::string(optarg);
            if (output == odef) {
                output = fn + ".dat";
            }
            break;
        case 'o':
            output = std::string(optarg);
            break;
        default:
            break;
        }
    }

    return true;
}

std::string file2string(std::string fn) {
    std::ifstream ifs(fn, std::ios::in | std::ios::binary);

    if (!ifs) {
        std::perror(fn.c_str());
        return std::string();
    }

    std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
    ifs.close();

    return str;
}

bool dataCheck(std::string data, std::string fn) {
    if (data.empty()) {
        std::cout << fn << ": Unknown Error" << std::endl;
        return false;
    }

    // RIFF Check
    if (data.substr(0,4) != "RIFF") {
        std::cout << fn << ": not RIFF File." << std::endl;
        return false;
    }

    // Wave Check
    if (data.substr(8, 4) != "WAVE") {
        std::cout << fn << ": not Wave File." << std::endl;
        return false;
    }

    return true;
}

int getDataSize(std::string s_hex) {
    int sum = 0;
    for (int i = 0; i < 4; i++) {
        sum += static_cast<unsigned char>(s_hex.at(i)) << (8*i);
    }

    return sum;
}

bool createData(std::string fn, std::string data) {
    std::ofstream ofs(fn, std::ios::out | std::ios::binary);

    if (!ofs) {
        std::perror(fn.c_str());
        return false;
    }

    ofs << data;
    ofs.close();

    return true;
}
<commit_msg>0.1.2<commit_after>#include "wave2data.h"

void showHelp() {
    std::cout << "Arguments:" << std::endl;
    std::cout << "\t-h           \t" << "show help" << std::endl;
    std::cout << "\t-v           \t" << "show version" << std::endl;
    std::cout << "\t-f <filename>\t" << "set input filename" << std::endl;
    std::cout << "\t-o <filename>\t" << "set output filename" << std::endl;
}

bool setopts(int argc, char* argv[], std::string &fn, std::string &output) {
    int result;
    auto odef = "output.dat";

    fn = "";
    output = odef;
    auto version = "wave2data 0.1.2";

    if (argc < 2) {
        return false;
    }

    while ((result=getopt(argc, argv, "hvf:o:"))!=-1) {
        switch (result) {
        case 'h':
            // help
            showHelp();
            break;
        case 'v':
            // version
            std::cout << version << std::endl;
            break;
        case 'f':
            fn = std::string(optarg);
            if (output == odef) {
                output = fn + ".dat";
            }
            break;
        case 'o':
            output = std::string(optarg);
            break;
        default:
            break;
        }
    }

    return true;
}

std::string file2string(std::string fn) {
    std::ifstream ifs(fn, std::ios::in | std::ios::binary);

    if (!ifs) {
        std::perror(fn.c_str());
        return std::string();
    }

    std::string str((std::istreambuf_iterator<char>(ifs)), std::istreambuf_iterator<char>());
    ifs.close();

    return str;
}

bool dataCheck(std::string data, std::string fn) {
    if (data.empty()) {
        std::cout << fn << ": Unknown Error" << std::endl;
        return false;
    }

    // RIFF Check
    if (data.substr(0,4) != "RIFF") {
        std::cout << fn << ": not RIFF File." << std::endl;
        return false;
    }

    // Wave Check
    if (data.substr(8, 4) != "WAVE") {
        std::cout << fn << ": not Wave File." << std::endl;
        return false;
    }

    return true;
}

int getDataSize(std::string s_hex) {
    int sum = 0;
    for (int i = 0; i < 4; i++) {
        sum += static_cast<unsigned char>(s_hex.at(i)) << (8*i);
    }

    return sum;
}

bool createData(std::string fn, std::string data) {
    std::ofstream ofs(fn, std::ios::out | std::ios::binary);

    if (!ofs) {
        std::perror(fn.c_str());
        return false;
    }

    ofs << data;
    ofs.close();

    return true;
}
<|endoftext|>


<commit_before>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "CompileConfig.h"
#include "Texture.h"
#include "Engine.h"
#include "Renderer.h"
#include "Image.h"
#include "Utils.h"
#include "MathUtils.h"

namespace ouzel
{
    namespace graphics
    {
        Texture::Texture()
        {

        }

        Texture::~Texture()
        {

        }

        bool Texture::init(const Size2& newSize, bool newDynamic, bool newMipmaps)
        {
            size = newSize;
            dynamic = newDynamic;
            mipmaps = newMipmaps;

            return true;
        }

        bool Texture::initFromFile(const std::string& newFilename, bool newDynamic, bool newMipmaps)
        {
            filename = newFilename;
            dynamic = newDynamic;
            mipmaps = newMipmaps;

            Image image;
            if (!image.initFromFile(filename))
            {
                return false;
            }

            return initFromData(image.getData(), image.getSize(), dynamic, mipmaps);
        }

        bool Texture::initFromData(const void* data, const Size2& newSize, bool newDynamic, bool newMipmaps)
        {
            OUZEL_UNUSED(data);

            size = newSize;
            dynamic = newDynamic;
            mipmaps = newMipmaps;

            return true;
        }

        bool Texture::upload(const void* data, const Size2& newSize)
        {
            OUZEL_UNUSED(data);

            if (!dynamic)
            {
                return false;
            }

            if (newSize.width <= 0.0f || newSize.height <= 0.0f)
            {
                return false;
            }

            return true;
        }

        static void imageRgba8Downsample2x2(uint32_t width, uint32_t height, uint32_t pitch, const uint8_t* src, uint8_t* dst)
        {
            const uint32_t dstwidth  = width / 2;
            const uint32_t dstheight = height / 2;

            if (dstwidth == 0 ||  dstheight == 0)
            {
                return;
            }

            for (uint32_t y = 0, ystep = pitch * 2; y < dstheight; ++y, src += ystep)
            {
                const uint8_t* rgba = src;
                for (uint32_t x = 0; x < dstwidth; ++x, rgba += 8, dst += 4)
                {
                    float r = powf(rgba[0], 2.2f);
                    float g = powf(rgba[1], 2.2f);
                    float b = powf(rgba[2], 2.2f);
                    float a = rgba[3];
                    r += powf(rgba[4], 2.2f);
                    g += powf(rgba[5], 2.2f);
                    b += powf(rgba[6], 2.2f);
                    a += rgba[7];
                    r += powf(rgba[pitch+0], 2.2f);
                    g += powf(rgba[pitch+1], 2.2f);
                    b += powf(rgba[pitch+2], 2.2f);
                    a += rgba[pitch+3];
                    r += powf(rgba[pitch+4], 2.2f);
                    g += powf(rgba[pitch+5], 2.2f);
                    b += powf(rgba[pitch+6], 2.2f);
                    a += rgba[pitch+7];

                    r *= 0.25f;
                    g *= 0.25f;
                    b *= 0.25f;
                    a *= 0.25f;
                    r = powf(r, 1.0f / 2.2f);
                    g = powf(g, 1.0f / 2.2f);
                    b = powf(b, 1.0f / 2.2f);
                    dst[0] = (uint8_t)r;
                    dst[1] = (uint8_t)g;
                    dst[2] = (uint8_t)b;
                    dst[3] = (uint8_t)a;
                }
            }
        }

        bool Texture::uploadData(const void* data, const Size2& newSize)
        {
            size = newSize;

            mipmapSizes.clear();
            mipmapSizes.push_back(newSize);

            mipLevels = 0;
            uploadMipmap(mipLevels, data);
            ++mipLevels;

            uint32_t newWidth = static_cast<uint32_t>(newSize.width);
            uint32_t newHeight = static_cast<uint32_t>(newSize.height);

#ifdef OUZEL_SUPPORTS_OPENGLES
            if (mipmaps && isPOT(newWidth) && isPOT(newHeight))
#else
            if (mipmaps)
#endif
            {
                uint32_t pitch = newWidth * 4;

                uint32_t bufferSize = newWidth * newHeight * 4;

                if (newWidth == 1)
                {
                    bufferSize *= 2;
                }
                if (newHeight == 1)
                {
                    bufferSize *= 2;
                }

                std::vector<uint8_t> newData(bufferSize);
                memcpy(newData.data(), data, newWidth * newHeight * 4);

                while (newWidth >= 2 && newHeight >= 2)
                {
                    imageRgba8Downsample2x2(newWidth, newHeight, pitch, newData.data(), newData.data());

                    newWidth >>= 1;
                    newHeight >>= 1;

                    mipmapSizes.push_back(Size2(static_cast<float>(newWidth), static_cast<float>(newHeight)));
                    uploadMipmap(mipLevels, newData.data());

                    pitch = newWidth * 4;
                    ++mipLevels;
                }

                if (newWidth > newHeight)
                {
                    for (; newWidth >= 2;)
                    {
                        memcpy(&newData.data()[newWidth*4], newData.data(), newWidth * 4);

                        imageRgba8Downsample2x2(newWidth, 2, pitch, newData.data(), newData.data());

                        newWidth >>= 1;

                        mipmapSizes.push_back(Size2(static_cast<float>(newWidth), static_cast<float>(newHeight)));
                        uploadMipmap(mipLevels, newData.data());

                        pitch = newWidth * 4;
                        ++mipLevels;
                    }
                }
                else
                {
                    for (; newHeight >= 2;)
                    {
                        uint32_t* src = reinterpret_cast<uint32_t*>(newData.data());
                        for (uint32_t i = newHeight - 1; i >= 0; --i)
                        {
                            src[i * 2] = src[i];
                            src[i * 2 + 1] = src[i];
                        }

                        imageRgba8Downsample2x2(2, newHeight, 8, newData.data(), newData.data());

                        newHeight >>= 1;

                        mipmapSizes.push_back(Size2(static_cast<float>(newWidth), static_cast<float>(newHeight)));
                        uploadMipmap(mipLevels, newData.data());

                        ++mipLevels;
                    }
                }
            }

            return true;
        }

        bool Texture::uploadMipmap(uint32_t level, const void* data)
        {
            OUZEL_UNUSED(data);

            if (level >= mipmapSizes.size())
            {
                return false;
            }

            return true;
        }
    } // namespace graphics
} // namespace ouzel
<commit_msg>Fix signedness of i<commit_after>// Copyright (C) 2016 Elviss Strazdins
// This file is part of the Ouzel engine.

#include "CompileConfig.h"
#include "Texture.h"
#include "Engine.h"
#include "Renderer.h"
#include "Image.h"
#include "Utils.h"
#include "MathUtils.h"

namespace ouzel
{
    namespace graphics
    {
        Texture::Texture()
        {

        }

        Texture::~Texture()
        {

        }

        bool Texture::init(const Size2& newSize, bool newDynamic, bool newMipmaps)
        {
            size = newSize;
            dynamic = newDynamic;
            mipmaps = newMipmaps;

            return true;
        }

        bool Texture::initFromFile(const std::string& newFilename, bool newDynamic, bool newMipmaps)
        {
            filename = newFilename;
            dynamic = newDynamic;
            mipmaps = newMipmaps;

            Image image;
            if (!image.initFromFile(filename))
            {
                return false;
            }

            return initFromData(image.getData(), image.getSize(), dynamic, mipmaps);
        }

        bool Texture::initFromData(const void* data, const Size2& newSize, bool newDynamic, bool newMipmaps)
        {
            OUZEL_UNUSED(data);

            size = newSize;
            dynamic = newDynamic;
            mipmaps = newMipmaps;

            return true;
        }

        bool Texture::upload(const void* data, const Size2& newSize)
        {
            OUZEL_UNUSED(data);

            if (!dynamic)
            {
                return false;
            }

            if (newSize.width <= 0.0f || newSize.height <= 0.0f)
            {
                return false;
            }

            return true;
        }

        static void imageRgba8Downsample2x2(uint32_t width, uint32_t height, uint32_t pitch, const uint8_t* src, uint8_t* dst)
        {
            const uint32_t dstwidth  = width / 2;
            const uint32_t dstheight = height / 2;

            if (dstwidth == 0 ||  dstheight == 0)
            {
                return;
            }

            for (uint32_t y = 0, ystep = pitch * 2; y < dstheight; ++y, src += ystep)
            {
                const uint8_t* rgba = src;
                for (uint32_t x = 0; x < dstwidth; ++x, rgba += 8, dst += 4)
                {
                    float r = powf(rgba[0], 2.2f);
                    float g = powf(rgba[1], 2.2f);
                    float b = powf(rgba[2], 2.2f);
                    float a = rgba[3];
                    r += powf(rgba[4], 2.2f);
                    g += powf(rgba[5], 2.2f);
                    b += powf(rgba[6], 2.2f);
                    a += rgba[7];
                    r += powf(rgba[pitch+0], 2.2f);
                    g += powf(rgba[pitch+1], 2.2f);
                    b += powf(rgba[pitch+2], 2.2f);
                    a += rgba[pitch+3];
                    r += powf(rgba[pitch+4], 2.2f);
                    g += powf(rgba[pitch+5], 2.2f);
                    b += powf(rgba[pitch+6], 2.2f);
                    a += rgba[pitch+7];

                    r *= 0.25f;
                    g *= 0.25f;
                    b *= 0.25f;
                    a *= 0.25f;
                    r = powf(r, 1.0f / 2.2f);
                    g = powf(g, 1.0f / 2.2f);
                    b = powf(b, 1.0f / 2.2f);
                    dst[0] = (uint8_t)r;
                    dst[1] = (uint8_t)g;
                    dst[2] = (uint8_t)b;
                    dst[3] = (uint8_t)a;
                }
            }
        }

        bool Texture::uploadData(const void* data, const Size2& newSize)
        {
            size = newSize;

            mipmapSizes.clear();
            mipmapSizes.push_back(newSize);

            mipLevels = 0;
            uploadMipmap(mipLevels, data);
            ++mipLevels;

            uint32_t newWidth = static_cast<uint32_t>(newSize.width);
            uint32_t newHeight = static_cast<uint32_t>(newSize.height);

#ifdef OUZEL_SUPPORTS_OPENGLES
            if (mipmaps && isPOT(newWidth) && isPOT(newHeight))
#else
            if (mipmaps)
#endif
            {
                uint32_t pitch = newWidth * 4;

                uint32_t bufferSize = newWidth * newHeight * 4;

                if (newWidth == 1)
                {
                    bufferSize *= 2;
                }
                if (newHeight == 1)
                {
                    bufferSize *= 2;
                }

                std::vector<uint8_t> newData(bufferSize);
                memcpy(newData.data(), data, newWidth * newHeight * 4);

                while (newWidth >= 2 && newHeight >= 2)
                {
                    imageRgba8Downsample2x2(newWidth, newHeight, pitch, newData.data(), newData.data());

                    newWidth >>= 1;
                    newHeight >>= 1;

                    mipmapSizes.push_back(Size2(static_cast<float>(newWidth), static_cast<float>(newHeight)));
                    uploadMipmap(mipLevels, newData.data());

                    pitch = newWidth * 4;
                    ++mipLevels;
                }

                if (newWidth > newHeight)
                {
                    for (; newWidth >= 2;)
                    {
                        memcpy(&newData.data()[newWidth*4], newData.data(), newWidth * 4);

                        imageRgba8Downsample2x2(newWidth, 2, pitch, newData.data(), newData.data());

                        newWidth >>= 1;

                        mipmapSizes.push_back(Size2(static_cast<float>(newWidth), static_cast<float>(newHeight)));
                        uploadMipmap(mipLevels, newData.data());

                        pitch = newWidth * 4;
                        ++mipLevels;
                    }
                }
                else
                {
                    for (; newHeight >= 2;)
                    {
                        uint32_t* src = reinterpret_cast<uint32_t*>(newData.data());
                        for (int32_t i = newHeight - 1; i >= 0; --i)
                        {
                            src[i * 2] = src[i];
                            src[i * 2 + 1] = src[i];
                        }

                        imageRgba8Downsample2x2(2, newHeight, 8, newData.data(), newData.data());

                        newHeight >>= 1;

                        mipmapSizes.push_back(Size2(static_cast<float>(newWidth), static_cast<float>(newHeight)));
                        uploadMipmap(mipLevels, newData.data());

                        ++mipLevels;
                    }
                }
            }

            return true;
        }

        bool Texture::uploadMipmap(uint32_t level, const void* data)
        {
            OUZEL_UNUSED(data);

            if (level >= mipmapSizes.size())
            {
                return false;
            }

            return true;
        }
    } // namespace graphics
} // namespace ouzel
<|endoftext|>


<commit_before>/* This file is part of Zanshin Todo.

   Copyright 2008-2009 Kevin Ottens <ervin@kde.org>

   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 2 of
   the License or (at your option) version 3 or any later version
   accepted by the membership of KDE e.V. (or its successor approved
   by the membership of KDE e.V.), which shall act as a proxy
   defined in Section 14 of version 3 of the license.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
   USA.
*/

#include "sidebar.h"

#if 0
#include <akonadi/item.h>
#include <akonadi/itemcreatejob.h>
#include <akonadi/itemdeletejob.h>
#include <akonadi/transactionsequence.h>

#include <boost/shared_ptr.hpp>

#include <KDE/KCalCore/Todo>
#endif

#include <KDE/Akonadi/EntityTreeView>
#include <KDE/KAction>
#include <KDE/KActionCollection>
#include <KDE/KIcon>
#include <KDE/KLocale>

#include <QtGui/QStackedWidget>
#include <QtGui/QToolBar>
#include <QtGui/QVBoxLayout>

#include "globaldefs.h"
#include "modelstack.h"
#include "sidebarpage.h"

SideBar::SideBar(ModelStack *models, KActionCollection *ac, QWidget *parent)
    : QWidget(parent)
{
    setupActions(ac);

    setLayout(new QVBoxLayout(this));
    m_stack = new QStackedWidget(this);
    layout()->addWidget(m_stack);
    layout()->setContentsMargins(0, 0, 0, 0);

    createPage(models->treeSideBarModel());
    createPage(models->categoriesSideBarModel());

    setupToolBar();
}

void SideBar::createPage(QAbstractItemModel *model)
{
    QAction *separator = new QAction(this);
    separator->setSeparator(true);

    QList<QAction*> contextActions;
    contextActions << m_add
                   << m_remove
                   << separator
                   << m_rename;

    SideBarPage *page = new SideBarPage(model, contextActions, m_stack);

    connect(page->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)),
            this, SLOT(updateActions(QModelIndex)));

    m_stack->addWidget(page);
}

void SideBar::setupToolBar()
{
    QHBoxLayout *toolbarLayout = new QHBoxLayout;
    toolbarLayout->setAlignment(Qt::AlignRight);

    QToolBar *projectBar = new QToolBar(this);
    projectBar->setIconSize(QSize(16, 16));
    layout()->addWidget(projectBar);
    projectBar->addAction(m_add);
    projectBar->addAction(m_remove);
}

void SideBar::setupActions(KActionCollection *ac)
{
    m_add = ac->addAction("sidebar_new", this, SLOT(onAddItem()));
    m_add->setText(i18n("New"));
    m_add->setIcon(KIcon("list-add"));

    m_remove = ac->addAction("sidebar_remove", this, SLOT(onRemoveItem()));
    m_remove->setText(i18n("Remove"));
    m_remove->setIcon(KIcon("list-remove"));

    m_rename = ac->addAction("sidebar_rename", this, SLOT(onRenameItem()));
    m_rename->setText(i18n("Rename"));
    m_rename->setIcon(KIcon("edit-rename"));

    m_previous = ac->addAction("sidebar_go_previous", this, SLOT(onPreviousItem()));
    m_previous->setText(i18n("Previous"));
    m_previous->setIcon(KIcon("go-previous"));
    m_previous->setShortcut(Qt::ALT | Qt::Key_Up);

    m_next = ac->addAction("sidebar_go_next", this, SLOT(onNextItem()));
    m_next->setText(i18n("Next"));
    m_next->setIcon(KIcon("go-next"));
    m_next->setShortcut(Qt::ALT | Qt::Key_Down);
}

void SideBar::setMode(Zanshin::ApplicationMode mode)
{
    switch (mode) {
    case Zanshin::ProjectMode:
        m_stack->setCurrentIndex(0);
        m_add->setText("New Project");
        m_remove->setText("Remove Project");
        m_rename->setText("Rename Project");
        m_previous->setText("Previous Project");
        m_next->setText("Next Project");
        break;

    case Zanshin::CategoriesMode:
        m_stack->setCurrentIndex(1);
        m_add->setText("New Category");
        m_remove->setText("Remove Category");
        m_rename->setText("Rename Category");
        m_previous->setText("Previous Category");
        m_next->setText("Next Category");
        break;
    }

    updateActions(currentPage()->selectionModel()->currentIndex());
}

QItemSelectionModel *SideBar::projectSelection() const
{
    return static_cast<SideBarPage*>(m_stack->widget(0))->selectionModel();
}

QItemSelectionModel *SideBar::categoriesSelection() const
{
    return static_cast<SideBarPage*>(m_stack->widget(1))->selectionModel();
}

void SideBar::updateActions(const QModelIndex &index)
{
    Zanshin::ItemType type = (Zanshin::ItemType) index.data(Zanshin::ItemTypeRole).toInt();

    m_add->setEnabled( type == Zanshin::Collection
                    || type == Zanshin::ProjectTodo
                    || type == Zanshin::CategoryRoot
                    || type == Zanshin::Category);

    m_remove->setEnabled( type == Zanshin::ProjectTodo
                       || type == Zanshin::Category );

    m_rename->setEnabled( type == Zanshin::ProjectTodo
                       || type == Zanshin::Category );
}

void SideBar::onAddItem()
{
    currentPage()->addNewItem();
}

void SideBar::onRemoveItem()
{
    currentPage()->removeCurrentItem();
}

void SideBar::onRenameItem()
{
    currentPage()->renameCurrentItem();
}

void SideBar::onPreviousItem()
{
    currentPage()->selectPreviousItem();
}

void SideBar::onNextItem()
{
    currentPage()->selectNextItem();
}

SideBarPage *SideBar::currentPage() const
{
    return static_cast<SideBarPage*>(m_stack->currentWidget());
}

SideBarPage *SideBar::page(int idx) const
{
    return static_cast<SideBarPage*>(m_stack->widget(idx));
}

void SideBar::addNewProject()
{
#if 0
    bool ok;
    QString summary = KInputDialog::getText(i18n("New Project"),
                                            i18n("Enter project name:"),
                                            QString(), &ok, this);
    summary = summary.trimmed();

    if (!ok || summary.isEmpty()) return;

    QModelIndex parent = m_projectTree->currentIndex();
    parent = GlobalModel::projectsLibrary()->mapToSource(parent);
    parent = GlobalModel::projects()->mapToSource(parent);
    parent = parent.sibling(parent.row(), TodoFlatModel::RemoteId);

    QString parentRemoteId = GlobalModel::todoTree()->data(parent).toString();

    KCalCore::Todo *todo = new KCalCore::Todo();
    todo->setSummary(summary);
    todo->addComment("X-Zanshin-Project");

    if (!parentRemoteId.isEmpty()) {
        todo->setRelatedTo(parentRemoteId);
    }

    IncidencePtr incidence(todo);
    Akonadi::Item item;
    item.setMimeType("application/x-vnd.akonadi.calendar.todo");
    item.setPayload<IncidencePtr>(incidence);

    Akonadi::Collection collection = GlobalModel::todoFlat()->collection();
    Akonadi::ItemCreateJob *job = new Akonadi::ItemCreateJob(item, collection);
    job->start();
#endif
}

#if 0
void addDeleteTodoJobsHelper(const QModelIndex &index, Akonadi::TransactionSequence *transaction)
{
    for (int i=0; i<GlobalModel::todoTree()->rowCount(index); i++) {
        addDeleteTodoJobsHelper(index.child(i, 0), transaction);
    }

    Akonadi::Item item = GlobalModel::todoTree()->itemForIndex(index);
    new Akonadi::ItemDeleteJob(item, transaction);
}
#endif

void SideBar::removeCurrentProject()
{
#if 0
    QModelIndex current = m_projectTree->currentIndex();
    current = GlobalModel::projectsLibrary()->mapToSource(current);
    current = GlobalModel::projects()->mapToSource(current);
    current = current.sibling(current.row(), 0);

    bool canRemove = true;

    if (GlobalModel::todoTree()->rowCount(current)>0) {
        QString summary = GlobalModel::todoTree()->data(current).toString();
        int rowType = GlobalModel::todoTree()->data(current.sibling(current.row(), TodoFlatModel::RowType)).toInt();
        QString message;
        QString caption;
        if (rowType==TodoFlatModel::FolderTodo) {
            message = i18n("Do you really want to delete the folder '%1', with all its projects and actions?", summary);
            caption = i18n("Delete Folder");
        } else {
            message = i18n("Do you really want to delete the project '%1', with all its actions?", summary);
            caption = i18n("Delete Project");
        }
        int button = KMessageBox::questionYesNo(this, message, caption);

        canRemove = (button==KMessageBox::Yes);
    }

    if (!canRemove) return;

    Akonadi::TransactionSequence *transaction = new Akonadi::TransactionSequence();
    addDeleteTodoJobsHelper(current, transaction);
    transaction->start();
#endif
}

void SideBar::addNewContext()
{
#if 0
    bool ok;
    QString summary = KInputDialog::getText(i18n("New Context"),
                                            i18n("Enter context name:"),
                                            QString(), &ok, this);
    summary = summary.trimmed();

    if (!ok || summary.isEmpty()) return;

    QModelIndex parent = m_contextTree->currentIndex();
    parent = GlobalModel::contextsLibrary()->mapToSource(parent);
    parent = GlobalModel::contexts()->mapToSource(parent);
    parent = parent.sibling(parent.row(), TodoFlatModel::Summary);

    GlobalModel::todoCategories()->addCategory(summary, parent);
#endif
}

void SideBar::removeCurrentContext()
{
#if 0
    QModelIndex current = m_contextTree->currentIndex();
    current = GlobalModel::contextsLibrary()->mapToSource(current);
    current = GlobalModel::contexts()->mapToSource(current);
    current = current.sibling(current.row(), 0);

    bool canRemove = true;

    QString summary = GlobalModel::todoCategories()->data(current).toString();

    if (GlobalModel::todoCategories()->rowCount(current)>0) {
        QString message = i18n("Do you really want to delete the context '%1', with all its sub-contexts? All actions won't be associated to those contexts anymore.", summary);
        QString caption = i18n("Delete Context");
        int button = KMessageBox::questionYesNo(this, message, caption);

        canRemove = (button==KMessageBox::Yes);
    }

    if (!canRemove) return;

    GlobalModel::todoCategories()->removeCategory(summary);
#endif
}

<commit_msg>Repair sidebar's toolbar layout (right align)<commit_after>/* This file is part of Zanshin Todo.

   Copyright 2008-2009 Kevin Ottens <ervin@kde.org>

   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 2 of
   the License or (at your option) version 3 or any later version
   accepted by the membership of KDE e.V. (or its successor approved
   by the membership of KDE e.V.), which shall act as a proxy
   defined in Section 14 of version 3 of the license.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
   USA.
*/

#include "sidebar.h"

#if 0
#include <akonadi/item.h>
#include <akonadi/itemcreatejob.h>
#include <akonadi/itemdeletejob.h>
#include <akonadi/transactionsequence.h>

#include <boost/shared_ptr.hpp>

#include <KDE/KCalCore/Todo>
#endif

#include <KDE/Akonadi/EntityTreeView>
#include <KDE/KAction>
#include <KDE/KActionCollection>
#include <KDE/KIcon>
#include <KDE/KLocale>

#include <QtGui/QStackedWidget>
#include <QtGui/QToolBar>
#include <QtGui/QVBoxLayout>

#include "globaldefs.h"
#include "modelstack.h"
#include "sidebarpage.h"

SideBar::SideBar(ModelStack *models, KActionCollection *ac, QWidget *parent)
    : QWidget(parent)
{
    setupActions(ac);

    setLayout(new QVBoxLayout(this));
    m_stack = new QStackedWidget(this);
    layout()->addWidget(m_stack);
    layout()->setContentsMargins(0, 0, 0, 0);

    createPage(models->treeSideBarModel());
    createPage(models->categoriesSideBarModel());

    setupToolBar();
}

void SideBar::createPage(QAbstractItemModel *model)
{
    QAction *separator = new QAction(this);
    separator->setSeparator(true);

    QList<QAction*> contextActions;
    contextActions << m_add
                   << m_remove
                   << separator
                   << m_rename;

    SideBarPage *page = new SideBarPage(model, contextActions, m_stack);

    connect(page->selectionModel(), SIGNAL(currentChanged(QModelIndex, QModelIndex)),
            this, SLOT(updateActions(QModelIndex)));

    m_stack->addWidget(page);
}

void SideBar::setupToolBar()
{
    QHBoxLayout *toolbarLayout = new QHBoxLayout;
    toolbarLayout->setAlignment(Qt::AlignRight);
    static_cast<QBoxLayout*>(layout())->addLayout(toolbarLayout);

    QToolBar *projectBar = new QToolBar(this);
    projectBar->setIconSize(QSize(16, 16));
    projectBar->addAction(m_add);
    projectBar->addAction(m_remove);

    toolbarLayout->addWidget(projectBar);
}

void SideBar::setupActions(KActionCollection *ac)
{
    m_add = ac->addAction("sidebar_new", this, SLOT(onAddItem()));
    m_add->setText(i18n("New"));
    m_add->setIcon(KIcon("list-add"));

    m_remove = ac->addAction("sidebar_remove", this, SLOT(onRemoveItem()));
    m_remove->setText(i18n("Remove"));
    m_remove->setIcon(KIcon("list-remove"));

    m_rename = ac->addAction("sidebar_rename", this, SLOT(onRenameItem()));
    m_rename->setText(i18n("Rename"));
    m_rename->setIcon(KIcon("edit-rename"));

    m_previous = ac->addAction("sidebar_go_previous", this, SLOT(onPreviousItem()));
    m_previous->setText(i18n("Previous"));
    m_previous->setIcon(KIcon("go-previous"));
    m_previous->setShortcut(Qt::ALT | Qt::Key_Up);

    m_next = ac->addAction("sidebar_go_next", this, SLOT(onNextItem()));
    m_next->setText(i18n("Next"));
    m_next->setIcon(KIcon("go-next"));
    m_next->setShortcut(Qt::ALT | Qt::Key_Down);
}

void SideBar::setMode(Zanshin::ApplicationMode mode)
{
    switch (mode) {
    case Zanshin::ProjectMode:
        m_stack->setCurrentIndex(0);
        m_add->setText("New Project");
        m_remove->setText("Remove Project");
        m_rename->setText("Rename Project");
        m_previous->setText("Previous Project");
        m_next->setText("Next Project");
        break;

    case Zanshin::CategoriesMode:
        m_stack->setCurrentIndex(1);
        m_add->setText("New Category");
        m_remove->setText("Remove Category");
        m_rename->setText("Rename Category");
        m_previous->setText("Previous Category");
        m_next->setText("Next Category");
        break;
    }

    updateActions(currentPage()->selectionModel()->currentIndex());
}

QItemSelectionModel *SideBar::projectSelection() const
{
    return static_cast<SideBarPage*>(m_stack->widget(0))->selectionModel();
}

QItemSelectionModel *SideBar::categoriesSelection() const
{
    return static_cast<SideBarPage*>(m_stack->widget(1))->selectionModel();
}

void SideBar::updateActions(const QModelIndex &index)
{
    Zanshin::ItemType type = (Zanshin::ItemType) index.data(Zanshin::ItemTypeRole).toInt();

    m_add->setEnabled( type == Zanshin::Collection
                    || type == Zanshin::ProjectTodo
                    || type == Zanshin::CategoryRoot
                    || type == Zanshin::Category);

    m_remove->setEnabled( type == Zanshin::ProjectTodo
                       || type == Zanshin::Category );

    m_rename->setEnabled( type == Zanshin::ProjectTodo
                       || type == Zanshin::Category );
}

void SideBar::onAddItem()
{
    currentPage()->addNewItem();
}

void SideBar::onRemoveItem()
{
    currentPage()->removeCurrentItem();
}

void SideBar::onRenameItem()
{
    currentPage()->renameCurrentItem();
}

void SideBar::onPreviousItem()
{
    currentPage()->selectPreviousItem();
}

void SideBar::onNextItem()
{
    currentPage()->selectNextItem();
}

SideBarPage *SideBar::currentPage() const
{
    return static_cast<SideBarPage*>(m_stack->currentWidget());
}

SideBarPage *SideBar::page(int idx) const
{
    return static_cast<SideBarPage*>(m_stack->widget(idx));
}

void SideBar::addNewProject()
{
#if 0
    bool ok;
    QString summary = KInputDialog::getText(i18n("New Project"),
                                            i18n("Enter project name:"),
                                            QString(), &ok, this);
    summary = summary.trimmed();

    if (!ok || summary.isEmpty()) return;

    QModelIndex parent = m_projectTree->currentIndex();
    parent = GlobalModel::projectsLibrary()->mapToSource(parent);
    parent = GlobalModel::projects()->mapToSource(parent);
    parent = parent.sibling(parent.row(), TodoFlatModel::RemoteId);

    QString parentRemoteId = GlobalModel::todoTree()->data(parent).toString();

    KCalCore::Todo *todo = new KCalCore::Todo();
    todo->setSummary(summary);
    todo->addComment("X-Zanshin-Project");

    if (!parentRemoteId.isEmpty()) {
        todo->setRelatedTo(parentRemoteId);
    }

    IncidencePtr incidence(todo);
    Akonadi::Item item;
    item.setMimeType("application/x-vnd.akonadi.calendar.todo");
    item.setPayload<IncidencePtr>(incidence);

    Akonadi::Collection collection = GlobalModel::todoFlat()->collection();
    Akonadi::ItemCreateJob *job = new Akonadi::ItemCreateJob(item, collection);
    job->start();
#endif
}

#if 0
void addDeleteTodoJobsHelper(const QModelIndex &index, Akonadi::TransactionSequence *transaction)
{
    for (int i=0; i<GlobalModel::todoTree()->rowCount(index); i++) {
        addDeleteTodoJobsHelper(index.child(i, 0), transaction);
    }

    Akonadi::Item item = GlobalModel::todoTree()->itemForIndex(index);
    new Akonadi::ItemDeleteJob(item, transaction);
}
#endif

void SideBar::removeCurrentProject()
{
#if 0
    QModelIndex current = m_projectTree->currentIndex();
    current = GlobalModel::projectsLibrary()->mapToSource(current);
    current = GlobalModel::projects()->mapToSource(current);
    current = current.sibling(current.row(), 0);

    bool canRemove = true;

    if (GlobalModel::todoTree()->rowCount(current)>0) {
        QString summary = GlobalModel::todoTree()->data(current).toString();
        int rowType = GlobalModel::todoTree()->data(current.sibling(current.row(), TodoFlatModel::RowType)).toInt();
        QString message;
        QString caption;
        if (rowType==TodoFlatModel::FolderTodo) {
            message = i18n("Do you really want to delete the folder '%1', with all its projects and actions?", summary);
            caption = i18n("Delete Folder");
        } else {
            message = i18n("Do you really want to delete the project '%1', with all its actions?", summary);
            caption = i18n("Delete Project");
        }
        int button = KMessageBox::questionYesNo(this, message, caption);

        canRemove = (button==KMessageBox::Yes);
    }

    if (!canRemove) return;

    Akonadi::TransactionSequence *transaction = new Akonadi::TransactionSequence();
    addDeleteTodoJobsHelper(current, transaction);
    transaction->start();
#endif
}

void SideBar::addNewContext()
{
#if 0
    bool ok;
    QString summary = KInputDialog::getText(i18n("New Context"),
                                            i18n("Enter context name:"),
                                            QString(), &ok, this);
    summary = summary.trimmed();

    if (!ok || summary.isEmpty()) return;

    QModelIndex parent = m_contextTree->currentIndex();
    parent = GlobalModel::contextsLibrary()->mapToSource(parent);
    parent = GlobalModel::contexts()->mapToSource(parent);
    parent = parent.sibling(parent.row(), TodoFlatModel::Summary);

    GlobalModel::todoCategories()->addCategory(summary, parent);
#endif
}

void SideBar::removeCurrentContext()
{
#if 0
    QModelIndex current = m_contextTree->currentIndex();
    current = GlobalModel::contextsLibrary()->mapToSource(current);
    current = GlobalModel::contexts()->mapToSource(current);
    current = current.sibling(current.row(), 0);

    bool canRemove = true;

    QString summary = GlobalModel::todoCategories()->data(current).toString();

    if (GlobalModel::todoCategories()->rowCount(current)>0) {
        QString message = i18n("Do you really want to delete the context '%1', with all its sub-contexts? All actions won't be associated to those contexts anymore.", summary);
        QString caption = i18n("Delete Context");
        int button = KMessageBox::questionYesNo(this, message, caption);

        canRemove = (button==KMessageBox::Yes);
    }

    if (!canRemove) return;

    GlobalModel::todoCategories()->removeCategory(summary);
#endif
}

<|endoftext|>


<commit_before><commit_msg>i965/vec4: Correct MUL destination hazard<commit_after><|endoftext|>


<commit_before><commit_msg>fix issue with *Paged* tests<commit_after><|endoftext|>


<commit_before>#include <catch.hpp>

#include <regex>
#include "test_data.hpp"
#include "libslic3r.h"

using namespace Slic3r::Test;

std::regex perimeters_regex("^G1 X[-0-9.]* Y[-0-9.]* E[-0-9.]* ; perimeter[ ]*$");
std::regex infill_regex("^G1 X[-0-9.]* Y[-0-9.]* E[-0-9.]* ; infill[ ]*$");
std::regex skirt_regex("^G1 X[-0-9.]* Y[-0-9.]* E[-0-9.]* ; skirt[ ]*$");

SCENARIO( "PrintGCode basic functionality", "[!mayfail]") {
    GIVEN("A default configuration and a print test object") {
        auto config {Slic3r::Config::new_from_defaults()};
        auto gcode {std::stringstream("")};

        WHEN("the output is executed with no support material") {
            config->set("first_layer_extrusion_width", 0);
            config->set("gcode_comments", true);
            Slic3r::Model model;
            auto print {Slic3r::Test::init_print({TestMesh::cube_20x20x20}, model, config)};
            Slic3r::Test::gcode(gcode, print);
            auto exported {gcode.str()};
            THEN("Some text output is generated.") {
                REQUIRE(exported.size() > 0);
            }
            THEN("Exported text contains slic3r version") {
                REQUIRE(exported.find(SLIC3R_VERSION) != std::string::npos);
            }
            THEN("Exported text contains git commit id") {
                REQUIRE(exported.find("; Git Commit") != std::string::npos);
                REQUIRE(exported.find(BUILD_COMMIT) != std::string::npos);
            }
            THEN("Exported text contains extrusion statistics.") {
                REQUIRE(exported.find("; external perimeters extrusion width") != std::string::npos);
                REQUIRE(exported.find("; perimeters extrusion width") != std::string::npos);
                REQUIRE(exported.find("; infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; solid infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; top solid infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; support material extrusion width") == std::string::npos);
                REQUIRE(exported.find("; first layer extrusion width") == std::string::npos);
            }

            THEN("GCode preamble is emitted.") {
                REQUIRE(exported.find("G21 ; set units to millimeters") != std::string::npos);
            }

            THEN("Config options emitted for print config, default region config, default object config") {
                REQUIRE(exported.find("; first_layer_temperature") != std::string::npos);
                REQUIRE(exported.find("; layer_height") != std::string::npos);
                REQUIRE(exported.find("; fill_density") != std::string::npos);
            }
            THEN("Infill is emitted.") {
                std::smatch has_match;
                REQUIRE(std::regex_search(exported, has_match, infill_regex));
            }
            THEN("Perimeters are emitted.") {
                std::smatch has_match;
                REQUIRE(std::regex_search(exported, has_match, perimeters_regex));
            }
            THEN("Skirt is emitted.") {
                std::smatch has_match;
                REQUIRE(std::regex_search(exported, has_match, skirt_regex));
            }
        }
        WHEN("the output is executed with support material") {
            Slic3r::Model model;
            config->set("first_layer_extrusion_width", 0);
            config->set("support_material", true);
            config->set("raft_layers", 3);
            auto print {Slic3r::Test::init_print({TestMesh::cube_20x20x20}, model, config)};
            Slic3r::Test::gcode(gcode, print);
            auto exported {gcode.str()};
            THEN("Some text output is generated.") {
                REQUIRE(exported.size() > 0);
            }
            THEN("Exported text contains extrusion statistics.") {
                REQUIRE(exported.find("; external perimeters extrusion width") != std::string::npos);
                REQUIRE(exported.find("; perimeters extrusion width") != std::string::npos);
                REQUIRE(exported.find("; infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; solid infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; top solid infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; support material extrusion width") != std::string::npos);
                REQUIRE(exported.find("; first layer extrusion width") == std::string::npos);
            }
        }
        WHEN("the output is executed with a separate first layer extrusion width") {
            Slic3r::Model model;
            config->set("first_layer_extrusion_width", 0.5);
            auto print {Slic3r::Test::init_print({TestMesh::cube_20x20x20}, model, config)};
            Slic3r::Test::gcode(gcode, print);
            auto exported {gcode.str()};
            THEN("Some text output is generated.") {
                REQUIRE(exported.size() > 0);
            }
            THEN("Exported text contains extrusion statistics.") {
                REQUIRE(exported.find("; external perimeters extrusion width") != std::string::npos);
                REQUIRE(exported.find("; perimeters extrusion width") != std::string::npos);
                REQUIRE(exported.find("; infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; solid infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; top solid infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; support material extrusion width") == std::string::npos);
                REQUIRE(exported.find("; first layer extrusion width") != std::string::npos);
            }
        }
        WHEN("Cooling is enabled and the fan is disabled.") {
            config->set("cooling", true);
            config->set("disable_fan_first_layers", 5);
            Slic3r::Model model;
            auto print {Slic3r::Test::init_print({TestMesh::cube_20x20x20}, model, config)};
            Slic3r::Test::gcode(gcode, print);
            auto exported {gcode.str()};
            THEN("GCode to disable fan is emitted."){
                REQUIRE(exported.find("M107") != std::string::npos);
            }
        }

        gcode.clear();
    }
}
<commit_msg>Make sure processing is done.<commit_after>#include <catch.hpp>

#include <regex>
#include "test_data.hpp"
#include "libslic3r.h"

using namespace Slic3r::Test;

std::regex perimeters_regex("^G1 X[-0-9.]* Y[-0-9.]* E[-0-9.]* ; perimeter[ ]*$");
std::regex infill_regex("^G1 X[-0-9.]* Y[-0-9.]* E[-0-9.]* ; infill[ ]*$");
std::regex skirt_regex("^G1 X[-0-9.]* Y[-0-9.]* E[-0-9.]* ; skirt[ ]*$");

SCENARIO( "PrintGCode basic functionality", "[!mayfail]") {
    GIVEN("A default configuration and a print test object") {
        auto config {Slic3r::Config::new_from_defaults()};
        auto gcode {std::stringstream("")};

        WHEN("the output is executed with no support material") {
            config->set("first_layer_extrusion_width", 0);
            config->set("gcode_comments", true);
            Slic3r::Model model;
            auto print {Slic3r::Test::init_print({TestMesh::cube_20x20x20}, model, config)};
            print->process();
            Slic3r::Test::gcode(gcode, print);
            auto exported {gcode.str()};
            THEN("Some text output is generated.") {
                REQUIRE(exported.size() > 0);
            }
            THEN("Exported text contains slic3r version") {
                REQUIRE(exported.find(SLIC3R_VERSION) != std::string::npos);
            }
            THEN("Exported text contains git commit id") {
                REQUIRE(exported.find("; Git Commit") != std::string::npos);
                REQUIRE(exported.find(BUILD_COMMIT) != std::string::npos);
            }
            THEN("Exported text contains extrusion statistics.") {
                REQUIRE(exported.find("; external perimeters extrusion width") != std::string::npos);
                REQUIRE(exported.find("; perimeters extrusion width") != std::string::npos);
                REQUIRE(exported.find("; infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; solid infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; top solid infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; support material extrusion width") == std::string::npos);
                REQUIRE(exported.find("; first layer extrusion width") == std::string::npos);
            }

            THEN("GCode preamble is emitted.") {
                REQUIRE(exported.find("G21 ; set units to millimeters") != std::string::npos);
            }

            THEN("Config options emitted for print config, default region config, default object config") {
                REQUIRE(exported.find("; first_layer_temperature") != std::string::npos);
                REQUIRE(exported.find("; layer_height") != std::string::npos);
                REQUIRE(exported.find("; fill_density") != std::string::npos);
            }
            THEN("Infill is emitted.") {
                std::smatch has_match;
                REQUIRE(std::regex_search(exported, has_match, infill_regex));
            }
            THEN("Perimeters are emitted.") {
                std::smatch has_match;
                REQUIRE(std::regex_search(exported, has_match, perimeters_regex));
            }
            THEN("Skirt is emitted.") {
                std::smatch has_match;
                REQUIRE(std::regex_search(exported, has_match, skirt_regex));
            }
        }
        WHEN("the output is executed with support material") {
            Slic3r::Model model;
            config->set("first_layer_extrusion_width", 0);
            config->set("support_material", true);
            config->set("raft_layers", 3);
            auto print {Slic3r::Test::init_print({TestMesh::cube_20x20x20}, model, config)};
            Slic3r::Test::gcode(gcode, print);
            auto exported {gcode.str()};
            THEN("Some text output is generated.") {
                REQUIRE(exported.size() > 0);
            }
            THEN("Exported text contains extrusion statistics.") {
                REQUIRE(exported.find("; external perimeters extrusion width") != std::string::npos);
                REQUIRE(exported.find("; perimeters extrusion width") != std::string::npos);
                REQUIRE(exported.find("; infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; solid infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; top solid infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; support material extrusion width") != std::string::npos);
                REQUIRE(exported.find("; first layer extrusion width") == std::string::npos);
            }
        }
        WHEN("the output is executed with a separate first layer extrusion width") {
            Slic3r::Model model;
            config->set("first_layer_extrusion_width", 0.5);
            auto print {Slic3r::Test::init_print({TestMesh::cube_20x20x20}, model, config)};
            Slic3r::Test::gcode(gcode, print);
            auto exported {gcode.str()};
            THEN("Some text output is generated.") {
                REQUIRE(exported.size() > 0);
            }
            THEN("Exported text contains extrusion statistics.") {
                REQUIRE(exported.find("; external perimeters extrusion width") != std::string::npos);
                REQUIRE(exported.find("; perimeters extrusion width") != std::string::npos);
                REQUIRE(exported.find("; infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; solid infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; top solid infill extrusion width") != std::string::npos);
                REQUIRE(exported.find("; support material extrusion width") == std::string::npos);
                REQUIRE(exported.find("; first layer extrusion width") != std::string::npos);
            }
        }
        WHEN("Cooling is enabled and the fan is disabled.") {
            config->set("cooling", true);
            config->set("disable_fan_first_layers", 5);
            Slic3r::Model model;
            auto print {Slic3r::Test::init_print({TestMesh::cube_20x20x20}, model, config)};
            Slic3r::Test::gcode(gcode, print);
            auto exported {gcode.str()};
            THEN("GCode to disable fan is emitted."){
                REQUIRE(exported.find("M107") != std::string::npos);
            }
        }

        gcode.clear();
    }
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include "base/logging.h"
#include "gfx_es2/draw_buffer.h"
#include "gfx/texture_atlas.h"
#include "input/input_state.h"
#include "virtual_input.h"

TouchButton::TouchButton(const Atlas *atlas, int imageIndex, int overlayImageIndex, int button, int rotationAngle, bool mirror_h)
	: atlas_(atlas), imageIndex_(imageIndex), overlayImageIndex_(overlayImageIndex), button_(button), mirror_h_(mirror_h)
{
	memset(pointerDown, 0, sizeof(pointerDown));
	w_ = atlas_->images[imageIndex_].w;
	h_ = atlas_->images[imageIndex_].h;
	rotationAngle_ = (float)rotationAngle * 3.1415927 / 180.0f;
	isDown_ = false;
}

void TouchButton::update(InputState &input_state)
{
	bool down = false;
	for (int i = 0; i < MAX_POINTERS; i++) {
		if (input_state.pointer_down[i] && isInside(input_state.pointer_x[i], input_state.pointer_y[i]))
			down = true;
	}

	if (down)
		input_state.pad_buttons |= button_;

	isDown_ = (input_state.pad_buttons & button_) != 0;
}

void TouchButton::draw(DrawBuffer &db, uint32_t color, uint32_t colorOverlay)
{
	float scale = 1.0f;
	if (isDown_) {
		color |= 0xFF000000;
		colorOverlay |= 0xFF000000;
		scale = 2.0f;
	}
	scale *= scale_;
	// We only mirror background
	db.DrawImageRotated(imageIndex_, x_ + w_*scale_/2, y_ + h_*scale_/2, scale, rotationAngle_, color, mirror_h_);
	if (overlayImageIndex_ != -1)
		db.DrawImageRotated(overlayImageIndex_, x_ + w_*scale_/2, y_ + h_*scale_/2, scale, rotationAngle_, colorOverlay);
}

TouchCrossPad::TouchCrossPad(const Atlas *atlas, int arrowIndex, int overlayIndex)
	: atlas_(atlas), arrowIndex_(arrowIndex), overlayIndex_(overlayIndex)
{

}

void TouchCrossPad::update(InputState &input_state)
{
	float stick_size_ = radius_ * 2;
	float inv_stick_size = 1.0f / (stick_size_ * scale_);
	const float deadzone = 0.17f;
	bool all_up = true;

	for (int i = 0; i < MAX_POINTERS; i++) {
		if (input_state.pointer_down[i]) {
			float dx = (input_state.pointer_x[i] - x_) * inv_stick_size;
			float dy = (input_state.pointer_y[i] - y_) * inv_stick_size;
			float rad = sqrtf(dx*dx+dy*dy);
			if (rad < deadzone || rad > 1.0f)
				continue;

			all_up = false;

			if (dx == 0 && dy == 0)
				continue;

			int direction = (int)(floorf((atan2f(dy, dx) / (2 * M_PI) * 8) + 0.5f)) & 7;

			input_state.pad_buttons &= ~(PAD_BUTTON_LEFT | PAD_BUTTON_RIGHT | PAD_BUTTON_UP | PAD_BUTTON_DOWN);
			switch (direction) {
			case 0: input_state.pad_buttons |= PAD_BUTTON_RIGHT; break;
			case 1: input_state.pad_buttons |= PAD_BUTTON_RIGHT | PAD_BUTTON_DOWN; break;
			case 2: input_state.pad_buttons |= PAD_BUTTON_DOWN; break;
			case 3: input_state.pad_buttons |= PAD_BUTTON_DOWN | PAD_BUTTON_LEFT; break;
			case 4: input_state.pad_buttons |= PAD_BUTTON_LEFT; break;
			case 5: input_state.pad_buttons |= PAD_BUTTON_UP | PAD_BUTTON_LEFT; break;
			case 6: input_state.pad_buttons |= PAD_BUTTON_UP; break;
			case 7: input_state.pad_buttons |= PAD_BUTTON_UP | PAD_BUTTON_RIGHT; break;
			}
		}
	}
	down_ = input_state.pad_buttons & (PAD_BUTTON_LEFT | PAD_BUTTON_RIGHT | PAD_BUTTON_UP | PAD_BUTTON_DOWN);
}

void TouchCrossPad::draw(DrawBuffer &db, uint32_t color, uint32_t colorOverlay)
{
	static const float xoff[4] = {1, 0, -1, 0};
	static const float yoff[4] = {0, 1, 0, -1};
	static const int dir[4] = {PAD_BUTTON_RIGHT, PAD_BUTTON_DOWN, PAD_BUTTON_LEFT, PAD_BUTTON_UP};
	for (int i = 0; i < 4; i++) {
		float x = x_ + xoff[i] * scale_ * radius_;
		float y = y_ + yoff[i] * scale_ * radius_;
		float angle = i * M_PI / 2;
		float imgScale = (down_ & dir[i]) ? scale_ * 2 : scale_;
		db.DrawImageRotated(arrowIndex_, x, y, imgScale, angle + PI, color, false);
		if (overlayIndex_ != -1)
			db.DrawImageRotated(overlayIndex_, x, y, imgScale, angle + PI, colorOverlay);
	}
}

TouchStick::TouchStick(const Atlas *atlas, int bgImageIndex, int stickImageIndex, int stick)
	: atlas_(atlas), bgImageIndex_(bgImageIndex), stickImageIndex_(stickImageIndex), stick_(stick)
{
	stick_size_ = atlas_->images[bgImageIndex].w / 3.5f;
	memset(dragging_, 0, sizeof(dragging_));
	memset(lastPointerDown_, 0, sizeof(lastPointerDown_));
}

void TouchStick::update(InputState &input_state)
{
	float inv_stick_size = 1.0f / (stick_size_ * scale_);
	bool all_up = true;
	for (int i = 0; i < MAX_POINTERS; i++) {
		if (input_state.pointer_down[i]) {
			all_up = false;
			float dx = (input_state.pointer_x[i] - stick_x_) * inv_stick_size;
			float dy = (input_state.pointer_y[i] - stick_y_) * inv_stick_size;
			// Ignore outside box
			if (!dragging_[i] && (fabsf(dx) > 1.4f || fabsf(dy) > 1.4f))
				goto skip;
			if (!lastPointerDown_[i] && (fabsf(dx) < 1.4f && fabsf(dy) < 1.4f)) {
				dragging_[i] = true;
			}
			if (!dragging_[i])
				goto skip;

			// Clamp to a circle
			float len = sqrtf(dx * dx + dy * dy);
			if (len > 1.0f) {
				dx /= len;
				dy /= len;
			}
			if (stick_ == 0) {
				input_state.pad_lstick_x = dx;
				input_state.pad_lstick_y = -dy;
			} else if (stick_ == 1) {
				input_state.pad_rstick_x = dx;
				input_state.pad_rstick_y = -dy;
			}
		} else {
			dragging_[i] = false;
		}
skip:
		lastPointerDown_[i] = input_state.pointer_down[i];
	}

	stick_delta_x_ = input_state.pad_lstick_x;
	stick_delta_y_ = -input_state.pad_lstick_y;
}

void TouchStick::draw(DrawBuffer &db, uint32_t color)
{
	if (bgImageIndex_ != -1)
		db.DrawImage(bgImageIndex_, stick_x_, stick_y_, 1.0f * scale_, color, ALIGN_CENTER);
	db.DrawImage(stickImageIndex_, stick_x_ + stick_delta_x_ * stick_size_ * scale_, stick_y_ + stick_delta_y_ * stick_size_ * scale_, 1.0f * scale_, color, ALIGN_CENTER);
}
<commit_msg>Don't clamp to a circle in the virtual stick.<commit_after>#include <stdio.h>
#include "base/logging.h"
#include "gfx_es2/draw_buffer.h"
#include "gfx/texture_atlas.h"
#include "input/input_state.h"
#include "virtual_input.h"

TouchButton::TouchButton(const Atlas *atlas, int imageIndex, int overlayImageIndex, int button, int rotationAngle, bool mirror_h)
	: atlas_(atlas), imageIndex_(imageIndex), overlayImageIndex_(overlayImageIndex), button_(button), mirror_h_(mirror_h)
{
	memset(pointerDown, 0, sizeof(pointerDown));
	w_ = atlas_->images[imageIndex_].w;
	h_ = atlas_->images[imageIndex_].h;
	rotationAngle_ = (float)rotationAngle * 3.1415927 / 180.0f;
	isDown_ = false;
}

void TouchButton::update(InputState &input_state)
{
	bool down = false;
	for (int i = 0; i < MAX_POINTERS; i++) {
		if (input_state.pointer_down[i] && isInside(input_state.pointer_x[i], input_state.pointer_y[i]))
			down = true;
	}

	if (down)
		input_state.pad_buttons |= button_;

	isDown_ = (input_state.pad_buttons & button_) != 0;
}

void TouchButton::draw(DrawBuffer &db, uint32_t color, uint32_t colorOverlay)
{
	float scale = 1.0f;
	if (isDown_) {
		color |= 0xFF000000;
		colorOverlay |= 0xFF000000;
		scale = 2.0f;
	}
	scale *= scale_;
	// We only mirror background
	db.DrawImageRotated(imageIndex_, x_ + w_*scale_/2, y_ + h_*scale_/2, scale, rotationAngle_, color, mirror_h_);
	if (overlayImageIndex_ != -1)
		db.DrawImageRotated(overlayImageIndex_, x_ + w_*scale_/2, y_ + h_*scale_/2, scale, rotationAngle_, colorOverlay);
}

TouchCrossPad::TouchCrossPad(const Atlas *atlas, int arrowIndex, int overlayIndex)
	: atlas_(atlas), arrowIndex_(arrowIndex), overlayIndex_(overlayIndex)
{

}

void TouchCrossPad::update(InputState &input_state)
{
	float stick_size_ = radius_ * 2;
	float inv_stick_size = 1.0f / (stick_size_ * scale_);
	const float deadzone = 0.17f;
	bool all_up = true;

	for (int i = 0; i < MAX_POINTERS; i++) {
		if (input_state.pointer_down[i]) {
			float dx = (input_state.pointer_x[i] - x_) * inv_stick_size;
			float dy = (input_state.pointer_y[i] - y_) * inv_stick_size;
			float rad = sqrtf(dx*dx+dy*dy);
			if (rad < deadzone || rad > 1.0f)
				continue;

			all_up = false;

			if (dx == 0 && dy == 0)
				continue;

			int direction = (int)(floorf((atan2f(dy, dx) / (2 * M_PI) * 8) + 0.5f)) & 7;

			input_state.pad_buttons &= ~(PAD_BUTTON_LEFT | PAD_BUTTON_RIGHT | PAD_BUTTON_UP | PAD_BUTTON_DOWN);
			switch (direction) {
			case 0: input_state.pad_buttons |= PAD_BUTTON_RIGHT; break;
			case 1: input_state.pad_buttons |= PAD_BUTTON_RIGHT | PAD_BUTTON_DOWN; break;
			case 2: input_state.pad_buttons |= PAD_BUTTON_DOWN; break;
			case 3: input_state.pad_buttons |= PAD_BUTTON_DOWN | PAD_BUTTON_LEFT; break;
			case 4: input_state.pad_buttons |= PAD_BUTTON_LEFT; break;
			case 5: input_state.pad_buttons |= PAD_BUTTON_UP | PAD_BUTTON_LEFT; break;
			case 6: input_state.pad_buttons |= PAD_BUTTON_UP; break;
			case 7: input_state.pad_buttons |= PAD_BUTTON_UP | PAD_BUTTON_RIGHT; break;
			}
		}
	}
	down_ = input_state.pad_buttons & (PAD_BUTTON_LEFT | PAD_BUTTON_RIGHT | PAD_BUTTON_UP | PAD_BUTTON_DOWN);
}

void TouchCrossPad::draw(DrawBuffer &db, uint32_t color, uint32_t colorOverlay)
{
	static const float xoff[4] = {1, 0, -1, 0};
	static const float yoff[4] = {0, 1, 0, -1};
	static const int dir[4] = {PAD_BUTTON_RIGHT, PAD_BUTTON_DOWN, PAD_BUTTON_LEFT, PAD_BUTTON_UP};
	for (int i = 0; i < 4; i++) {
		float x = x_ + xoff[i] * scale_ * radius_;
		float y = y_ + yoff[i] * scale_ * radius_;
		float angle = i * M_PI / 2;
		float imgScale = (down_ & dir[i]) ? scale_ * 2 : scale_;
		db.DrawImageRotated(arrowIndex_, x, y, imgScale, angle + PI, color, false);
		if (overlayIndex_ != -1)
			db.DrawImageRotated(overlayIndex_, x, y, imgScale, angle + PI, colorOverlay);
	}
}

TouchStick::TouchStick(const Atlas *atlas, int bgImageIndex, int stickImageIndex, int stick)
	: atlas_(atlas), bgImageIndex_(bgImageIndex), stickImageIndex_(stickImageIndex), stick_(stick)
{
	stick_size_ = atlas_->images[bgImageIndex].w / 3.5f;
	memset(dragging_, 0, sizeof(dragging_));
	memset(lastPointerDown_, 0, sizeof(lastPointerDown_));
}

void TouchStick::update(InputState &input_state)
{
	float inv_stick_size = 1.0f / (stick_size_ * scale_);
	bool all_up = true;
	for (int i = 0; i < MAX_POINTERS; i++) {
		if (input_state.pointer_down[i]) {
			all_up = false;
			float dx = (input_state.pointer_x[i] - stick_x_) * inv_stick_size;
			float dy = (input_state.pointer_y[i] - stick_y_) * inv_stick_size;
			// Ignore outside box
			if (!dragging_[i] && (fabsf(dx) > 1.4f || fabsf(dy) > 1.4f))
				goto skip;
			if (!lastPointerDown_[i] && (fabsf(dx) < 1.4f && fabsf(dy) < 1.4f)) {
				dragging_[i] = true;
			}
			if (!dragging_[i])
				goto skip;

			// Do not clamp to a circle! The PSP has nearly square range!

			// Old code to clamp to a circle
			// float len = sqrtf(dx * dx + dy * dy);
			// if (len > 1.0f) {
			//	dx /= len;
			//	dy /= len;
			//}

			if (stick_ == 0) {
				input_state.pad_lstick_x = dx;
				input_state.pad_lstick_y = -dy;
			} else if (stick_ == 1) {
				input_state.pad_rstick_x = dx;
				input_state.pad_rstick_y = -dy;
			}
		} else {
			dragging_[i] = false;
		}
skip:
		lastPointerDown_[i] = input_state.pointer_down[i];
	}

	stick_delta_x_ = input_state.pad_lstick_x;
	stick_delta_y_ = -input_state.pad_lstick_y;
}

void TouchStick::draw(DrawBuffer &db, uint32_t color)
{
	if (bgImageIndex_ != -1)
		db.DrawImage(bgImageIndex_, stick_x_, stick_y_, 1.0f * scale_, color, ALIGN_CENTER);
	db.DrawImage(stickImageIndex_, stick_x_ + stick_delta_x_ * stick_size_ * scale_, stick_y_ + stick_delta_y_ * stick_size_ * scale_, 1.0f * scale_, color, ALIGN_CENTER);
}
<|endoftext|>


<commit_before>#ifndef DUNE_STUFF_FUNCTION_INTERFACE_HH
#define DUNE_STUFF_FUNCTION_INTERFACE_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG

#include <vector>

#include <dune/common/shared_ptr.hh>
#include <dune/common/fvector.hh>
#include <dune/common/dynvector.hh>
#include <dune/common/function.hh>

#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/parameter.hh>

namespace Dune {
namespace Stuff {

//! forward
template< class RangeFieldImp >
class FunctionAffineSeparablCoefficient;

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class FunctionInterface
{
public:
  typedef FunctionInterface<  DomainFieldImp, domainDim, RangeFieldImp, rangeDim > ThisType;

  typedef DomainFieldImp                                  DomainFieldType;
  static const int                                        dimDomain = domainDim;
  typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType;

  typedef RangeFieldImp                                 RangeFieldType;
  static const int                                      dimRange = rangeDim;
  typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType;

  typedef Common::Parameter::FieldType  ParamFieldType;
  static const int                      maxParamDim = Common::Parameter::maxDim;
  typedef Common::Parameter::Type       ParamType;

  typedef ThisType                                            ComponentType;
  typedef FunctionAffineSeparablCoefficient< RangeFieldType > CoefficientType;

  virtual ~FunctionInterface() {}

  static std::string id()
  {
    return "function";
  }

  /** \defgroup type ´´Theis method has to be implemented for parametric functions and determines,
   *                   which evaluate() is callable.''
   */
  /* @{ */
  virtual bool parametric() const
  {
    return false;
  }
  /* @} */

  /** \defgroup info ´´These methods should be implemented in order to identify the function.'' */
  /* @{ */
  virtual std::string name() const
  {
    return id();
  }

  virtual int order() const
  {
    return -1;
  }
  /* @} */

  /** \defgroup nonparametric-must ´´These methods have to be implemented, if parametric() == false.'' */
  /* @{ */
  virtual void evaluate(const DomainType& /*_x*/, RangeType& /*_ret*/) const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == false!");
  }
  /* @} */

  /** \defgroup parametric-must ´´These methods have to be implemented, if parametric() == true.'' */
  /* @{ */
  virtual void evaluate(const DomainType& /*_x*/, const ParamType& /*_mu*/, RangeType& /*_ret*/) const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual size_t paramSize() const
  {
    if (!parametric())
      return 0;
    else
      DUNE_THROW(Dune::NotImplemented,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< ParamType >& paramRange() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< std::string >& paramExplanation() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual bool affineparametric() const
  {
    return false;
  }
  /* @} */

  /** \defgroup affineparametric ´´These methods have to be implemented, if affineparametric() == true.'' */
  /* @{ */
  virtual size_t numComponents() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if affineparametric() == true!");
  }

  virtual const std::vector< Dune::shared_ptr< const ComponentType > >& components() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if affineparametric() == true!");
  }

  virtual size_t numCoefficients() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if affineparametric() == true!");
  }

  virtual const std::vector< Dune::shared_ptr< const CoefficientType > >& coefficients() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if affineparametric() == true!");
  }
  /* @} */

  /** \defgroup provided ´´These methods are provided by the interface itself, but may not be implemented optimal.'' */
  /* @{ */
  virtual RangeType evaluate(const DomainType& _x) const
  {
    assert(!parametric());
    RangeType ret;
    evaluate(_x, ret);
    return ret;
  }
}; // class FunctionInterface

} // namespace Stuff
} // namespace Dune

#include "parametric/separable/coefficient.hh"

#endif // DUNE_STUFF_FUNCTION_INTERFACE_HH
<commit_msg>[function.interface] fixed affineparametric coefficient<commit_after>#ifndef DUNE_STUFF_FUNCTION_INTERFACE_HH
#define DUNE_STUFF_FUNCTION_INTERFACE_HH

#ifdef HAVE_CMAKE_CONFIG
  #include "cmake_config.h"
#elif defined (HAVE_CONFIG_H)
  #include <config.h>
#endif // ifdef HAVE_CMAKE_CONFIG

#include <vector>

#include <dune/common/shared_ptr.hh>
#include <dune/common/fvector.hh>
#include <dune/common/dynvector.hh>
#include <dune/common/function.hh>

#include <dune/stuff/common/color.hh>
#include <dune/stuff/common/parameter.hh>

namespace Dune {
namespace Stuff {

//! forward
template< class RangeFieldImp >
class FunctionAffineSeparablCoefficient;

template< class DomainFieldImp, int domainDim, class RangeFieldImp, int rangeDim >
class FunctionInterface
{
public:
  typedef FunctionInterface<  DomainFieldImp, domainDim, RangeFieldImp, rangeDim > ThisType;

  typedef DomainFieldImp                                  DomainFieldType;
  static const int                                        dimDomain = domainDim;
  typedef Dune::FieldVector< DomainFieldType, dimDomain > DomainType;

  typedef RangeFieldImp                                 RangeFieldType;
  static const int                                      dimRange = rangeDim;
  typedef Dune::FieldVector< RangeFieldType, dimRange > RangeType;

  typedef Common::Parameter::FieldType  ParamFieldType;
  static const int                      maxParamDim = Common::Parameter::maxDim;
  typedef Common::Parameter::Type       ParamType;

  typedef ThisType                                            ComponentType;
  typedef FunctionAffineSeparablCoefficient< RangeFieldType > CoefficientType;

  virtual ~FunctionInterface() {}

  static std::string id()
  {
    return "function";
  }

  /** \defgroup type ´´Theis method has to be implemented for parametric functions and determines,
   *                   which evaluate() is callable.''
   */
  /* @{ */
  virtual bool parametric() const
  {
    return false;
  }
  /* @} */

  /** \defgroup info ´´These methods should be implemented in order to identify the function.'' */
  /* @{ */
  virtual std::string name() const
  {
    return id();
  }

  virtual int order() const
  {
    return -1;
  }
  /* @} */

  /** \defgroup nonparametric-must ´´These methods have to be implemented, if parametric() == false.'' */
  /* @{ */
  virtual void evaluate(const DomainType& /*_x*/, RangeType& /*_ret*/) const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == false!");
  }
  /* @} */

  /** \defgroup parametric-must ´´These methods have to be implemented, if parametric() == true.'' */
  /* @{ */
  virtual void evaluate(const DomainType& /*_x*/, const ParamType& /*_mu*/, RangeType& /*_ret*/) const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual size_t paramSize() const
  {
    if (!parametric())
      return 0;
    else
      DUNE_THROW(Dune::NotImplemented,
                 "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< ParamType >& paramRange() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual const std::vector< std::string >& paramExplanation() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if parametric() == true!");
  }

  virtual bool affineparametric() const
  {
    return false;
  }
  /* @} */

  /** \defgroup affineparametric ´´These methods have to be implemented, if affineparametric() == true.'' */
  /* @{ */
  virtual size_t numComponents() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if affineparametric() == true!");
  }

  virtual const std::vector< Dune::shared_ptr< const ComponentType > >& components() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if affineparametric() == true!");
  }

  virtual size_t numCoefficients() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if affineparametric() == true!");
  }

  virtual const std::vector< Dune::shared_ptr< const CoefficientType > >& coefficients() const
  {
    DUNE_THROW(Dune::NotImplemented,
               "\n" << Dune::Stuff::Common::colorStringRed("ERROR:") << " implement me if affineparametric() == true!");
  }
  /* @} */

  /** \defgroup provided ´´These methods are provided by the interface itself, but may not be implemented optimal.'' */
  /* @{ */
  virtual RangeType evaluate(const DomainType& _x) const
  {
    assert(!parametric());
    RangeType ret;
    evaluate(_x, ret);
    return ret;
  }
}; // class FunctionInterface

} // namespace Stuff
} // namespace Dune

#include "affineparametric/coefficient.hh"

#endif // DUNE_STUFF_FUNCTION_INTERFACE_HH
<|endoftext|>