<commit_before>// GUI.cpp
// 29. April 2017
// Created by:
// 		Bryan Burkhardt (bmburkhardt@alaska.edu)
// 		Alexander Eckert (aeckert@alaska.edu)
// 		Jeremiah Jacobson (jjjacobson2@alaska.edu)
// 		Jarye Murphy (@alaska.edu)
// 		Cameron Showalter (@alaska.edu)
//
// Source file for GUI class

#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <iostream>

#include "../include/textureManager.hpp"
#include "../include/GUI.hpp"

GUI::GUI(std::shared_ptr<Music> music) : music(music) {
	std::cout << "ctor GUI\n";
	texmgr = std::make_unique<TextureManager>();
	loadTextures();
	window.create(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "MusicPlayer",
		sf::Style::Titlebar | sf::Style::Close);
	setTextures();

}

bool GUI::clickInSprite(sf::Sprite s, int x , int y) {
	if (x > s.getGlobalBounds().left && x <
			(s.getGlobalBounds().left + s.getGlobalBounds().width) &&
			y > s.getGlobalBounds().top && y < (s.getGlobalBounds().top
			+ s.getGlobalBounds().height)) {
		return true;
	}
	return false;
}

std::string GUI::trimFilename(const std::string& str) {
  std::size_t found = str.find_last_of("/\\");
  return str.substr(found+1);
}

void GUI::draw() {
	window.clear(sf::Color::Green);

	// draw buttons
	window.draw(musicPlayerBG  );
	window.draw(playPauseButton);			//0
	window.draw(prevButton); 				//1
	window.draw(nextButton);				//2
	window.draw(muteButton); 				//3
	window.draw(increaseVolumeButton);		//4
	window.draw(decreaseVolumeButton);		//5

	window.draw(prevSong);
	window.draw(currentSong);
	window.draw(nextSong);
	window.draw(next2Song);
	window.draw(next3Song);
	window.draw(next4Song);
	window.display();

	return;
}

void GUI::loadTextures() {
	texmgr->loadTexture("musicPlayerBGTex", "../res/background/musicplayerbg.png");
	texmgr->loadTexture("playTex", "../res/icons/play.png");
	texmgr->loadTexture("pauseTex", "../res/icons/pause.png");
	texmgr->loadTexture("prevTex", "../res/icons/previous.png");
	texmgr->loadTexture("nextTex", "../res/icons/next.png");
	texmgr->loadTexture("decreaseVolumeTex", "../res/icons/volume_down.png");
	texmgr->loadTexture("increaseVolumeTex", "../res/icons/volume_up.png");
	texmgr->loadTexture("muteTex", "../res/icons/mute.png");
	texmgr->loadTexture("playTex2", "../res/icons/play2.png");
	texmgr->loadTexture("pauseTex2", "../res/icons/pause2.png");
	texmgr->loadTexture("prevTex2", "../res/icons/previous2.png");
	texmgr->loadTexture("nextTex2", "../res/icons/next2.png");
	texmgr->loadTexture("decreaseVolumeTex2", "../res/icons/volume_down2.png");
	texmgr->loadTexture("increaseVolumeTex2", "../res/icons/volume_up2.png");
	texmgr->loadTexture("muteTexv2", "../res/icons/mutev2.png");
	texmgr->loadTexture("muteTex2", "../res/icons/mute2.png");
	texmgr->loadTexture("muteTexv22", "../res/icons/mutev2-2.png");
	std::cout << "Textures loaded" << std::endl;
}

void GUI::setTextures() {
	spriteVec = {
		playPauseButton,			// 0
		prevButton, 				// 1
		nextButton, 				// 2
		muteButton, 				// 3
		decreaseVolumeButton, 		// 4
		increaseVolumeButton
	};

	// set textures
	musicPlayerBG.setTexture(this->texmgr->getRef("musicPlayerBGTex"));
	playPauseButton.setTexture(this->texmgr->getRef("pauseTex"));
	prevButton.setTexture(this->texmgr->getRef("prevTex"));
	nextButton.setTexture(this->texmgr->getRef("nextTex"));
	muteButton.setTexture(this->texmgr->getRef("muteTex"));
	decreaseVolumeButton.setTexture(this->texmgr->getRef("decreaseVolumeTex"));
	increaseVolumeButton.setTexture(this->texmgr->getRef("increaseVolumeTex"));

	// set positions
	playPauseButton.setPosition(120,210);
	prevButton.setPosition(30,210);
	nextButton.setPosition(210,210);
	decreaseVolumeButton.setPosition(120,120);
	muteButton.setPosition(30,120);
	increaseVolumeButton.setPosition(210,120);
}

void GUI::stylePlaylist() {
	if(!font.loadFromFile("../res/fonts/TravelingTypewriter.ttf"))
		std::cout << "Font couldn't be found" << std::endl;
	else
		std::cout << "Font was found" << std::endl;

	textVec = {
		prevSong,
		currentSong,
		nextSong,
		next2Song,
		next3Song,
		next4Song
	};

	int counter = 35;
	for(auto i=0; textVec.size()-1; ++i) {
		textVec[i].setFont(font);
		textVec[i].setCharacterSize(24);
		if(i == 1)
			textVec[i].setColor(sf::Color::Blue);
		else
			textVec[i].setColor(sf::Color::Black);
		textVec[i].setPosition(360,counter);
		counter += 25;
	}
}

void GUI::displayPlaylist() {
	if (music->songListIndex_ == 0) {
		prevSong.setString(trimFilename(music->songList_[music->songList_.size() - 1]));
	}
	else {
		prevSong.setString(trimFilename(music->songList_[music->songListIndex_ - 1]));
	}

	currentSong.setString(trimFilename(music->songList_[music->songListIndex_]));

	if (music->songListIndex_ == music->songList_.size() - 1) {
		nextSong.setString(trimFilename(music->songList_[0]));
	}
	else {
		nextSong.setString(trimFilename(music->songList_[music->songListIndex_ + 1]));
	}

	if (music->songListIndex_ == music->songList_.size() - 2) {
		next2Song.setString(trimFilename(music->songList_[0]));
	}
	else if (music->songListIndex_ == music->songList_.size() - 1) {
		next2Song.setString(trimFilename(music->songList_[1]));
	}
	else {
		next2Song.setString(trimFilename(music->songList_[music->songListIndex_ + 2]));
	}

	if (music->songListIndex_ == music->songList_.size() - 3) {
		next3Song.setString(trimFilename(music->songList_[0]));
	}
	else if (music->songListIndex_ == music->songList_.size() - 2) {
		next3Song.setString(trimFilename(music->songList_[1]));
	}
	else if (music->songListIndex_ == music->songList_.size() - 1) {
		next3Song.setString(trimFilename(music->songList_[2]));
	}
	else {
		next3Song.setString(trimFilename(music->songList_[music->songListIndex_ + 3]));
	}

	if (music->songListIndex_ == music->songList_.size() - 4) {
		next4Song.setString(trimFilename(music->songList_[0]));
	}
	else if (music->songListIndex_ == music->songList_.size() - 3) {
		next4Song.setString(trimFilename(music->songList_[1]));
	}
	else if (music->songListIndex_ == music->songList_.size() - 2) {
		next4Song.setString(trimFilename(music->songList_[2]));
	}
	else if (music->songListIndex_ == music->songList_.size() - 1) {
		next4Song.setString(trimFilename(music->songList_[3]));
	}
	else {
		next4Song.setString(trimFilename(music->songList_[music->songListIndex_ + 4]));
	}
}

void GUI::update() {
	//stylePlaylist();
	displayPlaylist();
	return;
}<commit_msg>fix textvec counter<commit_after>// GUI.cpp
// 29. April 2017
// Created by:
// 		Bryan Burkhardt (bmburkhardt@alaska.edu)
// 		Alexander Eckert (aeckert@alaska.edu)
// 		Jeremiah Jacobson (jjjacobson2@alaska.edu)
// 		Jarye Murphy (@alaska.edu)
// 		Cameron Showalter (@alaska.edu)
//
// Source file for GUI class

#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <iostream>

#include "../include/textureManager.hpp"
#include "../include/GUI.hpp"

GUI::GUI(std::shared_ptr<Music> music) : music(music) {
	std::cout << "ctor GUI\n";
	texmgr = std::make_unique<TextureManager>();
	loadTextures();
	window.create(sf::VideoMode(WINDOW_WIDTH, WINDOW_HEIGHT), "MusicPlayer",
		sf::Style::Titlebar | sf::Style::Close);
	setTextures();

}

bool GUI::clickInSprite(sf::Sprite s, int x , int y) {
	if (x > s.getGlobalBounds().left && x <
			(s.getGlobalBounds().left + s.getGlobalBounds().width) &&
			y > s.getGlobalBounds().top && y < (s.getGlobalBounds().top
			+ s.getGlobalBounds().height)) {
		return true;
	}
	return false;
}

std::string GUI::trimFilename(const std::string& str) {
  std::size_t found = str.find_last_of("/\\");
  return str.substr(found+1);
}

void GUI::draw() {
	window.clear(sf::Color::Green);

	// draw buttons
	window.draw(musicPlayerBG  );
	window.draw(playPauseButton);			//0
	window.draw(prevButton); 				//1
	window.draw(nextButton);				//2
	window.draw(muteButton); 				//3
	window.draw(increaseVolumeButton);		//4
	window.draw(decreaseVolumeButton);		//5

	window.draw(prevSong);
	window.draw(currentSong);
	window.draw(nextSong);
	window.draw(next2Song);
	window.draw(next3Song);
	window.draw(next4Song);
	window.display();

	return;
}

void GUI::loadTextures() {
	texmgr->loadTexture("musicPlayerBGTex", "../res/background/musicplayerbg.png");
	texmgr->loadTexture("playTex", "../res/icons/play.png");
	texmgr->loadTexture("pauseTex", "../res/icons/pause.png");
	texmgr->loadTexture("prevTex", "../res/icons/previous.png");
	texmgr->loadTexture("nextTex", "../res/icons/next.png");
	texmgr->loadTexture("decreaseVolumeTex", "../res/icons/volume_down.png");
	texmgr->loadTexture("increaseVolumeTex", "../res/icons/volume_up.png");
	texmgr->loadTexture("muteTex", "../res/icons/mute.png");
	texmgr->loadTexture("playTex2", "../res/icons/play2.png");
	texmgr->loadTexture("pauseTex2", "../res/icons/pause2.png");
	texmgr->loadTexture("prevTex2", "../res/icons/previous2.png");
	texmgr->loadTexture("nextTex2", "../res/icons/next2.png");
	texmgr->loadTexture("decreaseVolumeTex2", "../res/icons/volume_down2.png");
	texmgr->loadTexture("increaseVolumeTex2", "../res/icons/volume_up2.png");
	texmgr->loadTexture("muteTexv2", "../res/icons/mutev2.png");
	texmgr->loadTexture("muteTex2", "../res/icons/mute2.png");
	texmgr->loadTexture("muteTexv22", "../res/icons/mutev2-2.png");
	std::cout << "Textures loaded" << std::endl;
}

void GUI::setTextures() {
	spriteVec = {
		playPauseButton,			// 0
		prevButton, 				// 1
		nextButton, 				// 2
		muteButton, 				// 3
		decreaseVolumeButton, 		// 4
		increaseVolumeButton
	};

	// set textures
	musicPlayerBG.setTexture(this->texmgr->getRef("musicPlayerBGTex"));
	playPauseButton.setTexture(this->texmgr->getRef("pauseTex"));
	prevButton.setTexture(this->texmgr->getRef("prevTex"));
	nextButton.setTexture(this->texmgr->getRef("nextTex"));
	muteButton.setTexture(this->texmgr->getRef("muteTex"));
	decreaseVolumeButton.setTexture(this->texmgr->getRef("decreaseVolumeTex"));
	increaseVolumeButton.setTexture(this->texmgr->getRef("increaseVolumeTex"));

	// set positions
	playPauseButton.setPosition(120,210);
	prevButton.setPosition(30,210);
	nextButton.setPosition(210,210);
	decreaseVolumeButton.setPosition(120,120);
	muteButton.setPosition(30,120);
	increaseVolumeButton.setPosition(210,120);
}

void GUI::stylePlaylist() {
	if(!font.loadFromFile("../res/fonts/TravelingTypewriter.ttf"))
		std::cout << "Font couldn't be found" << std::endl;
	else
		std::cout << "Font was found" << std::endl;

	textVec = {
		prevSong,
		currentSong,
		nextSong,
		next2Song,
		next3Song,
		next4Song
	};

	int counter = 35;
	for(auto i = 0; i < textVec.size(); ++i) {
		textVec[i].setFont(font);
		textVec[i].setCharacterSize(24);
		if(i == 1)
			textVec[i].setColor(sf::Color::Blue);
		else
			textVec[i].setColor(sf::Color::Black);
		textVec[i].setPosition(360,counter);
		counter += 25;
	}
}

void GUI::displayPlaylist() {
	if (music->songListIndex_ == 0) {
		prevSong.setString(trimFilename(music->songList_[music->songList_.size() - 1]));
	}
	else {
		prevSong.setString(trimFilename(music->songList_[music->songListIndex_ - 1]));
	}

	currentSong.setString(trimFilename(music->songList_[music->songListIndex_]));

	if (music->songListIndex_ == music->songList_.size() - 1) {
		nextSong.setString(trimFilename(music->songList_[0]));
	}
	else {
		nextSong.setString(trimFilename(music->songList_[music->songListIndex_ + 1]));
	}

	if (music->songListIndex_ == music->songList_.size() - 2) {
		next2Song.setString(trimFilename(music->songList_[0]));
	}
	else if (music->songListIndex_ == music->songList_.size() - 1) {
		next2Song.setString(trimFilename(music->songList_[1]));
	}
	else {
		next2Song.setString(trimFilename(music->songList_[music->songListIndex_ + 2]));
	}

	if (music->songListIndex_ == music->songList_.size() - 3) {
		next3Song.setString(trimFilename(music->songList_[0]));
	}
	else if (music->songListIndex_ == music->songList_.size() - 2) {
		next3Song.setString(trimFilename(music->songList_[1]));
	}
	else if (music->songListIndex_ == music->songList_.size() - 1) {
		next3Song.setString(trimFilename(music->songList_[2]));
	}
	else {
		next3Song.setString(trimFilename(music->songList_[music->songListIndex_ + 3]));
	}

	if (music->songListIndex_ == music->songList_.size() - 4) {
		next4Song.setString(trimFilename(music->songList_[0]));
	}
	else if (music->songListIndex_ == music->songList_.size() - 3) {
		next4Song.setString(trimFilename(music->songList_[1]));
	}
	else if (music->songListIndex_ == music->songList_.size() - 2) {
		next4Song.setString(trimFilename(music->songList_[2]));
	}
	else if (music->songListIndex_ == music->songList_.size() - 1) {
		next4Song.setString(trimFilename(music->songList_[3]));
	}
	else {
		next4Song.setString(trimFilename(music->songList_[music->songListIndex_ + 4]));
	}
}

void GUI::update() {
	stylePlaylist();
	displayPlaylist();
	return;
}<|endoftext|>


<commit_before>#include "GamepadController.hpp"

using namespace std;

namespace {
constexpr RJ::Time Dribble_Step_Time = 125 * 1000;
constexpr RJ::Time Kicker_Step_Time = 125 * 1000;
const float AXIS_MAX = 32768.0f;
}

GamepadController::GamepadController()
    : _controller(nullptr), _lastDribblerTime(0), _lastKickerTime(0) {

    if (SDL_Init(SDL_INIT_GAMECONTROLLER) != 0) {
        cerr << "ERROR: SDL could not initialize! SDL Error: " << SDL_GetError()
             << endl;
        return;
    }

    if (SDL_NumJoysticks()) {
        // Open the first available controller
        for (size_t i = 0; i < SDL_NumJoysticks(); ++i) {
            if (SDL_IsGameController(i)) {
                SDL_GameController* controller;

                cerr << "controller '" << i << "' is compatible, named '" << SDL_GameControllerNameForIndex(i) << "'" << endl;
                controller = SDL_GameControllerOpen(i);

                char* mapping;
                mapping = SDL_GameControllerMapping(controller);

                cerr << "controller " << i << " is mapped as '" << mapping << "'" << endl;
                SDL_free(mapping);

                if (controller != nullptr) {
                    _controller = controller;
                    cout << "Controller connected to " << SDL_GameControllerName(_controller) << endl;

                    SDL_Joystick* joy;
                    joy = SDL_GameControllerGetJoystick(_controller);

                    SDL_JoystickGUID guid = SDL_JoystickGetGUID(joy);

                    char gui_str[33];
                    SDL_JoystickGetGUIDString(guid, guid_str, 33);

                    string joy_name(SDL_JoystickName(joy));

                    // "GUID,name,mapping"
                    // Example: "341a3608000000000000504944564944,
                    //           Afterglow PS3 Controller,
                    //           a:b1,b:b2,y:b3,x:b0,start:b9,guide:b12,back:b8,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftshoulder:b4,rightshoulder:b5,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b6,righttrigger:b7"
                    string map_str(guid_str);
                    map_str += "," + joy_name;
                    map_str += ",a:b1";
                    map_str += ",b:b2";
                    map_str += ",y:b3";
                    map_str += ",x:b0";
                    map_str += ",start:b9";
                    SDL_GameControllerAddMapping(map_str.c_str());

                    break;
                } else {
                    cerr << "ERROR: Could not open controller! SDL Error: " << SDL_GetError()
                     << endl;
                }
            }
        }
    } else {
        cout << "WARNING: No manual controllers connected" << endl;
    }
}

GamepadController::~GamepadController() {
    QMutexLocker(&mutex());
    SDL_GameControllerClose(_controller);
    _controller = nullptr;
    SDL_Quit();
}

bool GamepadController::valid() const { return _controller != nullptr; }

void GamepadController::update() {
    QMutexLocker(&mutex());
    SDL_GameControllerUpdate();

    RJ::Time now = RJ::timestamp();

    /*
     *  DRIBBLER ON/OFF
     */
    if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_Y)) {
        _controls.dribble = !_controls.dribble;
    }

    /*
     *  DRIBBLER POWER
     */
    if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_LEFTSTICK)) {
        if ((now - _lastDribblerTime) >= Dribble_Step_Time) {
            _controls.dribblerPower = max(_controls.dribblerPower - 0.1, 0.0);
            _lastDribblerTime = now;
        }
    } else if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_RIGHTSTICK)) {
        if ((now - _lastDribblerTime) >= Dribble_Step_Time) {
            _controls.dribblerPower = min(_controls.dribblerPower + 0.1, 1.0);
            _lastDribblerTime = now;
        }
    } else {
        // Let dribbler speed change immediately
        _lastDribblerTime = now - Dribble_Step_Time;
    }

    /*
     *  KICKER POWER
     */
    if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) {
        if ((now - _lastKickerTime) >= Kicker_Step_Time) {
            _controls.kickPower = max(_controls.kickPower - 0.1, 0.0);
            _lastKickerTime = now;
        }
    } else if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) {
        if ((now - _lastKickerTime) >= Kicker_Step_Time) {
            _controls.kickPower = min(_controls.kickPower + 0.1, 1.0);
            _lastKickerTime = now;
        }
    } else {
        _lastKickerTime = now - Kicker_Step_Time;
    }

    /*
     *  KICK TRUE/FALSE
     */
    _controls.kick = SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_A);

    /*
     *  CHIP TRUE/FALSE
     */
    _controls.chip = SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_B);

    /*
     *  VELOCITY ROTATION
     */
    // Logitech F310 Controller
    _controls.rotation = -1 * SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_LEFTX) / AXIS_MAX;

    /*
     *  VELOCITY TRANSLATION
     */
    auto rightX = SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_RIGHTX) / AXIS_MAX;
    auto rightY = -SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_RIGHTY) / AXIS_MAX;

    Geometry2d::Point input(rightX, rightY);

    // Align along an axis using the DPAD as modifier buttons
    auto mVal = fabs(rightY);
    if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_DPAD_DOWN)) {
        input.y() = mVal;
        input.x() = 0;
    } else if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_DPAD_UP)) {
        input.y() = -mVal;
        input.x() = 0;
    } else if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) {
        input.y() = 0;
        input.x() = mVal;
    } else if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_DPAD_LEFT)) {
        input.y() = 0;
        input.x() = -mVal;
    }

    _controls.translation = Geometry2d::Point(input.x(), input.y());
}

JoystickControlValues GamepadController::getJoystickControlValues() {
    QMutexLocker(&mutex());
    return _controls;
}

void GamepadController::reset() {
    QMutexLocker(&mutex());
    _controls.dribble = false;
}
<commit_msg>adding sdl game controller class for more flexible manual controller use in soccer<commit_after>#include "GamepadController.hpp"

using namespace std;

namespace {
constexpr RJ::Time Dribble_Step_Time = 125 * 1000;
constexpr RJ::Time Kicker_Step_Time = 125 * 1000;
const float AXIS_MAX = 32768.0f;
}

GamepadController::GamepadController()
    : _controller(nullptr), _lastDribblerTime(0), _lastKickerTime(0) {

    if (SDL_Init(SDL_INIT_GAMECONTROLLER) != 0) {
        cerr << "ERROR: SDL could not initialize! SDL Error: " << SDL_GetError()
             << endl;
        return;
    }

    if (SDL_NumJoysticks()) {
        // Open the first available controller
        for (size_t i = 0; i < SDL_NumJoysticks(); ++i) {
            if (SDL_IsGameController(i)) {
                SDL_GameController* controller;

                cerr << "controller '" << i << "' is compatible, named '" << SDL_GameControllerNameForIndex(i) << "'" << endl;
                controller = SDL_GameControllerOpen(i);

                char* mapping;
                mapping = SDL_GameControllerMapping(controller);

                cerr << "controller " << i << " is mapped as '" << mapping << "'" << endl;
                SDL_free(mapping);

                if (controller != nullptr) {
                    _controller = controller;
                    cout << "Controller connected to " << SDL_GameControllerName(_controller) << endl;

                    SDL_Joystick* joy;
                    joy = SDL_GameControllerGetJoystick(_controller);

                    SDL_JoystickGUID guid = SDL_JoystickGetGUID(joy);

                    char guid_str[33];
                    SDL_JoystickGetGUIDString(guid, guid_str, 33);

                    string joy_name(SDL_JoystickName(joy));

                    // "GUID,name,mapping"
                    // Example: "341a3608000000000000504944564944,
                    //           Afterglow PS3 Controller,
                    //           a:b1,b:b2,y:b3,x:b0,start:b9,guide:b12,back:b8,dpup:h0.1,dpleft:h0.8,dpdown:h0.4,dpright:h0.2,leftshoulder:b4,rightshoulder:b5,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,lefttrigger:b6,righttrigger:b7"
                    string map_str(guid_str);
                    map_str += "," + joy_name;
                    map_str += ",a:b1";
                    map_str += ",b:b2";
                    map_str += ",y:b3";
                    map_str += ",x:b0";
                    map_str += ",start:b9";
                    SDL_GameControllerAddMapping(map_str.c_str());

                    break;
                } else {
                    cerr << "ERROR: Could not open controller! SDL Error: " << SDL_GetError()
                     << endl;
                }
            }
        }
    } else {
        cout << "WARNING: No manual controllers connected" << endl;
    }
}

GamepadController::~GamepadController() {
    QMutexLocker(&mutex());
    SDL_GameControllerClose(_controller);
    _controller = nullptr;
    SDL_Quit();
}

bool GamepadController::valid() const { return _controller != nullptr; }

void GamepadController::update() {
    QMutexLocker(&mutex());
    SDL_GameControllerUpdate();

    RJ::Time now = RJ::timestamp();

    /*
     *  DRIBBLER ON/OFF
     */
    if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_Y)) {
        _controls.dribble = !_controls.dribble;
    }

    /*
     *  DRIBBLER POWER
     */
    if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_LEFTSTICK)) {
        if ((now - _lastDribblerTime) >= Dribble_Step_Time) {
            _controls.dribblerPower = max(_controls.dribblerPower - 0.1, 0.0);
            _lastDribblerTime = now;
        }
    } else if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_RIGHTSTICK)) {
        if ((now - _lastDribblerTime) >= Dribble_Step_Time) {
            _controls.dribblerPower = min(_controls.dribblerPower + 0.1, 1.0);
            _lastDribblerTime = now;
        }
    } else {
        // Let dribbler speed change immediately
        _lastDribblerTime = now - Dribble_Step_Time;
    }

    /*
     *  KICKER POWER
     */
    if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) {
        if ((now - _lastKickerTime) >= Kicker_Step_Time) {
            _controls.kickPower = max(_controls.kickPower - 0.1, 0.0);
            _lastKickerTime = now;
        }
    } else if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) {
        if ((now - _lastKickerTime) >= Kicker_Step_Time) {
            _controls.kickPower = min(_controls.kickPower + 0.1, 1.0);
            _lastKickerTime = now;
        }
    } else {
        _lastKickerTime = now - Kicker_Step_Time;
    }

    /*
     *  KICK TRUE/FALSE
     */
    _controls.kick = SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_A);

    /*
     *  CHIP TRUE/FALSE
     */
    _controls.chip = SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_B);

    /*
     *  VELOCITY ROTATION
     */
    // Logitech F310 Controller
    _controls.rotation = -1 * SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_LEFTX) / AXIS_MAX;

    /*
     *  VELOCITY TRANSLATION
     */
    auto rightX = SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_RIGHTX) / AXIS_MAX;
    auto rightY = -SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_RIGHTY) / AXIS_MAX;

    Geometry2d::Point input(rightX, rightY);

    // Align along an axis using the DPAD as modifier buttons
    auto mVal = fabs(rightY);
    if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_DPAD_DOWN)) {
        input.y() = mVal;
        input.x() = 0;
    } else if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_DPAD_UP)) {
        input.y() = -mVal;
        input.x() = 0;
    } else if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) {
        input.y() = 0;
        input.x() = mVal;
    } else if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_DPAD_LEFT)) {
        input.y() = 0;
        input.x() = -mVal;
    }

    _controls.translation = Geometry2d::Point(input.x(), input.y());
}

JoystickControlValues GamepadController::getJoystickControlValues() {
    QMutexLocker(&mutex());
    return _controls;
}

void GamepadController::reset() {
    QMutexLocker(&mutex());
    _controls.dribble = false;
}
<|endoftext|>


<commit_before>#include "GamepadController.hpp"

using namespace std;

namespace {
    constexpr RJ::Time Dribble_Step_Time = 125 * 1000;
    constexpr RJ::Time Kicker_Step_Time = 125 * 1000;
    const float AXIS_MAX = 32768.0f;
}

GamepadController::GamepadController()
    : _controller(nullptr), _lastDribblerTime(0), _lastKickerTime(0) {
    // initialize using the SDL joystick
    if (SDL_Init(SDL_INIT_GAMECONTROLLER) != 0) {
        cerr << "ERROR: SDL could not initialize game controller system! SDL "
                "Error: " << SDL_GetError() << endl;
        return;
    }

    // Load controller mappings
    // TODO fix this path
    SDL_GameControllerAddMapping("030000006d04000016c2000011010000,Logitech Logitech Dual Action (D Input)\
,platform:Linux,x:b0,a:b1,b:b2,y:b3,back:b8,start:b9,dpleft:h0.8,dpdown:h0.0,\
dpdown:h0.4,dpright:h0.0,dpright:h0.2,dpup:h0.0,dpup:h0.1,leftshoulder:h0.0,\
dpup:h0.1,leftshoulder:h0.0,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,\
righttrigger:b7,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,");

    // Controllers will be detected later if needed.
    connected = false;
    openJoystick();
}

GamepadController::~GamepadController() {
    QMutexLocker(&mutex());
    SDL_GameControllerClose(_controller);
    _controller = nullptr;
    SDL_Quit();
}

void GamepadController::openJoystick() {
    if (SDL_NumJoysticks()) {
        // Open the first available controller
        for (size_t i = 0; i < SDL_NumJoysticks(); ++i) {
            // setup the joystick as a game controller if available
            if (SDL_IsGameController(i)) {
                SDL_GameController* controller;
                controller = SDL_GameControllerOpen(i);
                connected = true;

                if (controller != nullptr) {
                    _controller = controller;
                    cout << "Using " << SDL_GameControllerName(_controller)
                         << " game controller" << endl;
                    break;
                } else {
                    cerr << "ERROR: Could not open controller! SDL Error: "
                         << SDL_GetError() << endl;
                }
                // Only support one joystick for now.
                return;
            }
        }
    }
}

void GamepadController::closeJoystick() {
    SDL_GameControllerClose(_controller);
    cout << "Gamepad Controller Disconnected" << endl;
    connected = false;
}

bool GamepadController::valid() const { return _controller != nullptr; }

void GamepadController::update() {
    QMutexLocker(&mutex());
    SDL_GameControllerUpdate();

    RJ::Time now = RJ::timestamp();

    if (connected) {
        // Check if dc
        if (!SDL_GameControllerGetAttached(_controller)) {
            closeJoystick();
            return;
        }
    } else {
        // Check if new controller found
        // TODO use the SDL event API to only run this if we receive a connected event.
        openJoystick();
        if (!connected) {
            return;
        }
    }

    /*
     *  DRIBBLER POWER
     */
    if (SDL_GameControllerGetButton(_controller,
                                    SDL_CONTROLLER_BUTTON_LEFTSTICK)) {
        if ((now - _lastDribblerTime) >= Dribble_Step_Time) {
            _controls.dribblerPower = max(_controls.dribblerPower - 0.1, 0.0);
            _lastDribblerTime = now;
        }
    } else if (SDL_GameControllerGetButton(_controller,
                                           SDL_CONTROLLER_BUTTON_RIGHTSTICK)) {
        if ((now - _lastDribblerTime) >= Dribble_Step_Time) {
            _controls.dribblerPower = min(_controls.dribblerPower + 0.1, 1.0);
            _lastDribblerTime = now;
        }
    } else if (SDL_GameControllerGetButton(_controller,
                                           SDL_CONTROLLER_BUTTON_Y)) {
        /*
         *  DRIBBLER ON/OFF
         */
        if ((now - _lastDribblerTime) >= Dribble_Step_Time) {
            _controls.dribble = !_controls.dribble;
            _lastDribblerTime = now;
        }
    } else {
        // Let dribbler speed change immediately
        _lastDribblerTime = now - Dribble_Step_Time;
    }

    /*
     *  KICKER POWER
     */
    if (SDL_GameControllerGetButton(_controller,
                                    SDL_CONTROLLER_BUTTON_LEFTSHOULDER)) {
        if ((now - _lastKickerTime) >= Kicker_Step_Time) {
            _controls.kickPower = max(_controls.kickPower - 0.1, 0.0);
            _lastKickerTime = now;
        }
    } else if (SDL_GameControllerGetButton(
                   _controller, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) {
        if ((now - _lastKickerTime) >= Kicker_Step_Time) {
            _controls.kickPower = min(_controls.kickPower + 0.1, 1.0);
            _lastKickerTime = now;
        }
    } else {
        _lastKickerTime = now - Kicker_Step_Time;
    }

    /*
     *  KICK TRUE/FALSE
     */
    _controls.kick =
        SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_A);

    /*
     *  CHIP TRUE/FALSE
     */
    _controls.chip =
        SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_X);

    /*
     *  VELOCITY ROTATION
     */
    // Logitech F310 Controller
    _controls.rotation =
        -1 * SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_LEFTX) /
        AXIS_MAX;

    /*
     *  VELOCITY TRANSLATION
     */
    auto rightX =
        SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_RIGHTX) /
        AXIS_MAX;
    auto rightY =
        -SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_RIGHTY) /
        AXIS_MAX;

    Geometry2d::Point input(rightX, rightY);

    // Align along an axis using the DPAD as modifier buttons
    if (SDL_GameControllerGetButton(_controller,
                                    SDL_CONTROLLER_BUTTON_DPAD_DOWN)) {
        input.y() = -fabs(rightY);
        input.x() = 0;
    } else if (SDL_GameControllerGetButton(_controller,
                                           SDL_CONTROLLER_BUTTON_DPAD_UP)) {
        input.y() = fabs(rightY);
        input.x() = 0;
    } else if (SDL_GameControllerGetButton(_controller,
                                           SDL_CONTROLLER_BUTTON_DPAD_LEFT)) {
        input.y() = 0;
        input.x() = -fabs(rightX);
    } else if (SDL_GameControllerGetButton(_controller,
                                           SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) {
        input.y() = 0;
        input.x() = fabs(rightX);
    }

    // Floating point precision error rounding
    if (_controls.kickPower < 1e-1) _controls.kickPower = 0;
    if (_controls.dribblerPower < 1e-1) _controls.dribblerPower = 0;
    if (fabs(_controls.rotation) < 5e-2) _controls.rotation = 0;
    if (fabs(input.y()) < 5e-2) input.y() = 0;
    if (fabs(input.x()) < 5e-2) input.x() = 0;

    _controls.translation = Geometry2d::Point(input.x(), input.y());
}

JoystickControlValues GamepadController::getJoystickControlValues() {
    QMutexLocker(&mutex());
    return _controls;
}

void GamepadController::reset() {
    QMutexLocker(&mutex());
    _controls.dribble = false;
}
<commit_msg>First pass at trying to rebind mappings to fit a generic controller<commit_after>#include "GamepadController.hpp"

using namespace std;

namespace {
    constexpr RJ::Time Dribble_Step_Time = 125 * 1000;
    constexpr RJ::Time Kicker_Step_Time = 125 * 1000;
    const float AXIS_MAX = 32768.0f;
}

GamepadController::GamepadController()
    : _controller(nullptr), _lastDribblerTime(0), _lastKickerTime(0) {
    // initialize using the SDL joystick
    if (SDL_Init(SDL_INIT_GAMECONTROLLER) != 0) {
        cerr << "ERROR: SDL could not initialize game controller system! SDL "
                "Error: " << SDL_GetError() << endl;
        return;
    }

    // Load controller mappings
    // TODO fix this path
    SDL_GameControllerAddMapping("030000006d04000016c2000011010000,Logitech Logitech Dual Action (D Input)\
,platform:Linux,x:b0,a:b1,b:b2,y:b3,back:b8,start:b9,dpleft:h0.8,dpdown:h0.0,\
dpdown:h0.4,dpright:h0.0,dpright:h0.2,dpup:h0.0,dpup:h0.1,leftshoulder:h0.0,\
dpup:h0.1,leftshoulder:h0.0,leftshoulder:b4,lefttrigger:b6,rightshoulder:b5,\
righttrigger:b7,leftstick:b10,rightstick:b11,leftx:a0,lefty:a1,rightx:a2,righty:a3,");

    // Controllers will be detected later if needed.
    connected = false;
    openJoystick();
}

GamepadController::~GamepadController() {
    QMutexLocker(&mutex());
    SDL_GameControllerClose(_controller);
    _controller = nullptr;
    SDL_Quit();
}

void GamepadController::openJoystick() {
    if (SDL_NumJoysticks()) {
        // Open the first available controller
        for (size_t i = 0; i < SDL_NumJoysticks(); ++i) {
            // setup the joystick as a game controller if available
            if (SDL_IsGameController(i)) {
                SDL_GameController* controller;
                controller = SDL_GameControllerOpen(i);
                connected = true;

                if (controller != nullptr) {
                    _controller = controller;
                    cout << "Using " << SDL_GameControllerName(_controller)
                         << " game controller" << endl;
                    break;
                } else {
                    cerr << "ERROR: Could not open controller! SDL Error: "
                         << SDL_GetError() << endl;
                }
                // Only support one joystick for now.
                return;
            }
        }
    }
}

void GamepadController::closeJoystick() {
    SDL_GameControllerClose(_controller);
    cout << "Gamepad Controller Disconnected" << endl;
    connected = false;
}

bool GamepadController::valid() const { return _controller != nullptr; }

void GamepadController::update() {
    QMutexLocker(&mutex());
    SDL_GameControllerUpdate();

    RJ::Time now = RJ::timestamp();

    if (connected) {
        // Check if dc
        if (!SDL_GameControllerGetAttached(_controller)) {
            closeJoystick();
            return;
        }
    } else {
        // Check if new controller found
        // TODO use the SDL event API to only run this if we receive a connected event.
        openJoystick();
        if (!connected) {
            return;
        }
    }

    /*
     *  DRIBBLER ON/OFF
     */
    if (SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER)) {
        _controls.dribble = false;
    } else if (SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_TRIGGERLEFT)) {
        _controls.dribble = true;
    }

    /*
     *  DRIBBLER POWER
     */
    if (SDL_GameControllerGetButton(_controller,
                                    SDL_CONTROLLER_BUTTON_A)) {
        if ((now - _lastDribblerTime) >= Dribble_Step_Time) {
            _controls.dribblerPower = max(_controls.dribblerPower - 0.1, 0.0);
            _lastDribblerTime = now;
        }
    } else if (SDL_GameControllerGetButton(_controller,
                                           SDL_CONTROLLER_BUTTON_Y)) {
        if ((now - _lastDribblerTime) >= Dribble_Step_Time) {
            _controls.dribblerPower = min(_controls.dribblerPower + 0.1, 1.0);
            _lastDribblerTime = now;
        }
    } else {
        // Let dribbler speed change immediately
        _lastDribblerTime = now - Dribble_Step_Time;
    }

    /*
     *  KICKER POWER
     */
    if (SDL_GameControllerGetButton(_controller,
                                    SDL_CONTROLLER_BUTTON_X)) {
        if ((now - _lastKickerTime) >= Kicker_Step_Time) {
            _controls.kickPower = max(_controls.kickPower - 0.1, 0.0);
            _lastKickerTime = now;
        }
    } else if (SDL_GameControllerGetButton(
                   _controller, SDL_CONTROLLER_BUTTON_B)) {
        if ((now - _lastKickerTime) >= Kicker_Step_Time) {
            _controls.kickPower = min(_controls.kickPower + 0.1, 1.0);
            _lastKickerTime = now;
        }
    } else {
        _lastKickerTime = now - Kicker_Step_Time;
    }

    /*
     *  KICK TRUE/FALSE
     */
    _controls.kick =
        SDL_GameControllerGetButton(_controller, SDL_CONTROLLER_BUTTON_RIGHTSHOULDER);

    /*
     *  CHIP TRUE/FALSE
     */
    _controls.chip =
        SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_TRIGGERRIGHT);

    /*
     *  VELOCITY ROTATION
     */
    _controls.rotation =
        -1 * SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_LEFTX) /
        AXIS_MAX;

    /*
     *  VELOCITY TRANSLATION
     */
    auto rightX =
        SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_RIGHTX) /
        AXIS_MAX;
    auto rightY =
        -SDL_GameControllerGetAxis(_controller, SDL_CONTROLLER_AXIS_RIGHTY) /
        AXIS_MAX;

    Geometry2d::Point input(rightX, rightY);

    // Align along an axis using the DPAD as modifier buttons
    if (SDL_GameControllerGetButton(_controller,
                                    SDL_CONTROLLER_BUTTON_DPAD_DOWN)) {
        input.y() = -fabs(rightY);
        input.x() = 0;
    } else if (SDL_GameControllerGetButton(_controller,
                                           SDL_CONTROLLER_BUTTON_DPAD_UP)) {
        input.y() = fabs(rightY);
        input.x() = 0;
    } else if (SDL_GameControllerGetButton(_controller,
                                           SDL_CONTROLLER_BUTTON_DPAD_LEFT)) {
        input.y() = 0;
        input.x() = -fabs(rightX);
    } else if (SDL_GameControllerGetButton(_controller,
                                           SDL_CONTROLLER_BUTTON_DPAD_RIGHT)) {
        input.y() = 0;
        input.x() = fabs(rightX);
    }

    // Floating point precision error rounding
    if (_controls.kickPower < 1e-1) _controls.kickPower = 0;
    if (_controls.dribblerPower < 1e-1) _controls.dribblerPower = 0;
    if (fabs(_controls.rotation) < 5e-2) _controls.rotation = 0;
    if (fabs(input.y()) < 5e-2) input.y() = 0;
    if (fabs(input.x()) < 5e-2) input.x() = 0;

    _controls.translation = Geometry2d::Point(input.x(), input.y());
}

JoystickControlValues GamepadController::getJoystickControlValues() {
    QMutexLocker(&mutex());
    return _controls;
}

void GamepadController::reset() {
    QMutexLocker(&mutex());
    _controls.dribble = false;
}
<|endoftext|>


<commit_before>AliAnalysisTaskQASym * AddTaskQAsym(Int_t runNumber)

{
  // Creates a QA task exploiting simple symmetries phi, eta +/-, charge ...

  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskQAsym", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTasQAsym", "This task requires an input event handler");
    return NULL;
  }
   TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

   // Configure analysis
   //===========================================================================

   //Task for global tracks
   AliAnalysisTaskQASym *task0 = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_Global");
   task0->SetTrackType(0);
   task0->SelectCollisionCandidates();
   //Task for ITS tracks
   AliAnalysisTaskQASym *task1 = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_ITS");
   task1->SetTrackType(1);
   task1->SetStandAloneTrack(kFALSE);
   task1->SelectCollisionCandidates();
   //Task for ITS tracks SA
   AliAnalysisTaskQASym *task1sa = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_ITS_SA");
   task1sa->SetTrackType(1);
   task1sa->SetStandAloneTrack(kTRUE);
   task1sa->SelectCollisionCandidates();
   //Task for TPC tracks
   AliAnalysisTaskQASym *task2 = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_TPC");
   task2->SetTrackType(2);
   task2->SelectCollisionCandidates();

   //cuts for global tracks
   AliESDtrackCuts* esdTrackCutsL0 = new AliESDtrackCuts("AliESDtrackCuts0","Global");
   esdTrackCutsL0->SetMinNClustersTPC(70);
   esdTrackCutsL0->SetRequireTPCRefit(kTRUE);
   esdTrackCutsL0->SetMaxDCAToVertexXY(3.);
   esdTrackCutsL0->SetMaxDCAToVertexZ(3.);
   esdTrackCutsL0->SetAcceptKinkDaughters(kFALSE);

   //cuts for ITS tracks
   AliESDtrackCuts* esdTrackCutsL1 = new AliESDtrackCuts("AliESDtrackCuts1","ITS");
   esdTrackCutsL1->SetMaxDCAToVertexXY(3.);
   esdTrackCutsL1->SetMaxDCAToVertexZ(3.);
   esdTrackCutsL1->SetAcceptKinkDaughters(kFALSE);
   esdTrackCutsL1->SetRequireITSRefit(kTRUE);
   esdTrackCutsL1->SetRequireITSStandAlone(kTRUE, kFALSE);

   //cuts for ITS tracks SA
   AliESDtrackCuts* esdTrackCutsL1sa = new AliESDtrackCuts("AliESDtrackCuts1","ITS_SA");
   esdTrackCutsL1sa->SetMaxDCAToVertexXY(3.);
   esdTrackCutsL1sa->SetMaxDCAToVertexZ(3.);
   esdTrackCutsL1sa->SetAcceptKinkDaughters(kFALSE);
   esdTrackCutsL1sa->SetRequireITSRefit(kTRUE);
   // esdTrackCutsL1sa->SetRequireITSStandAlone(kTRUE, kTRUE); //cut on SA tracks in AliAnalysisTaskQASym

   //cuts for TPC tracks
   AliESDtrackCuts* esdTrackCutsL2 = new AliESDtrackCuts("AliESDtrackCuts2","TPC");
   esdTrackCutsL2->SetRequireTPCRefit(kFALSE);
   esdTrackCutsL2->SetAcceptKinkDaughters(kFALSE);
   //jacek's cuts:
   esdTrackCutsL2->SetMinNClustersTPC(70);
   // cut on max ncl=160 in Task
   esdTrackCutsL2->SetMaxDCAToVertexXY(3.);
   esdTrackCutsL2->SetMaxDCAToVertexZ(3.);
   esdTrackCutsL2->SetMaxChi2PerClusterTPC(3.999);
   //cut minChi=0 in task
   //esdTrackCutsL2->SetPRange(0.15,16); // not needed for QA
   //esdTrackCutsL2->SetEtaRange(-0.8, 0.7999); // not needed for QA

   task0->SetCuts(esdTrackCutsL0);
   task1->SetCuts(esdTrackCutsL1);
   task1sa->SetCuts(esdTrackCutsL1sa);
   task2->SetCuts(esdTrackCutsL2);

   mgr->AddTask(task0);
   mgr->AddTask(task1);
   mgr->AddTask(task1sa);
   mgr->AddTask(task2);

   AliAnalysisDataContainer *cout0  = 0;
   AliAnalysisDataContainer *cout1  = 0;
   AliAnalysisDataContainer *cout1sa  = 0;
   AliAnalysisDataContainer *cout2  = 0;

   if(runNumber>0){
    cout0 =  mgr->CreateContainer("QAsymHists_Global",TList::Class(),
				  AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
    cout1 =  mgr->CreateContainer("QAsymHists_ITS",TList::Class(),
				  AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
    cout1sa =  mgr->CreateContainer("QAsymHists_ITS_SA",TList::Class(),
				    AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
    cout2 =  mgr->CreateContainer("QAsymHists_TPC",TList::Class(),
				  AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
   }

   else{
      cout0 = mgr->CreateContainer("QAsymHists_Global",TList::Class(),
				 AliAnalysisManager::kOutputContainer,
				 Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
      cout1 = mgr->CreateContainer("QAsymHists_ITS",TList::Class(),
				   AliAnalysisManager::kOutputContainer,
				 Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
      cout1sa = mgr->CreateContainer("QAsymHists_ITS_SA",TList::Class(),
				     AliAnalysisManager::kOutputContainer,
				     Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
      cout2 = mgr->CreateContainer("QAsymHists_TPC",TList::Class(),
				   AliAnalysisManager::kOutputContainer,
				 Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
   }

   mgr->ConnectInput  (task0, 0, mgr->GetCommonInputContainer());
   mgr->ConnectInput  (task1, 0, mgr->GetCommonInputContainer());
   mgr->ConnectInput  (task1sa, 0, mgr->GetCommonInputContainer());
   mgr->ConnectInput  (task2, 0, mgr->GetCommonInputContainer());

   mgr->ConnectOutput (task0, 1, cout0);
   mgr->ConnectOutput (task1, 1, cout1);
   mgr->ConnectOutput (task1sa, 1, cout1sa);
   mgr->ConnectOutput (task2, 1, cout2);

   return task0;

}

<commit_msg>Correction of SA track rejection<commit_after>AliAnalysisTaskQASym * AddTaskQAsym(Int_t runNumber)

{
  // Creates a QA task exploiting simple symmetries phi, eta +/-, charge ...

  // Get the pointer to the existing analysis manager via the static access method.
  //==============================================================================
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTaskQAsym", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.
  //==============================================================================
  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTasQAsym", "This task requires an input event handler");
    return NULL;
  }
   TString inputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

   // Configure analysis
   //===========================================================================

   //Task for global tracks
   AliAnalysisTaskQASym *task0 = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_Global");
   task0->SetTrackType(0);
   task0->SelectCollisionCandidates();
   //Task for ITS tracks
   AliAnalysisTaskQASym *task1 = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_ITS");
   task1->SetTrackType(1);
   task1->SetStandAloneTrack(kFALSE);
   task1->SelectCollisionCandidates();
   //Task for ITS tracks SA
   AliAnalysisTaskQASym *task1sa = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_ITS_SA");
   task1sa->SetTrackType(1);
   task1sa->SetStandAloneTrack(kTRUE);
   task1sa->SelectCollisionCandidates();
   //Task for TPC tracks
   AliAnalysisTaskQASym *task2 = new AliAnalysisTaskQASym("AliAnalysisTaskQASym_TPC");
   task2->SetTrackType(2);
   task2->SelectCollisionCandidates();

   //cuts for global tracks
   AliESDtrackCuts* esdTrackCutsL0 = new AliESDtrackCuts("AliESDtrackCuts0","Global");
   esdTrackCutsL0->SetMinNClustersTPC(70);
   esdTrackCutsL0->SetRequireTPCRefit(kTRUE);
   esdTrackCutsL0->SetMaxDCAToVertexXY(3.);
   esdTrackCutsL0->SetMaxDCAToVertexZ(3.);
   esdTrackCutsL0->SetAcceptKinkDaughters(kFALSE);

   //cuts for ITS tracks
   AliESDtrackCuts* esdTrackCutsL1 = new AliESDtrackCuts("AliESDtrackCuts1","ITS");
   esdTrackCutsL1->SetMaxDCAToVertexXY(3.);
   esdTrackCutsL1->SetMaxDCAToVertexZ(3.);
   esdTrackCutsL1->SetAcceptKinkDaughters(kFALSE);
   esdTrackCutsL1->SetRequireITSRefit(kTRUE);
   esdTrackCutsL1->SetRequireITSStandAlone(kTRUE, kTRUE); //2nd option: reject pure SA tracks

   //cuts for ITS tracks SA
   AliESDtrackCuts* esdTrackCutsL1sa = new AliESDtrackCuts("AliESDtrackCuts1","ITS_SA");
   esdTrackCutsL1sa->SetMaxDCAToVertexXY(3.);
   esdTrackCutsL1sa->SetMaxDCAToVertexZ(3.);
   esdTrackCutsL1sa->SetAcceptKinkDaughters(kFALSE);
   esdTrackCutsL1sa->SetRequireITSRefit(kTRUE);
   // esdTrackCutsL1sa->SetRequireITSStandAlone(kTRUE, kTRUE); //cut on SA tracks in AliAnalysisTaskQASym

   //cuts for TPC tracks
   AliESDtrackCuts* esdTrackCutsL2 = new AliESDtrackCuts("AliESDtrackCuts2","TPC");
   esdTrackCutsL2->SetRequireTPCRefit(kFALSE);
   esdTrackCutsL2->SetAcceptKinkDaughters(kFALSE);
   //jacek's cuts:
   esdTrackCutsL2->SetMinNClustersTPC(70);
   // cut on max ncl=160 in Task
   esdTrackCutsL2->SetMaxDCAToVertexXY(3.);
   esdTrackCutsL2->SetMaxDCAToVertexZ(3.);
   esdTrackCutsL2->SetMaxChi2PerClusterTPC(3.999);
   //cut minChi=0 in task
   //esdTrackCutsL2->SetPRange(0.15,16); // not needed for QA
   //esdTrackCutsL2->SetEtaRange(-0.8, 0.7999); // not needed for QA

   task0->SetCuts(esdTrackCutsL0);
   task1->SetCuts(esdTrackCutsL1);
   task1sa->SetCuts(esdTrackCutsL1sa);
   task2->SetCuts(esdTrackCutsL2);

   mgr->AddTask(task0);
   mgr->AddTask(task1);
   mgr->AddTask(task1sa);
   mgr->AddTask(task2);

   AliAnalysisDataContainer *cout0  = 0;
   AliAnalysisDataContainer *cout1  = 0;
   AliAnalysisDataContainer *cout1sa  = 0;
   AliAnalysisDataContainer *cout2  = 0;

   if(runNumber>0){
    cout0 =  mgr->CreateContainer("QAsymHists_Global",TList::Class(),
				  AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
    cout1 =  mgr->CreateContainer("QAsymHists_ITS",TList::Class(),
				  AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
    cout1sa =  mgr->CreateContainer("QAsymHists_ITS_SA",TList::Class(),
				    AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
    cout2 =  mgr->CreateContainer("QAsymHists_TPC",TList::Class(),
				  AliAnalysisManager::kOutputContainer, Form("run%d.root",runNumber));
   }

   else{
      cout0 = mgr->CreateContainer("QAsymHists_Global",TList::Class(),
				 AliAnalysisManager::kOutputContainer,
				 Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
      cout1 = mgr->CreateContainer("QAsymHists_ITS",TList::Class(),
				   AliAnalysisManager::kOutputContainer,
				 Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
      cout1sa = mgr->CreateContainer("QAsymHists_ITS_SA",TList::Class(),
				     AliAnalysisManager::kOutputContainer,
				     Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
      cout2 = mgr->CreateContainer("QAsymHists_TPC",TList::Class(),
				   AliAnalysisManager::kOutputContainer,
				 Form("%s:PWG1_QAsymHists",AliAnalysisManager::GetCommonFileName()));
   }

   mgr->ConnectInput  (task0, 0, mgr->GetCommonInputContainer());
   mgr->ConnectInput  (task1, 0, mgr->GetCommonInputContainer());
   mgr->ConnectInput  (task1sa, 0, mgr->GetCommonInputContainer());
   mgr->ConnectInput  (task2, 0, mgr->GetCommonInputContainer());

   mgr->ConnectOutput (task0, 1, cout0);
   mgr->ConnectOutput (task1, 1, cout1);
   mgr->ConnectOutput (task1sa, 1, cout1sa);
   mgr->ConnectOutput (task2, 1, cout2);

   return task0;

}

<|endoftext|>


<commit_before>/* Converter.C
*
* Copyright (C) 2011 Marcel Schumann
*
* This program free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or (at
* your option) any later version.
*
* 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, see <http://www.gnu.org/licenses/>.
*/

// ----------------------------------------------------
// $Maintainer: Marcel Schumann $
// $Authors: Marcel Schumann $
// ----------------------------------------------------

#include <BALL/FORMAT/molFileFactory.h>
#include <BALL/FORMAT/dockResultFile.h>
#include <BALL/KERNEL/molecule.h>
#include <BALL/FORMAT/commandlineParser.h>
#include "version.h"

using namespace BALL;
using namespace std;

int main(int argc, char* argv[])
{
	CommandlineParser parpars("Converter", "interconvert molecular file-formats", VERSION, String(__DATE__), "Convert, combine and store");
	parpars.registerParameter("i", "input file", INFILE, true);
	parpars.registerParameter("o", "output file", OUTFILE, true);
	parpars.registerParameter("f", "output format", STRING);
	parpars.registerFlag("rm", "remove input file when finished");
	String man = String("This tool can be used to convert between different molecular file-formats.\nSupported formats are ") + MolFileFactory::getSupportedFormats() + String(".");
	parpars.setToolManual(man);
	parpars.setSupportedFormats("i",MolFileFactory::getSupportedFormats());
	parpars.setSupportedFormats("o",MolFileFactory::getSupportedFormats());

	String formats = MolFileFactory::getSupportedFormats();
	vector<String> v;
	formats.split(v,",");
	list<String> format_list;
	for (Size i=0; i<v.size(); i++)
	{
		format_list.push_back(v[i]);
	}
	parpars.setParameterRestrictions("f",format_list);

	parpars.parse(argc, argv);

	String default_format = "mol2";
	if (parpars.has("f")) default_format = parpars.get("f");
	GenericMolFile* input = MolFileFactory::open(parpars.get("i"), ios::in);
	GenericMolFile* output = MolFileFactory::open(parpars.get("o"), ios::out, default_format);
	DockResultFile* drf_output = dynamic_cast<DockResultFile*>(output);
	if (drf_output)
	{
		drf_output->setToolInfo(parpars.getStartCommand(), parpars.getStartTime());
	}

	Molecule* mol;
	int no_written = 0;
	int no_ignored = 0;
	while ((mol = input->read()))
	{
		bool b = output->write(*mol);
		if (b) no_written++;
		else no_ignored++;
		delete mol;
		if (no_written%50 == 0)
		{
			Log.level(5) << "\r" << no_written << "molecules";
			Log.flush();
		}
	}

	Log.level(20) << "\r";
	if (no_ignored > 0) Log.level(20) << "ignored " << no_ignored << " identical molecules!" << endl;
	Log.level(20) << "wrote " << no_written << " molecules." << endl;

	input->close();
	output->close();

	delete input;
	delete output;

	if (parpars.has("rm"))
	{
		File::remove(parpars.get("i"));
	}
}
<commit_msg>deleted invalid licensing<commit_after>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//

#include <BALL/FORMAT/molFileFactory.h>
#include <BALL/FORMAT/dockResultFile.h>
#include <BALL/KERNEL/molecule.h>
#include <BALL/FORMAT/commandlineParser.h>
#include "version.h"

using namespace BALL;
using namespace std;

int main(int argc, char* argv[])
{
	CommandlineParser parpars("Converter", "interconvert molecular file-formats", VERSION, String(__DATE__), "Convert, combine and store");
	parpars.registerParameter("i", "input file", INFILE, true);
	parpars.registerParameter("o", "output file", OUTFILE, true);
	parpars.registerParameter("f", "output format", STRING);
	parpars.registerFlag("rm", "remove input file when finished");
	String man = String("This tool can be used to convert between different molecular file-formats.\nSupported formats are ") + MolFileFactory::getSupportedFormats() + String(".");
	parpars.setToolManual(man);
	parpars.setSupportedFormats("i",MolFileFactory::getSupportedFormats());
	parpars.setSupportedFormats("o",MolFileFactory::getSupportedFormats());

	String formats = MolFileFactory::getSupportedFormats();
	vector<String> v;
	formats.split(v,",");
	list<String> format_list;
	for (Size i=0; i<v.size(); i++)
	{
		format_list.push_back(v[i]);
	}
	parpars.setParameterRestrictions("f",format_list);

	parpars.parse(argc, argv);

	String default_format = "mol2";
	if (parpars.has("f")) default_format = parpars.get("f");
	GenericMolFile* input = MolFileFactory::open(parpars.get("i"), ios::in);
	GenericMolFile* output = MolFileFactory::open(parpars.get("o"), ios::out, default_format);
	DockResultFile* drf_output = dynamic_cast<DockResultFile*>(output);
	if (drf_output)
	{
		drf_output->setToolInfo(parpars.getStartCommand(), parpars.getStartTime());
	}

	Molecule* mol;
	int no_written = 0;
	int no_ignored = 0;
	while ((mol = input->read()))
	{
		bool b = output->write(*mol);
		if (b) no_written++;
		else no_ignored++;
		delete mol;
		if (no_written%50 == 0)
		{
			Log.level(5) << "\r" << no_written << "molecules";
			Log.flush();
		}
	}

	Log.level(20) << "\r";
	if (no_ignored > 0) Log.level(20) << "ignored " << no_ignored << " identical molecules!" << endl;
	Log.level(20) << "wrote " << no_written << " molecules." << endl;

	input->close();
	output->close();

	delete input;
	delete output;

	if (parpars.has("rm"))
	{
		File::remove(parpars.get("i"));
	}
}
<|endoftext|>


<commit_before>#include <unordered_map>
#include <string>
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <sstream>
#include <cctype>
#include <cmath>
#include <stack>
#include <cstdlib>

using namespace std;

void die() {
	cout << "INVALID INPUT!" << endl;
	exit(EXIT_FAILURE);
}

class SpecialInt {
	private:
		int data;
	public:
		void set_data(int x) {
			if (x > 255) die();
			data = x;
		}
		int get_data() {
			if (data > 255) die();
			return data;
		}
		void increment_data() {
			if (data + 1 > 255) die();
			data++;
		}
};

vector<string> input() {
	vector<string> retval;
	string statement;
	getline(cin, statement);
	size_t found_let = statement.find("LET");
	size_t found_equals = statement.find("=");
	// "LET" is in there, so we're setting a variable!
	if (found_let != string::npos) {
		// But wait! Remember, a variable can only be one letter.
		// So how can we check for that? Well, if the variable is only one letter...
		// Then "=" will always be at the same index: 6
		if (found_equals == 6) {
			// Okay, so by now we know everything from the beginning to "=" is fine!
			// You may ask, what about the number? What if it's out of bounds?
			// Well, the SpecialInt class will handle that :)
			string var_name;
			var_name.push_back(statement.at(4));
			// Value should start at index: 8
			string var_value = statement.substr(8, (statement.size() - 1) - 7);
			retval.push_back(var_name);
			retval.push_back(var_value);
			return retval;
		}
		// OK, it's an error!
		else {
			die();
		}
	}
	// So there's no "LET", but maybe it's just an expression? An expression wouldn't have "=".
	else if (found_equals == string::npos) {
		retval.push_back(statement);
		return retval;
	}
	// OK, it's an error for sure!
	else {
		die();
	}
}

int logic(string statement) {
	// Separate the statement into logical parts.
	istringstream iss(statement);
	vector<string> vec;
	copy(istream_iterator<string> (iss), istream_iterator<string>(), back_inserter(vec));
	// Create stack for evaluation.
	stack<int> my_stack;
	if (vec.size() == 1) {
		// TODO
	}
}

int main() {
	// Hash table that holds variables.
	unordered_map<string, SpecialInt> hash;
	while (true) {
		// Get the input-vector from the function.
		vector<string> vec = input();
		// It's setting a variable.
		if (vec.size() == 2) {
			SpecialInt val;
			val.set_data(stoi(vec.at(1)));
			// But wait! We can't redeclare a variable! Let's make sure of that.
			if (hash.find(vec.at(0)) == hash.end()) {
				hash[vec.at(0)] = val;
			}
			// We must be trying to redeclare a variable! Bad!
			else {
				die();
			}
		}
		else {
			// Call logic function.
			int result = logic(vec.at(0));
		}
	}
	return 0;
}
<commit_msg>Working MAIN.cc?!?!<commit_after>#include <unordered_map>
#include <string>
#include <vector>
#include <iostream>
#include <iterator>
#include <algorithm>
#include <sstream>
#include <cctype>
#include <cmath>
#include <stack>
#include <cstdlib>

using namespace std;

void die() {
	cout << "INVALID INPUT!" << endl;
	exit(EXIT_FAILURE);
}

inline bool is_int(const string &s) {
	if (s.empty() || ((!isdigit(s[0])) && (s[0] != '+'))) return false;
	char *p;
	strtol(s.c_str(), &p, 10);
	return (*p == 0);
}

class SpecialInt {
	private:
		int data;
	public:
		void set_data(int x) {
			if (x > 255) die();
			data = x;
		}
		int get_data() {
			if (data > 255) die();
			return data;
		}
		void increment_data() {
			if (data + 1 > 255) die();
			data++;
		}
};

// Hash table.
unordered_map <string, SpecialInt> table;

vector<string> input() {
	vector<string> retval;
	string statement;
	getline(cin, statement);
	size_t found_let = statement.find("LET");
	size_t found_equals = statement.find("=");
	// "LET" is in there, so we're setting a variable!
	if (found_let != string::npos) {
		// But wait! Remember, a variable can only be one letter.
		// So how can we check for that? Well, if the variable is only one letter...
		// Then "=" will always be at the same index: 6
		if (found_equals == 6) {
			// Okay, so by now we know everything from the beginning to "=" is fine!
			// You may ask, what about the number? What if it's out of bounds?
			// Well, the SpecialInt class will handle that :)
			string var_name;
			var_name.push_back(statement.at(4));
			// Value should start at index: 8
			string var_value = statement.substr(8, (statement.size() - 1) - 7);
			retval.push_back(var_name);
			retval.push_back(var_value);
			return retval;
		}
		// OK, it's an error!
		else {
			die();
		}
	}
	// So there's no "LET", but maybe it's just an expression? An expression wouldn't have "=".
	else if (found_equals == string::npos) {
		retval.push_back(statement);
		return retval;
	}
	// OK, it's an error for sure!
	else {
		die();
	}
}

int logic(string statement) {
	int retval;
	// Separate the statement into logical parts.
	istringstream iss(statement);
	vector<string> vec;
	copy(istream_iterator<string> (iss), istream_iterator<string>(), back_inserter(vec));
	// Create stack for evaluation.
	vector<string> op_table;
	/*
	if (vec.size() == 1) {
		// TODO
	}
	*/
	for (string s : vec) {
		// We're going to treat this kinda like the RPN calculator.
		op_table.push_back(s);
		// This fucks all the logic up! Needed to add check for this!
		if (vec.size() == 1) {
			if (table.find(s) != table.end()) {
				table[s].increment_data();
				retval = table[s].get_data();
				return retval;
			}
		}
		if (op_table.size() == 3) {
			// We got the operator.
			string operat = op_table.at(1);
			// We have to declare the first and second values because of stupid C++ scoping rules.
			int val1;
			int val2;
			// The first value.
			// If the string is not an integer, it must be a variable. Look it up!
			// We're also handling conversion from a string to an integer with this.
			if (!is_int(op_table.at(0))) {
				val1 = table[op_table.at(0)].get_data();
				table[op_table.at(0)].increment_data();
			}
			// OK, it's an integer then. Let's make it so (via conversion as before).
			else { val1 = stoi(op_table.at(0)); }
			// Do the same process for the second item.
			if (!is_int(op_table.at(2))) {
				val2 = table[op_table.at(2)].get_data();
				table[op_table.at(2)].increment_data();
			}
			else { val2 = stoi(op_table.at(2)); }
			// Now we got the integer values. Now based off of the operator, let's do this!
			if (operat == "+") {
				// We got the result.
				int result = val1 + val2;
				// Clear the operation table.
				op_table.clear();
				// Now add the string of the result back onto it!
				op_table.push_back(to_string(result));
				retval = result;
			}
			else if (operat == "-") {
				int result = val1 - val2;
				op_table.clear();
				op_table.push_back(to_string(result));
				retval = result;
			}
			else if (operat == "*") {
				int result = val1 * val2;
				op_table.clear();
				op_table.push_back(to_string(result));
				retval = result;
			}
			else if (operat == "/") {
				int result = val1 / val2;
				op_table.clear();
				op_table.push_back(to_string(result));
				retval = result;
			}
			else if (operat == "^") {
				// TODO POSSIBLE ERROR WITH VAL1; SHOULD BE FLOAT INSTEAD OF INT????
				int result = pow(val1, val2);
				op_table.clear();
				op_table.push_back(to_string(result));
				retval = result;
			}
			else if (operat == "%") {
				int result = val1 % val2;
				op_table.clear();
				op_table.push_back(to_string(result));
				retval = result;
			}
		}
	}
	return retval;
}

int main() {
	// Hash table that holds variables.
	unordered_map<string, SpecialInt> hash;
	while (true) {
		// Get the input-vector from the function.
		vector<string> vec = input();
		// It's setting a variable.
		if (vec.size() == 2) {
			SpecialInt val;
			val.set_data(stoi(vec.at(1)));
			// But wait! We can't redeclare a variable! Let's make sure of that.
			if (table.find(vec.at(0)) == table.end()) {
				table[vec.at(0)] = val;
			}
			// We must be trying to redeclare a variable! Bad!
			else {
				die();
			}
		}
		else {
			// Call logic function.
			int result = logic(vec.at(0));
			cout << result << endl;
		}
	}
	return 0;
}
<|endoftext|>


<commit_before>/************************************************************************/
/* qt-opencv-multithreaded:                                             */
/* A multithreaded OpenCV application using the Qt framework.           */
/*                                                                      */
/* ShowIplImage.cpp                                                     */
/*                                                                      */
/* Nick D'Ademo <nickdademo@gmail.com>                                  */
/*                                                                      */
/* Copyright (c) 2011 Nick D'Ademo                                      */
/*                                                                      */
/* Permission is hereby granted, free of charge, to any person          */
/* obtaining a copy of this software and associated documentation       */
/* files (the "Software"), to deal in the Software without restriction, */
/* including without limitation the rights to use, copy, modify, merge, */
/* publish, distribute, sublicense, and/or sell copies of the Software, */
/* and to permit persons to whom the Software is furnished to do so,    */
/* subject to the following conditions:                                 */
/*                                                                      */
/* The above copyright notice and this permission notice shall be       */
/* included in all copies or substantial portions of the Software.      */
/*                                                                      */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,      */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF   */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND                */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS  */
/* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN   */
/* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN    */
/* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE     */
/* SOFTWARE.                                                            */
/*                                                                      */
/************************************************************************/

#include "ShowIplImage.h"

QImage IplImageToQImage(const IplImage *iplImage)
{
    // Local variables
    int height = iplImage->height;
    int width = iplImage->width;
    if(iplImage->depth == IPL_DEPTH_8U && iplImage->nChannels == 1)
    {
        // Set the color table (used to translate colour indexes to qRgb values)
        QVector<QRgb> colorTable;
        for (int i=0; i<256; i++)
            colorTable.push_back(qRgb(i,i,i));
        // Copy input IplImage
        const uchar *qImageBuffer = (const uchar*)iplImage->imageData;
        // Create QImage with same dimensions as input IplImage
        QImage img(qImageBuffer, width, height, QImage::Format_Indexed8);
        img.setColorTable(colorTable);
        return img;
    }
    else if(iplImage->depth == IPL_DEPTH_8U && iplImage->nChannels == 3)
    {
        // Copy input IplImage
        const uchar *qImageBuffer = (const uchar*)iplImage->imageData;
        // Create QImage with same dimensions as input IplImage
        QImage img(qImageBuffer, width, height, QImage::Format_RGB888);
        return img.rgbSwapped();
    }
    else
    {
        qDebug() << "ERROR: IplImage could not be converted to QImage.";
        return QImage();
    }
} // IplImageToQImage()
<commit_msg><commit_after>/************************************************************************/
/* qt-opencv-multithreaded:                                             */
/* A multithreaded OpenCV application using the Qt framework.           */
/*                                                                      */
/* ShowIplImage.cpp                                                     */
/*                                                                      */
/* Nick D'Ademo <nickdademo@gmail.com>                                  */
/*                                                                      */
/* Copyright (c) 2011 Nick D'Ademo                                      */
/*                                                                      */
/* Permission is hereby granted, free of charge, to any person          */
/* obtaining a copy of this software and associated documentation       */
/* files (the "Software"), to deal in the Software without restriction, */
/* including without limitation the rights to use, copy, modify, merge, */
/* publish, distribute, sublicense, and/or sell copies of the Software, */
/* and to permit persons to whom the Software is furnished to do so,    */
/* subject to the following conditions:                                 */
/*                                                                      */
/* The above copyright notice and this permission notice shall be       */
/* included in all copies or substantial portions of the Software.      */
/*                                                                      */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,      */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF   */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND                */
/* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS  */
/* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN   */
/* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN    */
/* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE     */
/* SOFTWARE.                                                            */
/*                                                                      */
/************************************************************************/

#include "ShowIplImage.h"

QImage IplImageToQImage(const IplImage *iplImage)
{
    // Local variables
    int height = iplImage->height;
    int width = iplImage->width;
    // PIXEL DEPTH=8-bits unsigned, NO. OF CHANNELS=1
    if(iplImage->depth == IPL_DEPTH_8U && iplImage->nChannels == 1)
    {
        // Set the color table (used to translate colour indexes to qRgb values)
        QVector<QRgb> colorTable;
        for (int i=0; i<256; i++)
            colorTable.push_back(qRgb(i,i,i));
        // Copy input IplImage
        const uchar *qImageBuffer = (const uchar*)iplImage->imageData;
        // Create QImage with same dimensions as input IplImage
        QImage img(qImageBuffer, width, height, QImage::Format_Indexed8);
        img.setColorTable(colorTable);
        return img;
    }
    // PIXEL DEPTH=8-bits unsigned, NO. OF CHANNELS=3
    else if(iplImage->depth == IPL_DEPTH_8U && iplImage->nChannels == 3)
    {
        // Copy input IplImage
        const uchar *qImageBuffer = (const uchar*)iplImage->imageData;
        // Create QImage with same dimensions as input IplImage
        QImage img(qImageBuffer, width, height, QImage::Format_RGB888);
        return img.rgbSwapped();
    }
    else
    {
        qDebug() << "ERROR: IplImage could not be converted to QImage.";
        return QImage();
    }
} // IplImageToQImage()
<|endoftext|>


<commit_before>//
// Copyright © 2019 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "DepthToSpace.hpp"

#include <DataLayoutIndexed.hpp>
#include <Permute.hpp>

#include <boost/assert.hpp>

using namespace armnnUtils;

namespace armnn
{

void DepthToSpace(const TensorInfo& inputInfo,
                  const DepthToSpaceDescriptor& descriptor,
                  const void* inputData,
                  void* outputData,
                  unsigned int dataTypeSize)
{
    const unsigned int blockSize = descriptor.m_BlockSize;
    BOOST_ASSERT(blockSize != 0u);

    const TensorShape& inputShape = inputInfo.GetShape();
    const unsigned int batches = inputShape[0];

    armnnUtils::DataLayoutIndexed dataLayoutIndexed(descriptor.m_DataLayout);
    const unsigned int inDepth  = inputShape[dataLayoutIndexed.GetChannelsIndex()];
    const unsigned int inHeight = inputShape[dataLayoutIndexed.GetHeightIndex()];
    const unsigned int inWidth  = inputShape[dataLayoutIndexed.GetWidthIndex()];

    const unsigned int outDepth = inDepth / (blockSize * blockSize);

    // The 4D input data can be interpreted as 6D (implicitly reshaped) as follows:
    //
    // [batch, block size, block size, inDepth, inHeight, inWidth] for NCHW and
    // [batch, inHeight, inWidth, blockSize, blockSize, outDepth] for NHWC.
    //
    // DepthToSpace can then be implemented as a permutation in 6D resulting in
    // the following shapes:
    //
    // [batch, outDepth, inHeight, blockSize, inWidth, blockSize] for NCHW and
    // [batch, inHeight, blockSize, inWidth, blockSize, outDepth] for NHWC.
    //
    // NOTE:
    // Since 6D tensors are not currently supported, in practice we need to handle each
    // batch separately and execute 5D permutations

    TensorShape permDestShape;
    std::initializer_list<unsigned int> permVector;
    if (descriptor.m_DataLayout == DataLayout::NCHW)
    {
        permDestShape = TensorShape({ outDepth, inHeight, blockSize, inWidth, blockSize });
        permVector    = { 2, 4, 0, 1, 3 };
    }
    else
    {
        permDestShape = TensorShape({ inHeight, blockSize, inWidth, blockSize, outDepth });
        permVector    = { 0, 2, 1, 3, 4 };
    }

    const unsigned int numElementsPerBatch = inputShape.GetNumElements() / batches;

    for (unsigned int batchIndex = 0u; batchIndex < batches; ++batchIndex)
    {
        const uintptr_t batchDataOffset = batchIndex * (numElementsPerBatch * dataTypeSize);

        armnnUtils::Permute(permDestShape,
                            PermutationVector(permVector),
                            static_cast<const void*>(reinterpret_cast<const uint8_t*>(inputData) + batchDataOffset),
                            static_cast<void*>(reinterpret_cast<uint8_t*>(outputData) + batchDataOffset),
                            dataTypeSize);
    }
}

} // namespace armnn
<commit_msg>IVGCVSW-3908 Fix DepthToSpace reference unit test failures on Android Q<commit_after>//
// Copyright © 2019 Arm Ltd. All rights reserved.
// SPDX-License-Identifier: MIT
//

#include "DepthToSpace.hpp"

#include <DataLayoutIndexed.hpp>
#include <Permute.hpp>

#include <boost/assert.hpp>

using namespace armnnUtils;

namespace armnn
{

void DepthToSpace(const TensorInfo& inputInfo,
                  const DepthToSpaceDescriptor& descriptor,
                  const void* inputData,
                  void* outputData,
                  unsigned int dataTypeSize)
{
    const unsigned int blockSize = descriptor.m_BlockSize;
    BOOST_ASSERT(blockSize != 0u);

    const TensorShape& inputShape = inputInfo.GetShape();
    const unsigned int batches = inputShape[0];

    armnnUtils::DataLayoutIndexed dataLayoutIndexed(descriptor.m_DataLayout);
    const unsigned int inDepth  = inputShape[dataLayoutIndexed.GetChannelsIndex()];
    const unsigned int inHeight = inputShape[dataLayoutIndexed.GetHeightIndex()];
    const unsigned int inWidth  = inputShape[dataLayoutIndexed.GetWidthIndex()];

    const unsigned int outDepth = inDepth / (blockSize * blockSize);

    // The 4D input data can be interpreted as 6D (implicitly reshaped) as follows:
    //
    // [batch, block size, block size, inDepth, inHeight, inWidth] for NCHW and
    // [batch, inHeight, inWidth, blockSize, blockSize, outDepth] for NHWC.
    //
    // DepthToSpace can then be implemented as a permutation in 6D resulting in
    // the following shapes:
    //
    // [batch, outDepth, inHeight, blockSize, inWidth, blockSize] for NCHW and
    // [batch, inHeight, blockSize, inWidth, blockSize, outDepth] for NHWC.
    //
    // NOTE:
    // Since 6D tensors are not currently supported, in practice we need to handle each
    // batch separately and execute 5D permutations

    TensorShape permDestShape;
    PermutationVector permVector{};
    if (descriptor.m_DataLayout == DataLayout::NCHW)
    {
        permDestShape = TensorShape({ outDepth, inHeight, blockSize, inWidth, blockSize });
        permVector    = { 2, 4, 0, 1, 3 };
    }
    else
    {
        permDestShape = TensorShape({ inHeight, blockSize, inWidth, blockSize, outDepth });
        permVector    = { 0, 2, 1, 3, 4 };
    }

    const unsigned int numElementsPerBatch = inputShape.GetNumElements() / batches;

    for (unsigned int batchIndex = 0u; batchIndex < batches; ++batchIndex)
    {
        const uintptr_t batchDataOffset = batchIndex * (numElementsPerBatch * dataTypeSize);

        armnnUtils::Permute(permDestShape,
                            permVector,
                            static_cast<const void*>(reinterpret_cast<const uint8_t*>(inputData) + batchDataOffset),
                            static_cast<void*>(reinterpret_cast<uint8_t*>(outputData) + batchDataOffset),
                            dataTypeSize);
    }
}

} // namespace armnn
<|endoftext|>


<commit_before>// -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: primitiveManager.C,v 1.41 2006/04/29 08:08:18 oliver Exp $
//
// Author:
//   Andreas Moll
//

#include <BALL/VIEW/KERNEL/primitiveManager.h>
#include <BALL/VIEW/KERNEL/mainControl.h>
#include <BALL/VIEW/KERNEL/clippingPlane.h>
#include <BALL/VIEW/KERNEL/threads.h>
#include <BALL/VIEW/KERNEL/message.h>
#include <BALL/VIEW/DIALOGS/displayProperties.h>
#include <BALL/FORMAT/INIFile.h>

#include <BALL/VIEW/PRIMITIVES/sphere.h>
#include <BALL/VIEW/PRIMITIVES/mesh.h>
#include <BALL/VIEW/PRIMITIVES/disc.h>
#include <BALL/VIEW/PRIMITIVES/box.h>
#include <BALL/VIEW/PRIMITIVES/simpleBox.h>
#include <BALL/VIEW/DATATYPE/vertex2.h>
#include <BALL/VIEW/DATATYPE/vertex1.h>

#include <qapplication.h>

namespace BALL
{
	namespace VIEW
	{

#ifdef BALL_QT_HAS_THREADS
	UpdateRepresentationThread PrimitiveManager::thread_;
	Mutex 										 PrimitiveManager::mutex_;
#endif

		PrimitiveManager::PrimitiveManager(MainControl* mc)
			throw()
			: Object(),
				main_control_(mc),
				update_running_(false),
				update_pending_(false)
		{
		}

		PrimitiveManager::~PrimitiveManager()
			throw()
		{
			clear();
		}

		PrimitiveManager::PrimitiveManager(const PrimitiveManager& pm)
			throw()
			: Object(pm)
		{
		}

		void PrimitiveManager::clear()
			throw()
		{
			representations_to_be_updated_.clear();
			currently_updateing_.clear();

		#ifdef BALL_QT_HAS_THREADS
			if (thread_.running())
			{
				thread_.terminate();
				thread_.wait();
			}
		#endif

			// call clear for all stored representations to clear also their geometric objects
			RepresentationsIterator it = begin();
			for (; it != end(); it++)
			{
				(*it)->clear();
			}
			representations_.clear();
		}

		bool PrimitiveManager::insert(Representation& representation, bool send_message)
			throw()
		{
			if (has(representation)) return false;
			representations_.push_back(&representation);

			if (!send_message) return true;

			main_control_->notify_(new RepresentationMessage(representation, RepresentationMessage::ADD));

			return true;
		}

		bool PrimitiveManager::has(const Representation& representation) const
			throw()
		{
			RepresentationsConstIterator it = begin();
			for (; it != end(); it++)
			{
				if (*it == &representation) return true;
			}
			return false;
		}

		bool PrimitiveManager::remove(Representation& representation, bool send_message)
			throw()
		{
			bool found = false;
			RepresentationsIterator it = begin();
			for( ; it != end(); it++)
			{
				if (*it == &representation)
				{
					found = true;
					break;
				}
			}

			if (!found) return false;

			representations_.erase(it);

			if (send_message)
			{
				main_control_->notify_(new RepresentationMessage(representation, RepresentationMessage::REMOVE));
			}

			if (!willBeUpdated(representation))
			{
				delete &representation;
			}

			return true;
		}

		void PrimitiveManager::dump(std::ostream& s, Size depth) const
			throw()
		{
			BALL_DUMP_STREAM_PREFIX(s);

			BALL_DUMP_DEPTH(s, depth);
			BALL_DUMP_HEADER(s, this, this);

			BALL_DUMP_DEPTH(s, depth);

			s << "number of representations: " << representations_.size() << std::endl;

			RepresentationsConstIterator it = begin();
			for (; it != end(); it++)
			{
				(*it)->dump(s, depth +1);
				s << std::endl;
			}

			BALL_DUMP_STREAM_SUFFIX(s);
		}

		Representation* PrimitiveManager::createRepresentation()
			throw()
		{
			Representation* rp = new Representation;
			insert(*rp, false);
			return rp;
		}

		const PrimitiveManager& PrimitiveManager::operator = (const PrimitiveManager& pm)
			throw()
		{
			RepresentationsConstIterator it = pm.begin();

			for (; it != pm.end(); it++)
			{
				Representation* rp = new Representation(**it);
				representations_.push_back(rp);
			}

			return *this;
		}

		bool PrimitiveManager::operator == (const PrimitiveManager& pm) const
			throw()
		{
			if (pm.getNumberOfRepresentations() != getNumberOfRepresentations()) return false;

			RepresentationsConstIterator it1 = begin();
			RepresentationsConstIterator it2 = pm.begin();
			for (; it1 != end() && it2 != pm.end(); it1++)
			{
				if (**it1 != **it2) return false;
				it2++;
			}

			return true;
		}

		PrimitiveManager::RepresentationList PrimitiveManager::removedComposite(const Composite& composite, bool update)
			throw()
		{
			// Representations either to be updated or deleted
			RepresentationList changed_representations = getRepresentationsOf(composite);

			RepresentationList removed_representations;

			// iterate over all Representations
			RepresentationsIterator rep_it = changed_representations.begin();
			for (; rep_it != changed_representations.end(); rep_it++)
			{
				Representation& rep = **rep_it;

				// test if a Representation has Composites which are (not) to be removed
				List<const Composite*> composites;

				List<const Composite*>::ConstIterator crit = rep.getComposites().begin();

				// special case for representations with composites of two different roots:
				// we have to update them manualy here!
				// otherwise no update will be done for this representations!
				const Composite* root = &(**crit).getRoot();
				bool must_be_updated = false;

				for(; crit != rep.getComposites().end(); crit++)
				{
					if (&composite != *crit && !composite.isAncestorOf(**crit))
					{
						composites.push_back(*crit);
					}

					if (&(**crit).getRoot() != root) must_be_updated = true;
				}

				rep.setComposites(composites);

				// if we have no more Composites in the Representation, it is to be deleted
				if (rep.getComposites().size() == 0)
				{
					removed_representations.push_back(&rep);
					continue;
				}

				// if we have no model processor, remove all GeometricObjects
				if (rep.getModelProcessor() == 0)
				{
					rep.clearGeometricObjects();
				}

				// see above: manual update
				if (must_be_updated)
				{
					rep.update(true);
					continue;
				}

				// call update for the Representation
				if (update) update_(rep);
			}

			// Representations are to be deleted
			rep_it = removed_representations.begin();
			for (; rep_it != removed_representations.end(); rep_it++)
			{
				remove(**rep_it);
			}

			return removed_representations;
		}

		List<Representation*> PrimitiveManager::getRepresentationsOf(const Composite& composite)
			throw()
		{
			List<Representation*> changed_representations;
			RepresentationsIterator rep_it = begin();
			for (; rep_it != end(); rep_it++)
			{
				List<const Composite*>::const_iterator cit = (**rep_it).getComposites().begin();
				for (; cit != (**rep_it).getComposites().end(); ++cit)
				{
					if (&composite == *cit ||
							composite.isRelatedWith(**cit))
					{
						changed_representations.push_back(*rep_it);
						break;
					}
				}
			}

			return changed_representations;
		}

		void PrimitiveManager::update_(Representation& rep)
			throw()
		{
			if (!has(rep))
			{
				return;
			}

		#ifdef BALL_QT_HAS_THREADS
			if (rep.isHidden())
			{
				rep.needs_update_ = true;
				// update of GeometricControl, also if Representation is hidden
				main_control_->notify_(new RepresentationMessage(rep, RepresentationMessage::UPDATE));
				return;
			}

			if (!getMainControl()->useMultithreading())
			{
				rep.update_();
				main_control_->notify_(new RepresentationMessage(rep, RepresentationMessage::UPDATE));
				return;
			}

			representations_to_be_updated_.push_back(&rep);
			currently_updateing_.insert(&rep);

			if (!updateRunning()) startUpdateThread_();
		#endif
		}

		void PrimitiveManager::startUpdateThread_()
			throw()
		{
		#ifdef BALL_VIEW_DEBUG
			Log.error() << "starting Representation Update" << std::endl;
		#endif

		#ifdef BALL_QT_HAS_THREADS
			if (!representations_to_be_updated_.size()) return;

			if (!mutex_.tryLock()) return;

			update_running_ = true;
			// maybe the Representation to be updated is already deleted?
			Representation* rep = *representations_to_be_updated_.begin();
			if (!has(*rep))
			{
				delete rep;
				representations_to_be_updated_.pop_front();
				currently_updateing_.erase(rep);
				mutex_.unlock();
				startUpdateThread_();
				return;
			}

			// start the UpdateRepresentationThread
			thread_.setRepresentation(*rep);

			#if BALL_QT_VERSION >=	0x030200
				thread_.start(QThread::LowPriority);
			#else
				thread_.start();
			#endif

			// no statusbar changes while beeing otherwise busy
			if (main_control_->compositesAreLocked()) return;

			thread_.wait(500);
			if (!thread_.running()) return;

			// keep the user informed: we are still building the Representation -> Statusbar text
			Position pos = 3;
			String dots;

			while (thread_.running())
			{
				main_control_->setStatusbarText("Creating Model ..." + dots);
				qApp->wakeUpGuiThread();
				qApp->processEvents();
				if (pos < 40)
				{
					pos ++;
					dots +="..";
				}
				else
				{
					pos = 3;
					dots = "...";
				}
				thread_.wait(500);
			}

			main_control_->setStatusbarText("");
		#endif
		}

		void PrimitiveManager::finishedUpdate_()
			throw()
		{
		#ifdef BALL_QT_HAS_THREADS
			if (representations_to_be_updated_.size() == 0)
			{
				BALLVIEW_DEBUG
				return;
			}

			Representation* rep = *representations_to_be_updated_.begin();
			representations_to_be_updated_.pop_front();
			currently_updateing_.erase(rep);

			// Representation might have been deleted
			if (has(*rep))
			{
				// no it wasnt, so update all widgets, that this Representation was rebuild
				main_control_->notify_(new RepresentationMessage(*rep, RepresentationMessage::UPDATE));
			}
			else
			{
				delete rep;
			}

			mutex_.unlock();

			if (representations_to_be_updated_.size() == 0)
			{
				#ifdef BALL_VIEW_DEBUG
					Log.error() << "finished all Representations Update" << std::endl;
				#endif

				update_running_ = false;
				update_pending_ = false;
				update_finished_.wakeAll();
				main_control_->setPreferencesEnabled_(true);
				return;
			}

			startUpdateThread_();
		#endif
		}

		bool PrimitiveManager::updateRunning() const
			throw()
		{
			return update_running_;
		}

		bool PrimitiveManager::willBeUpdated(const Representation& rep) const
			throw()
		{
			return currently_updateing_.has((Representation*)&rep);
		}

		HashSet<Representation*>& PrimitiveManager::getRepresentationsBeeingUpdated()
		{
			return currently_updateing_;
		}

		bool PrimitiveManager::removeClippingPlane(ClippingPlane* plane)
		{
			for (vector<ClippingPlane*>::iterator it = clipping_planes_.begin();
					 it != clipping_planes_.end(); it++)
			{
				if (*it == plane)
				{
					clipping_planes_.erase(it);
					delete (*it);
					getMainControl()->sendMessage(*new SyncClippingPlanesMessage());
					getMainControl()->sendMessage(*new SceneMessage(SceneMessage::REDRAW));

					return true;
				}
			}

			return false;
		}

		void PrimitiveManager::insertClippingPlane(ClippingPlane* plane)
		{
			clipping_planes_.push_back(plane);

			getMainControl()->sendMessage(*new SyncClippingPlanesMessage());
			getMainControl()->sendMessage(*new SceneMessage(SceneMessage::REDRAW));
		}

		void PrimitiveManager::rebuildAllRepresentations()
			throw()
		{
			RepresentationsIterator it = begin();
			for (;it != end(); it++)
			{
				if (currently_updateing_.has(*it)) continue;
				representations_to_be_updated_.push_back(*it);
				currently_updateing_.insert(*it);
			}

			startUpdateThread_();
		}

		void PrimitiveManager::storeRepresentations(INIFile& out)
		{
			Position nr_of_representations = 0;
			RepresentationsConstIterator it = begin();
			RepresentationList reps;
			for (; it != end(); it++)
			{
				// only store representations with composites!
				if (!(**it).getComposites().size() ||
						!modelMuteableByDisplayProperties((**it).getModelType()))
				{
					continue;
				}

				bool ok = true;

				// we can only store reps for one system!
				List<const Composite*>::const_iterator cit = (**it).getComposites().begin();
				const Composite* root = &(**cit).getRoot();
				cit++;
				for (; cit != (**it).getComposites().end(); cit++)
				{
					if ((**cit).getRoot() != *root)
					{
						ok = false;
						break;
					}
				}

				if (!ok)
				{
					Log.error() << "Can not store a representation for items of multiple systems." << std::endl;
					continue;
				}

				Index system_nr = -1;
				CompositeManager& cm = getMainControl()->getCompositeManager();
				CompositeManager::CompositeIterator cit2 = cm.begin();
				for (Position nr = 0; cit2 != cm.end(); cit2++)
				{
					if (root == *cit2)
					{
						system_nr = nr;
						break;
					}

					nr++;
				}

				if (system_nr == -1) continue;

				out.insertValue("BALLVIEW_PROJECT",
												String("Representation") + String(nr_of_representations),
												String(system_nr) + String(";") + (**it).toString());
				nr_of_representations++;
				reps.push_back(*it);
			}

			// create a numerical id for every representation
			HashMap<const Representation*, Position> rep_to_pos_map;

			PrimitiveManager::RepresentationList::const_iterator rep_it = reps.begin();
			for (Position i = 0; rep_it != reps.end(); rep_it++)
			{
				rep_to_pos_map[*rep_it] = i;
				i++;
			}

			// write the clipping planes
			for (Position plane_pos = 0; plane_pos < getClippingPlanes().size(); plane_pos++)
			{
				ClippingPlane* const plane = getClippingPlanes()[plane_pos];
				String data_string;

				data_string += vector3ToString(plane->getNormal());
				data_string += " ";
				data_string += vector3ToString(plane->getPoint());

				data_string += String(plane->isActive());
				data_string += " ";

				HashSet<const Representation*>::ConstIterator rit = plane->getRepresentations().begin();
				for (; +rit; ++rit)
				{
					data_string += String(rep_to_pos_map[*rit]);
					data_string += " ";
				}

				out.insertValue("BALLVIEW_PROJECT", "ClippingPlane" + String(plane_pos), data_string);
			}
		}

		void PrimitiveManager::restoreRepresentations(const INIFile& in, const vector<const Composite*>& new_systems)
		{
			DisplayProperties* dp = DisplayProperties::getInstance(0);

			if (dp == 0) return;

			try
			{
				for (Position p = 0; p < 9999999; p++)
				{
					// stop condition
					if (!in.hasEntry("BALLVIEW_PROJECT", "Representation" + String(p))) break;

					String data_string = in.getValue("BALLVIEW_PROJECT", "Representation" + String(p));

					vector<String> string_vector;
					Size split_size;

					// Representation0=1;3 2 2 6.500000 0 0 [2]|Color|H
					// 								 ^ 																	System Number
					// 								         ^            							Model Settings
					// 								         							 ^            Composites numbers
					// 								         							     ^        Custom Color
					// 								         							     			^   Hidden Flag

					// split off information of system number
					split_size = data_string.split(string_vector, ";");
					Position system_pos = string_vector[0].toUnsignedInt();

					// split off between representation settings and composite numbers
					data_string = string_vector[1];
					vector<String> string_vector2;
					data_string.split(string_vector2, "[]");
					data_string = string_vector2[0];

					if (!dp->getSettingsFromString(data_string))
					{
						BALLVIEW_DEBUG;
						Log.error() << "data_string " << std::endl;
						continue;
					}

					// Composites id's per number
					data_string = string_vector2[1];
					data_string.split(string_vector2, ",");
					HashSet<Position> hash_set;
					for (Position p = 0; p < string_vector2.size(); p++)
					{
						hash_set.insert(string_vector2[p].toUnsignedInt());
					}

					if (system_pos >= new_systems.size())
					{
						Log.error() << "Error while reading project file, invalid structure for Representation! Aborting..." << std::endl;
						continue;
					}

					// custom color
					data_string = string_vector[1];
					if (data_string.has('|'))
					{
						data_string.split(string_vector2, "|");
						ColorRGBA color;
						color = string_vector2[1];
						dp->setCustomColor(color);
					}

					// to select the composites for the new Representation:
					// send a ControlSelectionMessage, on which the DisplayProperties will work
					Composite* composite = (Composite*) new_systems[system_pos];
					ControlSelectionMessage* msg = new ControlSelectionMessage();
					Position current = 0;

					Composite::CompositeIterator ccit = composite->beginComposite();
					for (; +ccit; ++ccit)
					{
						if (hash_set.has(current)) msg->getSelection().push_back(&*ccit);
						current++;
					}

					if (hash_set.size() == 0)
					{
						BALLVIEW_DEBUG;
						continue;
					}

					getMainControl()->sendMessage(*msg);

					Representation* rep = 0;
					dp->apply();
					rep = dp->getRepresentation();
					if (rep == 0)
					{
						BALLVIEW_DEBUG;
						continue;
					}

					// is representation hidden?
					if (string_vector2.size() == 3 && string_vector2[2].has('H'))
					{
						rep->setHidden(true);
						rep->update(false);

			 #ifndef BALL_QT_HAS_THREADS
						getMainControl()->sendMessage(*new RepresentationMessage(*rep, RepresentationMessage::UPDATE));
			 #endif
					}
				}

				// create a vector with all Representations to access per numeric id
				vector<const Representation*> representations;

				PrimitiveManager::RepresentationList::const_iterator rit = getRepresentations().begin();
				for (; rit != getRepresentations().end(); rit++)
				{
					representations.push_back(*rit);
				}

				// create clipping planes
				for (Position p = 0; p < 9999999; p++)
				{
					if (!in.hasEntry("BALLVIEW_PROJECT", "ClippingPlane" + String(p))) break;

					String data_string = in.getValue("BALLVIEW_PROJECT", "ClippingPlane" + String(p));

					vector<String> string_vector;
					Size split_size = data_string.split(string_vector);

					// we have a clipping plane
					if (split_size < 3)
					{
						Log.error() << "Error in "  << __FILE__ << "  " << __LINE__<< std::endl;
						continue;
					}

					ClippingPlane* plane = new ClippingPlane();
					Vector3 v;
					stringToVector3(string_vector[0], v);
					plane->setNormal(v);
					stringToVector3(string_vector[1], v);
					plane->setPoint(v);

					bool is_active = string_vector[2].toBool();
					plane->setActive(is_active);

					for (Position rep_pos = 3; rep_pos < split_size; rep_pos++)
					{
						Position rep_nr = string_vector[rep_pos].toUnsignedInt();
						if (rep_nr > getNumberOfRepresentations())
						{
							Log.error() << "Error in "  << __FILE__ << "  " << __LINE__<< std::endl;
							continue;
						}

						plane->getRepresentations().insert(representations[rep_nr]);
					}

					insertClippingPlane(plane);

				} // for all clipping planes

			}
			catch(Exception::InvalidFormat e)
			{
				Log.error() << "Error while reading project file! Aborting..." << std::endl;
				Log.error() << e << std::endl;
				return;
			}
		}

		void PrimitiveManager::focusRepresentation(const Representation& rep)
		{
			List<Vector3> positions;

			Vector3 center;
			List<GeometricObject*>::ConstIterator it = rep.getGeometricObjects().begin();
			for (; it != rep.getGeometricObjects().end(); it++)
			{
				const GeometricObject& go = **it;

				// cant use Vertex or Vertex2 here, no idea why
				if (RTTI::isKindOf<Vertex2>(go))
				{
					const Vertex2& v = *dynamic_cast<const Vertex2*>(&go);
					positions.push_back(v.getVertex1());
					positions.push_back(v.getVertex2());
				}
				else if (RTTI::isKindOf<Vertex>(go))
				{
					const Vertex& v = *dynamic_cast<const Vertex*>(&go);
					positions.push_back(v.getVertex());
				}
				else if (RTTI::isKindOf<SimpleBox3>(go))
				{
					const SimpleBox3& b = reinterpret_cast<const SimpleBox3&>(go);
					positions.push_back(b.a);
					positions.push_back(b.b);
				}
				else if (RTTI::isKindOf<Sphere>(go))
				{
					const Sphere& s = reinterpret_cast<const Sphere&>(go);
					positions.push_back(s.getPosition());
				}
				else if (RTTI::isKindOf<Disc>(go))
				{
					const Disc& d = reinterpret_cast<const Disc&>(go);
					positions.push_back(d.getCircle().p);
				}
				else if (RTTI::isKindOf<Mesh>(go))
				{
					const Mesh& mesh = reinterpret_cast<const Mesh&>(go);

					for (Size index = 0; index < mesh.vertex.size(); ++index)
					{
						positions.push_back(mesh.vertex[index]);
					}
					continue;
				}
				else if (RTTI::isKindOf<BALL::VIEW::Box>(go))
				{
					const BALL::VIEW::Box& box = reinterpret_cast<const BALL::VIEW::Box&>(go);
					positions.push_back(box.getPoint());
					positions.push_back(box.getPoint() + box.getHeightVector());
					positions.push_back(box.getPoint() + box.getRightVector());
					positions.push_back(box.getPoint() + box.getDiagonalVector());
				}
				else
				{
					Log.error() << "Unknown geometric object: " << typeid(go).name()
											<< "in " << __FILE__ << __LINE__ << std::endl;
					continue;
				}
			}

			VIEW::focusCamera(positions);
		}

		HashSet<Representation*>& PrimitiveManager::getRepresentationsBeeingDrawn()
		{
			return currently_drawing_;
		}

	} // namespace VIEW

} // namespace BALL
<commit_msg>Removed the ancient and long-since obsolete primitive manager.<commit_after><|endoftext|>