<commit_before>#include "trainmonitor.h"
#include <QFile>
#include <QDir>
#include <QTextStream>

TrainMonitor::TrainMonitor()
{
#pragma message("[MKJ] Clean up when everything is done")
#pragma message("[MKJ] Look for things that would be useful in a log")

}

TrainMonitor::~TrainMonitor()
{

}

void TrainMonitor::do_run() {
	generateSectionList();
}

void TrainMonitor::do_handleOccupancy(QString section, bool state)
{
    qDebug() << __PRETTY_FUNCTION__;
	qDebug() << "New Occupancy Data at Monitor:" << section << " State:" << state;
	Section monitoredSection = retrieveSections(section);
	monitoredSection.setOccupancy(state);
    //if (state) Monitor(monitoredSection);
    if (state) Monitor(section);
}

void TrainMonitor::Monitor(QString section)
{
    //while (!m_engineSectionQueue.empty())
    //{
        //engineSection es = m_engineSectionQueue.front();
        //m_engineSectionQueue.dequeue();
        //updateEnginePath(es.path.getEngine());

#pragma message("[MKJ] Will nextSection1 be enough padding for a crash scenario?")
        //Section monitorSection = es.path.getNextSection1();

    Section currentSection = retrieveSections(section);

    switch (currentSection.getNumOfConns())
    {
        case 1:		// Endpoint case
        {
            updateSingleConnList(currentSection);
            endpointMonitor(currentSection);
            break;
        }
        case 2:		// Straight case
        {
            updateDoubleConnList(currentSection);
            straightMonitor(currentSection);
            break;
        }
        case 3:		// Switch case
        {
            updateTripleConnList(currentSection);
            switchMonitor(currentSection);
            break;
        }
        case 4:		// Crossover case
        {
            updateQuadConnList(currentSection);
            //crossoverMonitor(currentSection);
            break;
        }
        default:
        {
            qFatal("Invalid track type");
            break;
        }
    }
}

void TrainMonitor::endpointMonitor(Section sec)
{
	// Shutdown the section since the means the train is headed
    // towards the end of the track
    for (auto section : sectionPairs)
    {
        if (sec.getNode() == section.second)
        {
            if(section.first != "")
            {
                qDebug() << "Shutting off section " section.second;
                Section shutdownSection = retrieveSections(section.second);
                QStringList shutdownList = shutdownSection.getNode().split("-");
                emit sectionOff(shutdownList[0].toInt(),shutdownList[1].toInt());
            }
        }
    }
}

void TrainMonitor::straightMonitor(Section sec)
{
    QString nextSection;
    bool found = false;

    for (auto section : sectionPairs)
    {
        if(sec.getNode() == section.second)
        {
            nextSection = getNextStraightSection(
                        retrieveSections(section.first), retrieveSections(section.second));

            found = true;
        }
    }

    if(!found)
    {
        //QFatal << "Shit didn't work homie!!!";
    }

    for(auto section : sectionPairs)
    {
        if(nextSection == section.second)
        {
            //emit trackOff();
            qDebug() << "Shutting off section " section.second;
            Section shutdownSection = retrieveSections(section.second);
            QStringList shutdownList = shutdownSection.getNode().split("-");
            emit sectionOff(shutdownList[0].toInt(),shutdownList[1].toInt());
        }
    }
}

void TrainMonitor::switchMonitor(Section sec)
{
    QString monitorSection;
    QString nextSection;
    for (auto section : sectionPairs)
    {
        if(sec.getNode() == section.second)
        {
            nextSection = getNextStraightSection(
                        retrieveSections(section.first), retrieveSections(section.second));
        }

        if(nextSection != "")
        {
            switch (retrieveSections(nextSection).getNumOfConns())
            {
                case 1: {
                    //emit trackOff();
                    qDebug() << "Shutting off section " section.second;
                    Section shutdownSection = retrieveSections(nextSection);
                    QStringList shutdownList = shutdownSection.getNode().split("-");
                    emit sectionOff(shutdownList[0].toInt(),shutdownList[1].toInt());

                    break;
                } case 2: {
                    monitorSection = getNextStraightSection(
                                retrieveSections(section.first), retrieveSections(nextSection));
                    break;
                } case 3: {
                    monitorSection = getNextStraightSection(
                                retrieveSections(section.second), retrieveSections(nextSection));
                    break;
                } case 4:
                    // TODO
                    break;
            }
        }
    }

    for (auto section : sectionPairs)
    {
        if(section.second == monitorSection)
        {
            //emit trackOff();
            qDebug() << "Shutting off section " section.second;
            Section shutdownSection = retrieveSections(section.second);
            QStringList shutdownList = shutdownSection.getNode().split("-");
            emit sectionOff(shutdownList[0].toInt(),shutdownList[1].toInt());
        }
    }
}

//void TrainMonitor::crossoverMonitor(Section sec, engineSection es)
//{

//}

Section TrainMonitor::retrieveSections(QString section)
{
	Section newSection;
	//int NotFoundIndex;

	bool found = false;
	for (Section it : m_sectionList)
	{
		if (it.getNode() == section)
		{
			newSection = it;
			found = true;
			break;
		}
	}

	if (!found)
	{
		qWarning("Invalid section:%s. Are you sure the section exists?", section.toLatin1().constData());
	}

	return newSection;
}

void TrainMonitor::generateSectionList()
{
#pragma message("[MKJ] Do we want to move this to a central location?")
	qDebug() << "Testing file input";
	QString filename = QDir::currentPath().append("/Sections.txt");
	QFile infile(filename);
	if (!infile.open(QIODevice::ReadOnly | QIODevice::Text)) {

		qFatal("Cannot find input file: %s", filename.toLatin1().constData());
		return;
	}

	QTextStream in(&infile);
	QString node;
	int numOfConns;
    QString conn1, conn2, conn3;
    int ltNum; bool thrownLeft;

	while (!in.atEnd())
	{

		QStringList splitString = in.readLine().split(",");
        node = splitString[0];
        qDebug() << "node:" << node;
        numOfConns = splitString[1].toInt();
        conn1 = splitString[2];
        conn2 = splitString[3];
        conn3 = splitString[4];
        ltNum = splitString[5].toInt();
        thrownLeft = (splitString[6] == "false")? false : true;

        Section sec = Section(node, numOfConns, conn1, conn2,
            conn3, ltNum, thrownLeft);
		qDebug() << "SECTION:" << sec.getNode() << " CONN1:" << conn1 << ", CONN2:" << conn2;

		m_sectionList.append(sec);
	}
	infile.close();
}

void TrainMonitor::handle_serialOpened()
{
    int switches = 0;
    for (Section  sec : m_sectionList)
    {
        if (sec.getNumOfConns() ==  3)
        {
            switches++;
            emit throwTurnout(sec.getLtNum());
        }
    }

    qDebug() << switches << " switches have be initialized";
}

Section TrainMonitor::findNextSection(Section previousSection,
	Section currentSection)
{
	Section nextSection;
	Section temp;

	if (previousSection.getNode() != "" && currentSection.getNode() != "")
	{
		switch (currentSection.getNumOfConns())
		{
		case 1:
		{
			// The next section will be a null string
			break;
		}
		case 2:
		case 4:
		{
			// The next section will be the only other choice other
			// than the previous section (straight section) or conn1
			// or conn2 (crossover)
			if (currentSection.getConn1() == previousSection.getNode())
			{
				nextSection = retrieveSections(
					currentSection.getConn2());
			}
			else
			{
				nextSection = retrieveSections(
					currentSection.getConn1());
			}
			break;
		}
		case 3:
		{
			if (currentSection.getConn1() == previousSection.getNode())
			{
                if (currentSection.getThrownLeft())	// configured left
				{
					nextSection = retrieveSections(
						currentSection.getConn2());
				}
				else
				{
					nextSection = retrieveSections(
						currentSection.getConn3());
				}
			}
			else
			{
				nextSection = retrieveSections(
					currentSection.getConn1());
			}
		}
		}
	}
	else
	{
		// One or both of the track sections are null. Therefore, the next
		// section will be null too
	}

	return nextSection;
}

/// Updates to an endpoint.....fix comment later
void TrainMonitor::updateSingleConnList(Section current)
{
    bool found = false;
    for(auto sec : sectionPairs)
    {
        if (sec.second == current.getConn1())
        {
            sec.first = sec.second;
            sec.second = current.getNode();
            found = true;
        }
    }

    if(!found)
    {
        /// TODO
        std::pair<QString, QString> secPair=
                std::make_pair<QString, QString>("", current.getNode());
        sectionPairs.push_back(secPair);
    }
}

/// Updates strait aways.....
void TrainMonitor::updateDoubleConnList(Section current)
{
    bool found = false;
    for(auto sec : sectionPairs)
    {
        if (sec.second == current.getConn1() ||
                sec.second == current.getConn2())
        {
            sec.first = sec.second;
            sec.second = current.getNode();
            found = true;
        }
    }

    if(!found)
    {
        /// TODO
        std::pair<QString, QString> secPair=
                std::make_pair<QString, QString>("", current.getNode());
        sectionPairs.push_back(secPair);
    }
}

/// Updates switches.....
void TrainMonitor::updateTripleConnList(Section current)
{
    bool found = false;
    for(auto sec : sectionPairs)
    {
        if (sec.second == current.getConn1() ||
                sec.second == current.getConn2() ||
                sec.second == current.getConn3())
        {
            sec.first = sec.second;
            sec.second = current.getNode();
            found = true;
        }
    }

    if(!found)
        if(!found)
        {
            /// TODO
            std::pair<QString, QString> secPair =
                     std::make_pair<QString, QString>("", current.getNode());
            sectionPairs.push_back(secPair);
        }
}

/// Updates Crossovers....
void TrainMonitor::updateQuadConnList(Section current)
{
    // TODO
}

QString TrainMonitor::getNextStraightSection(Section previous, Section current)
{
    QString nextSection;
    if(previous.getNode() == current.getConn1())
    {
        nextSection = current.getConn2();
    }
    else
    {
        nextSection = current.getConn1();
    }

    return nextSection;
}

QString TrainMonitor::getNextSwitchSection(Section previous, Section current)
{
    QString nextSection;

    if(previous.getNode() == current.getConn2() ||
            previous.getNode() == current.getConn3())
    {
        nextSection = current.getConn1();
    }
    else
    {
        if(!current.getThrownLeft())
        {
            if(current.getThrown())
            {
                nextSection = current.getConn3();
            }
            else
            {
                nextSection = current.getConn2();
            }
        }
        else
        {
            if(current.getThrown())
            {
                nextSection = current.getConn2();
            }
            else
            {
                nextSection = current.getConn3();
            }
        }
    }

    return nextSection;
}

void TrainMonitor::do_handleSwitch(int LT, bool closed)
{
    qDebug() << __PRETTY_FUNCTION__;
    for(auto section : m_sectionList)
    {
        if(section.getLtNum() == LT)
        {
            if(closed)
            {
                section.setThrown(false);
            }
            else
            {
                section.setThrown(true);
            }
        }
    }
}

<commit_msg>fixed pretty function issue<commit_after>#include "trainmonitor.h"
#include <QFile>
#include <QDir>
#include <QTextStream>

TrainMonitor::TrainMonitor()
{
#pragma message("[MKJ] Clean up when everything is done")
#pragma message("[MKJ] Look for things that would be useful in a log")

}

TrainMonitor::~TrainMonitor()
{

}

void TrainMonitor::do_run() {
	generateSectionList();
}

void TrainMonitor::do_handleOccupancy(QString section, bool state)
{
    //qDebug() << __PRETTY_FUNCTION__;
	qDebug() << "New Occupancy Data at Monitor:" << section << " State:" << state;
	Section monitoredSection = retrieveSections(section);
	monitoredSection.setOccupancy(state);
    //if (state) Monitor(monitoredSection);
    if (state) Monitor(section);
}

void TrainMonitor::Monitor(QString section)
{
    //while (!m_engineSectionQueue.empty())
    //{
        //engineSection es = m_engineSectionQueue.front();
        //m_engineSectionQueue.dequeue();
        //updateEnginePath(es.path.getEngine());

#pragma message("[MKJ] Will nextSection1 be enough padding for a crash scenario?")
        //Section monitorSection = es.path.getNextSection1();

    Section currentSection = retrieveSections(section);

    switch (currentSection.getNumOfConns())
    {
        case 1:		// Endpoint case
        {
            updateSingleConnList(currentSection);
            endpointMonitor(currentSection);
            break;
        }
        case 2:		// Straight case
        {
            updateDoubleConnList(currentSection);
            straightMonitor(currentSection);
            break;
        }
        case 3:		// Switch case
        {
            updateTripleConnList(currentSection);
            switchMonitor(currentSection);
            break;
        }
        case 4:		// Crossover case
        {
            updateQuadConnList(currentSection);
            //crossoverMonitor(currentSection);
            break;
        }
        default:
        {
            qFatal("Invalid track type");
            break;
        }
    }
}

void TrainMonitor::endpointMonitor(Section sec)
{
	// Shutdown the section since the means the train is headed
    // towards the end of the track
    for (auto section : sectionPairs)
    {
        if (sec.getNode() == section.second)
        {
            if(section.first != "")
            {
                qDebug() << "Shutting off section " << section.second;
                Section shutdownSection = retrieveSections(section.second);
                QStringList shutdownList = shutdownSection.getNode().split("-");
                emit sectionOff(shutdownList[0].toInt(),shutdownList[1].toInt());
            }
        }
    }
}

void TrainMonitor::straightMonitor(Section sec)
{
    QString nextSection;
    bool found = false;

    for (auto section : sectionPairs)
    {
        if(sec.getNode() == section.second)
        {
            nextSection = getNextStraightSection(
                        retrieveSections(section.first), retrieveSections(section.second));

            found = true;
        }
    }

    if(!found)
    {
        //QFatal << "Shit didn't work homie!!!";
    }

    for(auto section : sectionPairs)
    {
        if(nextSection == section.second)
        {
            //emit trackOff();
            qDebug() << "Shutting off section " << section.second;
            Section shutdownSection = retrieveSections(section.second);
            QStringList shutdownList = shutdownSection.getNode().split("-");
            emit sectionOff(shutdownList[0].toInt(),shutdownList[1].toInt());
        }
    }
}

void TrainMonitor::switchMonitor(Section sec)
{
    QString monitorSection;
    QString nextSection;
    for (auto section : sectionPairs)
    {
        if(sec.getNode() == section.second)
        {
            nextSection = getNextStraightSection(
                        retrieveSections(section.first), retrieveSections(section.second));
        }

        if(nextSection != "")
        {
            switch (retrieveSections(nextSection).getNumOfConns())
            {
                case 1: {
                    //emit trackOff();
                    qDebug() << "Shutting off section " << section.second;
                    Section shutdownSection = retrieveSections(nextSection);
                    QStringList shutdownList = shutdownSection.getNode().split("-");
                    emit sectionOff(shutdownList[0].toInt(),shutdownList[1].toInt());

                    break;
                } case 2: {
                    monitorSection = getNextStraightSection(
                                retrieveSections(section.first), retrieveSections(nextSection));
                    break;
                } case 3: {
                    monitorSection = getNextStraightSection(
                                retrieveSections(section.second), retrieveSections(nextSection));
                    break;
                } case 4:
                    // TODO
                    break;
            }
        }
    }

    for (auto section : sectionPairs)
    {
        if(section.second == monitorSection)
        {
            //emit trackOff();
            qDebug() << "Shutting off section " << section.second;
            Section shutdownSection = retrieveSections(section.second);
            QStringList shutdownList = shutdownSection.getNode().split("-");
            emit sectionOff(shutdownList[0].toInt(),shutdownList[1].toInt());
        }
    }
}

//void TrainMonitor::crossoverMonitor(Section sec, engineSection es)
//{

//}

Section TrainMonitor::retrieveSections(QString section)
{
	Section newSection;
	//int NotFoundIndex;

	bool found = false;
	for (Section it : m_sectionList)
	{
		if (it.getNode() == section)
		{
			newSection = it;
			found = true;
			break;
		}
	}

	if (!found)
	{
		qWarning("Invalid section:%s. Are you sure the section exists?", section.toLatin1().constData());
	}

	return newSection;
}

void TrainMonitor::generateSectionList()
{
#pragma message("[MKJ] Do we want to move this to a central location?")
	qDebug() << "Testing file input";
	QString filename = QDir::currentPath().append("/Sections.txt");
	QFile infile(filename);
	if (!infile.open(QIODevice::ReadOnly | QIODevice::Text)) {

		qFatal("Cannot find input file: %s", filename.toLatin1().constData());
		return;
	}

	QTextStream in(&infile);
	QString node;
	int numOfConns;
    QString conn1, conn2, conn3;
    int ltNum; bool thrownLeft;

	while (!in.atEnd())
	{

		QStringList splitString = in.readLine().split(",");
        node = splitString[0];
        qDebug() << "node:" << node;
        numOfConns = splitString[1].toInt();
        conn1 = splitString[2];
        conn2 = splitString[3];
        conn3 = splitString[4];
        ltNum = splitString[5].toInt();
        thrownLeft = (splitString[6] == "false")? false : true;

        Section sec = Section(node, numOfConns, conn1, conn2,
            conn3, ltNum, thrownLeft);
		qDebug() << "SECTION:" << sec.getNode() << " CONN1:" << conn1 << ", CONN2:" << conn2;

		m_sectionList.append(sec);
	}
	infile.close();
}

void TrainMonitor::handle_serialOpened()
{
    int switches = 0;
    for (Section  sec : m_sectionList)
    {
        if (sec.getNumOfConns() ==  3)
        {
            switches++;
            emit throwTurnout(sec.getLtNum());
        }
    }

    qDebug() << switches << " switches have be initialized";
}

Section TrainMonitor::findNextSection(Section previousSection,
	Section currentSection)
{
	Section nextSection;
	Section temp;

	if (previousSection.getNode() != "" && currentSection.getNode() != "")
	{
		switch (currentSection.getNumOfConns())
		{
		case 1:
		{
			// The next section will be a null string
			break;
		}
		case 2:
		case 4:
		{
			// The next section will be the only other choice other
			// than the previous section (straight section) or conn1
			// or conn2 (crossover)
			if (currentSection.getConn1() == previousSection.getNode())
			{
				nextSection = retrieveSections(
					currentSection.getConn2());
			}
			else
			{
				nextSection = retrieveSections(
					currentSection.getConn1());
			}
			break;
		}
		case 3:
		{
			if (currentSection.getConn1() == previousSection.getNode())
			{
                if (currentSection.getThrownLeft())	// configured left
				{
					nextSection = retrieveSections(
						currentSection.getConn2());
				}
				else
				{
					nextSection = retrieveSections(
						currentSection.getConn3());
				}
			}
			else
			{
				nextSection = retrieveSections(
					currentSection.getConn1());
			}
		}
		}
	}
	else
	{
		// One or both of the track sections are null. Therefore, the next
		// section will be null too
	}

	return nextSection;
}

/// Updates to an endpoint.....fix comment later
void TrainMonitor::updateSingleConnList(Section current)
{
    bool found = false;
    for(auto sec : sectionPairs)
    {
        if (sec.second == current.getConn1())
        {
            sec.first = sec.second;
            sec.second = current.getNode();
            found = true;
        }
    }

    if(!found)
    {
        /// TODO
        std::pair<QString, QString> secPair=
                std::make_pair<QString, QString>("", current.getNode());
        sectionPairs.push_back(secPair);
    }
}

/// Updates strait aways.....
void TrainMonitor::updateDoubleConnList(Section current)
{
    bool found = false;
    for(auto sec : sectionPairs)
    {
        if (sec.second == current.getConn1() ||
                sec.second == current.getConn2())
        {
            sec.first = sec.second;
            sec.second = current.getNode();
            found = true;
        }
    }

    if(!found)
    {
        /// TODO
        std::pair<QString, QString> secPair=
                std::make_pair<QString, QString>("", current.getNode());
        sectionPairs.push_back(secPair);
    }
}

/// Updates switches.....
void TrainMonitor::updateTripleConnList(Section current)
{
    bool found = false;
    for(auto sec : sectionPairs)
    {
        if (sec.second == current.getConn1() ||
                sec.second == current.getConn2() ||
                sec.second == current.getConn3())
        {
            sec.first = sec.second;
            sec.second = current.getNode();
            found = true;
        }
    }

    if(!found)
        if(!found)
        {
            /// TODO
            std::pair<QString, QString> secPair =
                     std::make_pair<QString, QString>("", current.getNode());
            sectionPairs.push_back(secPair);
        }
}

/// Updates Crossovers....
void TrainMonitor::updateQuadConnList(Section current)
{
    // TODO
}

QString TrainMonitor::getNextStraightSection(Section previous, Section current)
{
    QString nextSection;
    if(previous.getNode() == current.getConn1())
    {
        nextSection = current.getConn2();
    }
    else
    {
        nextSection = current.getConn1();
    }

    return nextSection;
}

QString TrainMonitor::getNextSwitchSection(Section previous, Section current)
{
    QString nextSection;

    if(previous.getNode() == current.getConn2() ||
            previous.getNode() == current.getConn3())
    {
        nextSection = current.getConn1();
    }
    else
    {
        if(!current.getThrownLeft())
        {
            if(current.getThrown())
            {
                nextSection = current.getConn3();
            }
            else
            {
                nextSection = current.getConn2();
            }
        }
        else
        {
            if(current.getThrown())
            {
                nextSection = current.getConn2();
            }
            else
            {
                nextSection = current.getConn3();
            }
        }
    }

    return nextSection;
}

void TrainMonitor::do_handleSwitch(int LT, bool closed)
{
    //qDebug() << __PRETTY_FUNCTION__;
    for(auto section : m_sectionList)
    {
        if(section.getLtNum() == LT)
        {
            if(closed)
            {
                section.setThrown(false);
            }
            else
            {
                section.setThrown(true);
            }
        }
    }
}

<|endoftext|>


<commit_before>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include "inset.h"
#include "polygonOptimizer.h"
#include "utils/polygonUtils.h"
namespace cura {

void generateInsets(SliceLayerPart* part, int extrusionWidth, int insetCount, bool avoidOverlappingPerimeters)
{
    part->combBoundery = part->outline.offset(-extrusionWidth);
    if (insetCount == 0)
    {
        part->insets.push_back(part->outline);
        return;
    }

    for(int i=0; i<insetCount; i++)
    {
        part->insets.push_back(Polygons());
        if (i == 0)
        {
            offsetSafe(part->outline, - extrusionWidth/2, extrusionWidth, part->insets[i], avoidOverlappingPerimeters);
        } else
        {
            offsetExtrusionWidth(part->insets[i-1], true, extrusionWidth, part->insets[i], &part->perimeterGaps, avoidOverlappingPerimeters);
        }

        optimizePolygons(part->insets[i]);
        if (part->insets[i].size() < 1)
        {
            part->insets.pop_back();
            break;
        }
    }
}

void generateInsets(SliceLayer* layer, int extrusionWidth, int insetCount, bool avoidOverlappingPerimeters)
{
    for(unsigned int partNr = 0; partNr < layer->parts.size(); partNr++)
    {
        generateInsets(&layer->parts[partNr], extrusionWidth, insetCount, avoidOverlappingPerimeters);
    }

    //Remove the parts which did not generate an inset. As these parts are too small to print,
    // and later code can now assume that there is always minimal 1 inset line.
    for(unsigned int partNr = 0; partNr < layer->parts.size(); partNr++)
    {
        if (layer->parts[partNr].insets.size() < 1)
        {
            layer->parts.erase(layer->parts.begin() + partNr);
            partNr -= 1;
        }
    }
}

}//namespace cura
<commit_msg>made the comb boundary larger, so that (barely) connected parts still use the comb boundary<commit_after>/** Copyright (C) 2013 David Braam - Released under terms of the AGPLv3 License */
#include "inset.h"
#include "polygonOptimizer.h"
#include "utils/polygonUtils.h"
namespace cura {

void generateInsets(SliceLayerPart* part, int extrusionWidth, int insetCount, bool avoidOverlappingPerimeters)
{
    int combBoundaryInset = extrusionWidth/2; // hard coded value
    part->combBoundery = part->outline.offset(-combBoundaryInset);
    if (insetCount == 0)
    {
        part->insets.push_back(part->outline);
        return;
    }

    for(int i=0; i<insetCount; i++)
    {
        part->insets.push_back(Polygons());
        if (i == 0)
        {
            offsetSafe(part->outline, - extrusionWidth/2, extrusionWidth, part->insets[i], avoidOverlappingPerimeters);
        } else
        {
            offsetExtrusionWidth(part->insets[i-1], true, extrusionWidth, part->insets[i], &part->perimeterGaps, avoidOverlappingPerimeters);
        }

        optimizePolygons(part->insets[i]);
        if (part->insets[i].size() < 1)
        {
            part->insets.pop_back();
            break;
        }
    }
}

void generateInsets(SliceLayer* layer, int extrusionWidth, int insetCount, bool avoidOverlappingPerimeters)
{
    for(unsigned int partNr = 0; partNr < layer->parts.size(); partNr++)
    {
        generateInsets(&layer->parts[partNr], extrusionWidth, insetCount, avoidOverlappingPerimeters);
    }

    //Remove the parts which did not generate an inset. As these parts are too small to print,
    // and later code can now assume that there is always minimal 1 inset line.
    for(unsigned int partNr = 0; partNr < layer->parts.size(); partNr++)
    {
        if (layer->parts[partNr].insets.size() < 1)
        {
            layer->parts.erase(layer->parts.begin() + partNr);
            partNr -= 1;
        }
    }
}

}//namespace cura
<|endoftext|>


<commit_before>// This source file compiles those annoying implementation-in-header libraries

#define GLEW_STATIC
#include <GL/glew.h>

#include <nanovg.h>

#define NANOVG_GL2_IMPLEMENTATION
// #define NANOVG_GL3_IMPLEMENTATION
// #define NANOVG_GLES2_IMPLEMENTATION
// #define NANOVG_GLES3_IMPLEMENTATION
#include <nanovg_gl.h>

// Hack to get framebuffer objects working on OpenGL 2 (we blindly assume the extension is supported)
#define NANOVG_FBO_VALID
#include <nanovg_gl_utils.h>

#define BLENDISH_IMPLEMENTATION
#include <blendish.h>

#define NANOSVG_IMPLEMENTATION
#define NANOSVG_ALL_COLOR_KEYWORDS
#include <nanosvg.h>

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include <stb_image_write.h>
<commit_msg>Remove stb_imagewrite.h reference.<commit_after>// This source file compiles those annoying implementation-in-header libraries

#define GLEW_STATIC
#include <GL/glew.h>

#include <nanovg.h>

#define NANOVG_GL2_IMPLEMENTATION
// #define NANOVG_GL3_IMPLEMENTATION
// #define NANOVG_GLES2_IMPLEMENTATION
// #define NANOVG_GLES3_IMPLEMENTATION
#include <nanovg_gl.h>

// Hack to get framebuffer objects working on OpenGL 2 (we blindly assume the extension is supported)
#define NANOVG_FBO_VALID
#include <nanovg_gl_utils.h>

#define BLENDISH_IMPLEMENTATION
#include <blendish.h>

#define NANOSVG_IMPLEMENTATION
#define NANOSVG_ALL_COLOR_KEYWORDS
#include <nanosvg.h>
<|endoftext|>


<commit_before>#include "Library.h"
#include "AddGameWizard.h"
#include "Defines.h"
#include "GridGameWidget.h"

#include <QFileDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QDebug>
#include <QFileSystemWatcher>

Database Library::db(QDir(CONFIG_FOLDER).filePath("horizon.db"));

/** Library constructor
 * Initialize the library UI and generate an initial list of all the games available.
 * \param p Inherited palette configuration for setting StyleSheets.
 * \param parent Pointer to parent widget.
*/
Library::Library(QSettings* p, QWidget* parent)
    : QWidget(parent)
{
    this->setObjectName("libraryUI");
    this->setStyleSheet("QPushButton {"
                        "color: " + p->value("Primary/LightText").toString() + "; "
                        "background-color: " + p->value("Primary/DarkElement").toString() + "; "
                        "border: none; margin: 0px; padding: 0px;} "
                        "QPushButton:hover {"
                        "background-color: " + p->value("Primary/InactiveSelection").toString() + ";} "
                        "QListWidget {"
                        "background-color: " + p->value("Primary/TertiaryBase").toString() + "; "
                        "color: " + p->value("Primary/LightText").toString() + ";}"
                        "QLabel {"
                        "color: " + p->value("Primary/LightText").toString() + ";"
                        "font-family: SourceSansPro; }"
                        "QComboBox::down-arrow { image: url(:/SystemMenu/Icons/DropdownArrow.png); }");

    init(p);

    QList<Game> games = Library::db.getGames();
    for (auto game : games)
    {
        qDebug() << game.id << game.gameName << game.gameDirectory << game.executablePath;
    }

    connect(&db, &Database::dbChanged, this, &Library::refreshGames);

    refreshGames();
}

void Library::init(QSettings* p)
{
    QGridLayout* mainLayout = new QGridLayout(this);
    mainLayout->setMargin(0);

    QWidget* searchBar = new QWidget();
    searchBar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    searchBar->setMinimumHeight(40);
    searchBar->setStyleSheet("background-color:" + p->value("Navbar/SelectedColor").toString() + ";");
    mainLayout->addWidget(searchBar, 0, 0);

    QHBoxLayout* searchLayout = new QHBoxLayout(searchBar);

    searchBox = new QLineEdit();
    searchBox->setPlaceholderText(tr("Search games"));
    searchBox->setStyleSheet("border: none;"
                             "color: " + p->value("Primary/LightText").toString() + ";");
    searchBox->setMinimumWidth(225);
    searchBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    searchLayout->addWidget(searchBox);
    connect(searchBox, &QLineEdit::returnPressed, this, &Library::refreshGames);

    QPixmap search(":/SystemMenu/Icons/SearchInverted.png");
    QIcon searchIcon(search);

    QPushButton* searchBtn = new QPushButton("");
    searchBtn->setIcon(searchIcon);
    searchBtn->setIconSize(QSize(16, 16));
    searchBtn->setStyleSheet("background-color: transparent;");
    searchBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    searchLayout->addWidget(searchBtn);
    connect(searchBtn, &QPushButton::clicked, this, &Library::refreshGames);

    QWidget* line = new QWidget();
    line->setMinimumSize(1, 2);
    line->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
    line->setStyleSheet("border: 1px solid #9e5eee;");
    searchLayout->addWidget(line);

    QFont textFont("Roboto", 11);

    QLabel* filterLabel = new QLabel(tr("Filter by: "));
    filterLabel->setFont(textFont);
    searchLayout->addWidget(filterLabel);

    QComboBox* filterBox = new QComboBox();
    filterBox->addItem(tr("All"));
    searchLayout->addWidget(filterBox);

    QComboBox* actionBox = new QComboBox();
    actionBox->addItem(tr("Action"));
    searchLayout->addWidget(actionBox);

    QComboBox* ratingBox = new QComboBox();
    ratingBox->addItem(tr("Rating"));
    searchLayout->addWidget(ratingBox);

    searchLayout->addStretch();

    QPixmap grid(":/SystemMenu/Icons/GridViewInverted.png");
    QIcon gridIcon(grid);
    QPixmap listImg(":/SystemMenu/Icons/DetailedListViewInverted.png");
    QIcon listIcon(listImg);
    QPixmap carousel(":/SystemMenu/Icons/CarouselViewInverted.png");
    QIcon carouselIcon(carousel);

    QPushButton* gridBtn = new QPushButton("");
    gridBtn->setIcon(gridIcon);
    gridBtn->setIconSize(QSize(16, 16));
    gridBtn->setStyleSheet("background-color: transparent;");
    gridBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    searchLayout->addWidget(gridBtn);

    QPushButton* listBtn = new QPushButton("");
    listBtn->setIcon(listIcon);
    listBtn->setIconSize(QSize(16, 16));
    listBtn->setStyleSheet("background-color: transparent;");
    listBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    searchLayout->addWidget(listBtn);

    QPushButton* carouselBtn = new QPushButton("");
    carouselBtn->setIcon(carouselIcon);
    carouselBtn->setIconSize(QSize(16, 16));
    carouselBtn->setStyleSheet("background-color: transparent;");
    carouselBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    searchLayout->addWidget(carouselBtn);

    QPushButton* addGameBtn = new QPushButton(tr("Add game"));
    addGameBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    addGameBtn->setStyleSheet("margin: 11px 0 0 11px; padding: 5px;");
    mainLayout->addWidget(addGameBtn, 1, 0);
    connect(addGameBtn, &QPushButton::clicked, this, &Library::addGame);

    QWidget* gamesWidget = new QWidget();
    mainLayout->addWidget(gamesWidget, 2, 0);

    gamesLayout = new QGridLayout();
    gamesLayout->setSpacing(12);
    gamesWidget->setLayout(gamesLayout);
}

/** Function to launch a game.
 * Populates a message box on failure, or runs the games upon success.
 * \param gameName The name of the game to launch
*/
void Library::launchGame(QString gameName)
{
    if (!gl.isProcessRunning())
    {
        Game game = Library::db.getGameByName(gameName);
        if (game.arguments.trimmed() == "")
        {
            gl.runProcess(game.executablePath, game.gameDirectory);
        }
        else
        {
            gl.runProcessWithArgs(game.executablePath, game.gameDirectory, game.arguments);
        }
    }
    else
    {
        QMessageBox messageBox;
        messageBox.setText(tr("Error: an application is already running."));
        messageBox.exec();
    }
}

/** Event handler for adding a game.
 * Prompts the user for various paths, and adds the final game to the database.
*/
void Library::addGame()
{
    AddGameWizard* wiz = new AddGameWizard();
    wiz->show();
}

/** Recreate the list of games displayed in the main widget.
* Sort the list alphabetically by name
*/
void Library::refreshGames()
{
    qDebug() << "REFRESH";
    for (int i = 0; i < gamesWidgets.size(); i++)
    {
        QWidget* widget = gamesWidgets[i];
        gamesLayout->removeWidget(widget);
        widget->deleteLater();
    }
    gamesWidgets.clear();

    QList<Game> gameList = Library::db.getGames();
    std::sort(gameList.begin(), gameList.end(), [&](const Game& g1, const Game& g2){return g1.gameName < g2.gameName; });
    int row = 0, col = 0;
    for (auto game : gameList)
    {
        QString lowerGameName = game.gameName.toLower();
        QString searchString = searchBox->text().trimmed();
        if (!searchString.isEmpty() && !lowerGameName.contains(searchString.toLower()))
        {
            continue;
        }

        GridGameWidget* gameWidget = new GridGameWidget(game.gameName, 999);
        gamesLayout->addWidget(gameWidget, row, col);
        connect(gameWidget, &GridGameWidget::clicked, [=] { launchGame(game.gameName); });
        gamesWidgets.append(gameWidget);

        if (col == 3)
        {
            row++;
        }
        col = (col < 3 ? col + 1 : 0);
    }
}
<commit_msg>Remove debug line<commit_after>#include "Library.h"
#include "AddGameWizard.h"
#include "Defines.h"
#include "GridGameWidget.h"

#include <QFileDialog>
#include <QInputDialog>
#include <QMessageBox>
#include <QDebug>
#include <QFileSystemWatcher>

Database Library::db(QDir(CONFIG_FOLDER).filePath("horizon.db"));

/** Library constructor
 * Initialize the library UI and generate an initial list of all the games available.
 * \param p Inherited palette configuration for setting StyleSheets.
 * \param parent Pointer to parent widget.
*/
Library::Library(QSettings* p, QWidget* parent)
    : QWidget(parent)
{
    this->setObjectName("libraryUI");
    this->setStyleSheet("QPushButton {"
                        "color: " + p->value("Primary/LightText").toString() + "; "
                        "background-color: " + p->value("Primary/DarkElement").toString() + "; "
                        "border: none; margin: 0px; padding: 0px;} "
                        "QPushButton:hover {"
                        "background-color: " + p->value("Primary/InactiveSelection").toString() + ";} "
                        "QListWidget {"
                        "background-color: " + p->value("Primary/TertiaryBase").toString() + "; "
                        "color: " + p->value("Primary/LightText").toString() + ";}"
                        "QLabel {"
                        "color: " + p->value("Primary/LightText").toString() + ";"
                        "font-family: SourceSansPro; }"
                        "QComboBox::down-arrow { image: url(:/SystemMenu/Icons/DropdownArrow.png); }");

    init(p);

    QList<Game> games = Library::db.getGames();
    for (auto game : games)
    {
        qDebug() << game.id << game.gameName << game.gameDirectory << game.executablePath;
    }

    connect(&db, &Database::dbChanged, this, &Library::refreshGames);

    refreshGames();
}

void Library::init(QSettings* p)
{
    QGridLayout* mainLayout = new QGridLayout(this);
    mainLayout->setMargin(0);

    QWidget* searchBar = new QWidget();
    searchBar->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed);
    searchBar->setMinimumHeight(40);
    searchBar->setStyleSheet("background-color:" + p->value("Navbar/SelectedColor").toString() + ";");
    mainLayout->addWidget(searchBar, 0, 0);

    QHBoxLayout* searchLayout = new QHBoxLayout(searchBar);

    searchBox = new QLineEdit();
    searchBox->setPlaceholderText(tr("Search games"));
    searchBox->setStyleSheet("border: none;"
                             "color: " + p->value("Primary/LightText").toString() + ";");
    searchBox->setMinimumWidth(225);
    searchBox->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    searchLayout->addWidget(searchBox);
    connect(searchBox, &QLineEdit::returnPressed, this, &Library::refreshGames);

    QPixmap search(":/SystemMenu/Icons/SearchInverted.png");
    QIcon searchIcon(search);

    QPushButton* searchBtn = new QPushButton("");
    searchBtn->setIcon(searchIcon);
    searchBtn->setIconSize(QSize(16, 16));
    searchBtn->setStyleSheet("background-color: transparent;");
    searchBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    searchLayout->addWidget(searchBtn);
    connect(searchBtn, &QPushButton::clicked, this, &Library::refreshGames);

    QWidget* line = new QWidget();
    line->setMinimumSize(1, 2);
    line->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding);
    line->setStyleSheet("border: 1px solid #9e5eee;");
    searchLayout->addWidget(line);

    QFont textFont("Roboto", 11);

    QLabel* filterLabel = new QLabel(tr("Filter by: "));
    filterLabel->setFont(textFont);
    searchLayout->addWidget(filterLabel);

    QComboBox* filterBox = new QComboBox();
    filterBox->addItem(tr("All"));
    searchLayout->addWidget(filterBox);

    QComboBox* actionBox = new QComboBox();
    actionBox->addItem(tr("Action"));
    searchLayout->addWidget(actionBox);

    QComboBox* ratingBox = new QComboBox();
    ratingBox->addItem(tr("Rating"));
    searchLayout->addWidget(ratingBox);

    searchLayout->addStretch();

    QPixmap grid(":/SystemMenu/Icons/GridViewInverted.png");
    QIcon gridIcon(grid);
    QPixmap listImg(":/SystemMenu/Icons/DetailedListViewInverted.png");
    QIcon listIcon(listImg);
    QPixmap carousel(":/SystemMenu/Icons/CarouselViewInverted.png");
    QIcon carouselIcon(carousel);

    QPushButton* gridBtn = new QPushButton("");
    gridBtn->setIcon(gridIcon);
    gridBtn->setIconSize(QSize(16, 16));
    gridBtn->setStyleSheet("background-color: transparent;");
    gridBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    searchLayout->addWidget(gridBtn);

    QPushButton* listBtn = new QPushButton("");
    listBtn->setIcon(listIcon);
    listBtn->setIconSize(QSize(16, 16));
    listBtn->setStyleSheet("background-color: transparent;");
    listBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    searchLayout->addWidget(listBtn);

    QPushButton* carouselBtn = new QPushButton("");
    carouselBtn->setIcon(carouselIcon);
    carouselBtn->setIconSize(QSize(16, 16));
    carouselBtn->setStyleSheet("background-color: transparent;");
    carouselBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    searchLayout->addWidget(carouselBtn);

    QPushButton* addGameBtn = new QPushButton(tr("Add game"));
    addGameBtn->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
    addGameBtn->setStyleSheet("margin: 11px 0 0 11px; padding: 5px;");
    mainLayout->addWidget(addGameBtn, 1, 0);
    connect(addGameBtn, &QPushButton::clicked, this, &Library::addGame);

    QWidget* gamesWidget = new QWidget();
    mainLayout->addWidget(gamesWidget, 2, 0);

    gamesLayout = new QGridLayout();
    gamesLayout->setSpacing(12);
    gamesWidget->setLayout(gamesLayout);
}

/** Function to launch a game.
 * Populates a message box on failure, or runs the games upon success.
 * \param gameName The name of the game to launch
*/
void Library::launchGame(QString gameName)
{
    if (!gl.isProcessRunning())
    {
        Game game = Library::db.getGameByName(gameName);
        if (game.arguments.trimmed() == "")
        {
            gl.runProcess(game.executablePath, game.gameDirectory);
        }
        else
        {
            gl.runProcessWithArgs(game.executablePath, game.gameDirectory, game.arguments);
        }
    }
    else
    {
        QMessageBox messageBox;
        messageBox.setText(tr("Error: an application is already running."));
        messageBox.exec();
    }
}

/** Event handler for adding a game.
 * Prompts the user for various paths, and adds the final game to the database.
*/
void Library::addGame()
{
    AddGameWizard* wiz = new AddGameWizard();
    wiz->show();
}

/** Recreate the list of games displayed in the main widget.
* Sort the list alphabetically by name
*/
void Library::refreshGames()
{
    for (int i = 0; i < gamesWidgets.size(); i++)
    {
        QWidget* widget = gamesWidgets[i];
        gamesLayout->removeWidget(widget);
        widget->deleteLater();
    }
    gamesWidgets.clear();

    QList<Game> gameList = Library::db.getGames();
    std::sort(gameList.begin(), gameList.end(), [&](const Game& g1, const Game& g2){return g1.gameName < g2.gameName; });
    int row = 0, col = 0;
    for (auto game : gameList)
    {
        QString lowerGameName = game.gameName.toLower();
        QString searchString = searchBox->text().trimmed();
        if (!searchString.isEmpty() && !lowerGameName.contains(searchString.toLower()))
        {
            continue;
        }

        GridGameWidget* gameWidget = new GridGameWidget(game.gameName, 999);
        gamesLayout->addWidget(gameWidget, row, col);
        connect(gameWidget, &GridGameWidget::clicked, [=] { launchGame(game.gameName); });
        gamesWidgets.append(gameWidget);

        if (col == 3)
        {
            row++;
        }
        col = (col < 3 ? col + 1 : 0);
    }
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $
Version:   $Revision: 7837 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkNavigationTool.h"
#include "mitkCommon.h"
#include "mitkTestingMacros.h"
#include "mitkDataNode.h"
#include "mitkTrackingTool.h"

#include <itkSpatialObject.h>

class mitkNavigationToolTestClass
  {
  public:

    static void TestInstantiation()
    {
    // let's create an object of our class
    mitk::NavigationTool::Pointer myNavigationTool = mitk::NavigationTool::New();
    MITK_TEST_CONDITION_REQUIRED(myNavigationTool.IsNotNull(),"Testing instantiation")
    }

    static void TestGetterAndSetter()
    {
    mitk::NavigationTool::Pointer myNavigationTool = mitk::NavigationTool::New();

    //initialize a few things
    mitk::DataNode::Pointer myNode = mitk::DataNode::New();
    itk::SpatialObject<3>::Pointer mySpatialObject = itk::SpatialObject<3>::New();

    //set everything
    myNavigationTool->SetType(mitk::NavigationTool::Instrument);
    myNavigationTool->SetIdentifier("Tool#15");
    myNavigationTool->SetDataNode(myNode);
    myNavigationTool->SetSpatialObject(mySpatialObject);
    //notice: cannot test Get/SetTrackingTool because this class cannot be instantiated alone
    myNavigationTool->SetCalibrationFile("Test.srom");
    myNavigationTool->SetSerialNumber("0815");
    myNavigationTool->SetTrackingDeviceType(mitk::NDIAurora);

    //test getter
    MITK_TEST_CONDITION(myNavigationTool->GetType()==mitk::NavigationTool::Instrument,"Testing getter and setter of type.");
    MITK_TEST_CONDITION(myNavigationTool->GetIdentifier()=="Tool#15","Testing getter and setter of identifier.");
    MITK_TEST_CONDITION(myNavigationTool->GetDataNode()==myNode,"Testing getter and setter of dataNode.");
    MITK_TEST_CONDITION(myNavigationTool->GetSpatialObject()==mySpatialObject,"Testing getter and setter of itk spatial object.");
    MITK_TEST_CONDITION(myNavigationTool->GetCalibrationFile()=="Test.srom","Testing getter and setter of calibration file.");
    MITK_TEST_CONDITION(myNavigationTool->GetSerialNumber()=="0815","Testing getter and setter of serial number.");
    MITK_TEST_CONDITION(myNavigationTool->GetTrackingDeviceType()==mitk::NDIAurora,"Testing getter and setter of tracking device type.");

    }

  };
/** This function is testing the TrackingVolume class. */
int mitkNavigationToolTest(int /* argc */, char* /*argv*/[])
{
  MITK_TEST_BEGIN("NavigationTool")

  mitkNavigationToolTestClass::TestInstantiation();
  mitkNavigationToolTestClass::TestGetterAndSetter();

  MITK_TEST_END()
}

<commit_msg>ENH (#3138): Added test for new methods GetToolName().<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date: 2008-02-25 17:27:17 +0100 (Mo, 25 Feb 2008) $
Version:   $Revision: 7837 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkNavigationTool.h"
#include "mitkCommon.h"
#include "mitkTestingMacros.h"
#include "mitkDataNode.h"
#include "mitkTrackingTool.h"

#include <itkSpatialObject.h>

class mitkNavigationToolTestClass
  {
  public:

    static void TestInstantiation()
    {
    // let's create an object of our class
    mitk::NavigationTool::Pointer myNavigationTool = mitk::NavigationTool::New();
    MITK_TEST_CONDITION_REQUIRED(myNavigationTool.IsNotNull(),"Testing instantiation")
    }

    static void TestGetterAndSetter()
    {
    mitk::NavigationTool::Pointer myNavigationTool = mitk::NavigationTool::New();

    //initialize a few things
    mitk::DataNode::Pointer myNode = mitk::DataNode::New();
    myNode->SetName("TestNodeName");
    itk::SpatialObject<3>::Pointer mySpatialObject = itk::SpatialObject<3>::New();

    //set everything
    myNavigationTool->SetType(mitk::NavigationTool::Instrument);
    myNavigationTool->SetIdentifier("Tool#15");
    myNavigationTool->SetDataNode(myNode);
    myNavigationTool->SetSpatialObject(mySpatialObject);
    //notice: cannot test Get/SetTrackingTool because this class cannot be instantiated alone
    myNavigationTool->SetCalibrationFile("Test.srom");
    myNavigationTool->SetSerialNumber("0815");
    myNavigationTool->SetTrackingDeviceType(mitk::NDIAurora);

    //test getter
    MITK_TEST_CONDITION(myNavigationTool->GetType()==mitk::NavigationTool::Instrument,"Testing getter and setter of type.");
    MITK_TEST_CONDITION(myNavigationTool->GetIdentifier()=="Tool#15","Testing getter and setter of identifier.");
    MITK_TEST_CONDITION(myNavigationTool->GetDataNode()==myNode,"Testing getter and setter of dataNode.");
    MITK_TEST_CONDITION(myNavigationTool->GetSpatialObject()==mySpatialObject,"Testing getter and setter of itk spatial object.");
    MITK_TEST_CONDITION(myNavigationTool->GetCalibrationFile()=="Test.srom","Testing getter and setter of calibration file.");
    MITK_TEST_CONDITION(myNavigationTool->GetSerialNumber()=="0815","Testing getter and setter of serial number.");
    MITK_TEST_CONDITION(myNavigationTool->GetTrackingDeviceType()==mitk::NDIAurora,"Testing getter and setter of tracking device type.");
    MITK_TEST_CONDITION(myNavigationTool->GetToolName()=="TestNodeName","Testing method GetToolName().");

    }

  };
/** This function is testing the TrackingVolume class. */
int mitkNavigationToolTest(int /* argc */, char* /*argv*/[])
{
  MITK_TEST_BEGIN("NavigationTool")

  mitkNavigationToolTestClass::TestInstantiation();
  mitkNavigationToolTestClass::TestGetterAndSetter();

  MITK_TEST_END()
}

<|endoftext|>


<commit_before>#include "VInputHandler.h"
#include <string.h>
#include <math.h>

VInputHandler::VInputHandler(sf::Window* window)
{
	this->window = window;
#ifdef USE_GAMEPAD_API
	GamepadInit();
#else
#endif
}

VInputHandler::~VInputHandler()
{
	buttonInputs.clear();
	axisInputs.clear();
	window = nullptr;

#ifdef USE_GAMEPAD_API
	GamepadShutdown();
#elif USE_SFML_JOYSTICK
	memset(JoystickID, NULL, sizeof(JoystickID));
#endif
}

void VInputHandler::SetButtonInput(const sf::String& name, int key, int gamepad, int mouse)
{
	if (buttonInputs.find(name) != buttonInputs.end())
	{
		if (buttonInputs[name].key == key &&
			buttonInputs[name].gamepad == gamepad &&
			buttonInputs[name].mouse == mouse)
		{
			return;
		}
	}

	ButtonInput button;
	button.key = (sf::Keyboard::Key)key;

#ifdef USE_GAMEPAD_API
	button.gamepad = (GAMEPAD_BUTTON)(gamepad);
#elif defined(USE_SFML_JOYSTICK)
	button.gamepad = (Button)gamepad;
	sf::Joystick::update();
#else
	if (gamepad > 0)
		button.gamepad = (sf::XInputDevice::XButton)((unsigned short)gamepad);
	else
		button.gamepad = (sf::XInputDevice::XButton)0;
#endif

	button.mouse = (sf::Mouse::Button)mouse;
	buttonInputs[name] = button;
}

void VInputHandler::SetAxisInput(const sf::String& name, int keyA, int keyB, int gamepad)
{
	if (axisInputs.find(name) != axisInputs.end())
	{
		if (axisInputs[name].keyA == keyA &&
			axisInputs[name].gamepad == gamepad &&
			axisInputs[name].keyB == keyB)
		{
			return;
		}
	}

	AxisInput axis;
	axis.keyA = (sf::Keyboard::Key)keyA;
	axis.keyB = (sf::Keyboard::Key)keyB;

#ifdef USE_GAMEPAD_API
	axis.gamepad = (XAxis)gamepad;
#elif defined(USE_SFML_JOYSTICK)
	axis.gamepad = (sf::Joystick::Axis)gamepad;
	sf::Joystick::update();
#else
	axis.gamepad = (sf::XInputDevice::XAxis)gamepad;
#endif

	memset(axis.lastValue, NULL, sizeof(axis.lastValue));
	memset(axis.value, NULL, sizeof(axis.value));

	axisInputs[name] = axis;
}

bool VInputHandler::GetButtonInput(const sf::String& name, ButtonInput& input)
{
	if (buttonInputs.find(name) != buttonInputs.end())
	{
		input = buttonInputs[name];
		return true;
	}

	return false;
}

bool VInputHandler::GetAxisInput(const sf::String& name, AxisInput& input)
{
	if (axisInputs.find(name) != axisInputs.end())
	{
		input = axisInputs[name];
		return true;
	}

	return false;
}

bool VInputHandler::IsGamepadActive()
{
	return isGamepadActive;
}

#ifdef USE_SFML_JOYSTICK
int VInputHandler::GetJoystickID(int ControllerIndex)
{
	if (ControllerIndex < 0 || ControllerIndex >= CONTROLLER_COUNT)
		return -1;

	return ControllerIndex;
}
void VInputHandler::SetDeadzone(float value)
{
	deadzone = value;
}
float VInputHandler::GetDeadzone()
{
	return deadzone;
}
#endif

bool VInputHandler::IsButtonPressed(const sf::String& name, int controller)
{
	if (buttonInputs.find(name) != buttonInputs.end())
	{
		return buttonInputs[name].pressed[controller];
	}

	return false;
}

bool VInputHandler::IsButtonDown(const sf::String& name, int controller)
{
	if (buttonInputs.find(name) != buttonInputs.end())
	{
		return buttonInputs[name].down[controller];
	}

	return false;
}

bool VInputHandler::IsButtonUp(const sf::String& name, int controller)
{
	if (buttonInputs.find(name) != buttonInputs.end())
	{
		return !IsButtonDown(name);
	}

	return false;
}

bool VInputHandler::IsButtonReleased(const sf::String& name, int controller)
{
	if (buttonInputs.find(name) != buttonInputs.end())
	{
		return buttonInputs[name].released[controller];
	}

	return false;
}

float VInputHandler::CurrentAxisValue(const sf::String& name, int controller)
{
	if (axisInputs.find(name) != axisInputs.end())
	{
		return axisInputs[name].value[controller];
	}

	return 0;
}

float VInputHandler::LastAxisValue(const sf::String& name, int controller)
{
	if (axisInputs.find(name) != axisInputs.end())
	{
		return axisInputs[name].lastValue[controller];
	}

	return 0;
}

float VInputHandler::ScrollWheelDelta()
{
	return scrollWheel;
}

void VInputHandler::ResetScrollWheel()
{
	scrollWheel = 0;
}

void VInputHandler::HandleEvents(const sf::Event& event)
{
	if (event.type == sf::Event::MouseWheelScrolled)
	{
		scrollWheel = event.mouseWheelScroll.delta;
	}
}

void VInputHandler::Update(float dt)
{
#ifdef USE_GAMEPAD_API
	GamepadUpdate();
#elif defined(USE_SFML_JOYSTICK)
	int count = 0;
	memset(JoystickID, NULL, sizeof(JoystickID));
	for (int i = 0; i < sf::Joystick::Count; i++)
	{
		if (count >= CONTROLLER_COUNT)
			break;

		if (sf::Joystick::isConnected(i))
		{
			JoystickID[count] = i + 1;
			count++;
		}
	}
#endif

	sf::Vector2i mousePosition = sf::Mouse::getPosition();

	for (int i = 0; i < CONTROLLER_COUNT; i++)
	{
		for (std::map<sf::String, ButtonInput>::iterator button = buttonInputs.begin(); button != buttonInputs.end(); ++button)
		{
			ButtonInput& b = button->second;

			b.pressed[i] = false;
			b.released[i] = false;

			bool mousePress = sf::Mouse::isButtonPressed(b.mouse) &&
				(mousePosition.x >= window->getPosition().x &&
					mousePosition.y >= window->getPosition().y &&
					mousePosition.x < (window->getPosition().x + (int)window->getSize().x) &&
					mousePosition.y < (window->getPosition().y + (int)window->getSize().y));

			if (sf::Keyboard::isKeyPressed(b.key) || mousePress
#ifdef USE_GAMEPAD_API
				|| (GamepadIsConnected((GAMEPAD_DEVICE)i) && GamepadButtonDown((GAMEPAD_DEVICE)i, b.gamepad))
#elif defined(USE_SFML_JOYSTICK)
				 || (JoystickID[i] > 0 && b.gamepad >= 0 && b.gamepad < sf::Joystick::getButtonCount(JoystickID[i] - 1) && sf::Joystick::isButtonPressed(JoystickID[i] - 1, b.gamepad))
#else
				|| (sf::XInputDevice::isConnected(i) && sf::XInputDevice::isButtonPressed(i, b.gamepad))
#endif
				)
			{
				if (!b.down[i])
					b.pressed[i] = true;
				b.down[i] = true;

				isGamepadActive = !(sf::Keyboard::isKeyPressed(b.key) || sf::Mouse::isButtonPressed(b.mouse));
			}
			else
			{
				if (b.down[i])
					b.released[i] = true;
				b.down[i] = false;
			}
		}

		for (std::map<sf::String, AxisInput>::iterator axis = axisInputs.begin(); axis != axisInputs.end(); ++axis)
		{
			AxisInput& a = axis->second;

			a.lastValue[i] = a.value[i];
			a.value[i] = 0;

			if (a.gamepad >= 0)
			{
#ifdef USE_GAMEPAD_API
				if (GamepadIsConnected((GAMEPAD_DEVICE)i))
				{
					float val1 = 0, val2 = 0;

					#ifdef WIN32
					const float TriggerMax = 255.0f;
					#else
					const float TriggerMax = 32768.0f;
					#endif

					switch (a.gamepad)
					{
					case PovX:
					{
						GamepadStickNormXY((GAMEPAD_DEVICE)i, STICK_LEFT, &val1, &val2);
						break;
					}
					case PovY:
					{
						GamepadStickNormXY((GAMEPAD_DEVICE)i, STICK_LEFT, &val2, &val1);
						val1 *= -1;
						break;
					}
					case Z:
					{
						GamepadStickNormXY((GAMEPAD_DEVICE)i, STICK_RIGHT, &val1, &val2);
						break;
					}
					case V:
					{
						GamepadStickNormXY((GAMEPAD_DEVICE)i, STICK_RIGHT, &val2, &val1);
						val1 *= -1;
						break;
					}
					case L:
					{
						val1 = GamepadTriggerValue((GAMEPAD_DEVICE)i, TRIGGER_LEFT) / TriggerMax;
						break;
					}
					case R:
					{
						val1 = GamepadTriggerValue((GAMEPAD_DEVICE)i, TRIGGER_RIGHT) / TriggerMax;
						break;
					}
					}

					val1 *= 100.0f;

					if (fabs(val1) > 0.0f)
					{
						a.value[i] = val1;
						isGamepadActive = true;
					}
					else
					{
						a.value[i] = 0;
					}
				}

#elif defined(USE_SFML_JOYSTICK)
				float axis = JoystickID[i] > 0 && a.gamepad >= 0 ? sf::Joystick::getAxisPosition(JoystickID[i] - 1, a.gamepad) : 0.0f;
				if (fabsf(axis) >= deadzone) //Deadzone
				{
					a.value[i] = axis;
					isGamepadActive = true;
				}
				else
				{
					a.value[i] = 0;
				}
#else
				float axis = sf::XInputDevice::isConnected(i) ? sf::XInputDevice::getAxisPosition(i, a.gamepad) : 0.0f;
				if ((int)axis != 0)
				{
					a.value[i] = axis;
					isGamepadActive = true;
				}
				else
				{
					a.value[i] = 0;
				}
#endif

				if (a.keyA >= 0)
				{
					if (sf::Keyboard::isKeyPressed(a.keyA))
					{
						a.value[i] = 100.0f;
						isGamepadActive = false;
					}
				}

				if (a.keyB >= 0)
				{
					if (sf::Keyboard::isKeyPressed(a.keyB))
					{
						a.value[i] = -100.0f;
						isGamepadActive = false;
					}
				}
			}
		}
	}

	if (mousePosition - lastMousePos != sf::Vector2i())
	{
		isGamepadActive = false;
	}

	lastMousePos = mousePosition;
}
<commit_msg>Replace Normalized input values with stick values to normalize afterwards.<commit_after>#include "VInputHandler.h"
#include <string.h>
#include <math.h>

VInputHandler::VInputHandler(sf::Window* window)
{
	this->window = window;
#ifdef USE_GAMEPAD_API
	GamepadInit();
#else
#endif
}

VInputHandler::~VInputHandler()
{
	buttonInputs.clear();
	axisInputs.clear();
	window = nullptr;

#ifdef USE_GAMEPAD_API
	GamepadShutdown();
#elif USE_SFML_JOYSTICK
	memset(JoystickID, NULL, sizeof(JoystickID));
#endif
}

void VInputHandler::SetButtonInput(const sf::String& name, int key, int gamepad, int mouse)
{
	if (buttonInputs.find(name) != buttonInputs.end())
	{
		if (buttonInputs[name].key == key &&
			buttonInputs[name].gamepad == gamepad &&
			buttonInputs[name].mouse == mouse)
		{
			return;
		}
	}

	ButtonInput button;
	button.key = (sf::Keyboard::Key)key;

#ifdef USE_GAMEPAD_API
	button.gamepad = (GAMEPAD_BUTTON)(gamepad);
#elif defined(USE_SFML_JOYSTICK)
	button.gamepad = (Button)gamepad;
	sf::Joystick::update();
#else
	if (gamepad > 0)
		button.gamepad = (sf::XInputDevice::XButton)((unsigned short)gamepad);
	else
		button.gamepad = (sf::XInputDevice::XButton)0;
#endif

	button.mouse = (sf::Mouse::Button)mouse;
	buttonInputs[name] = button;
}

void VInputHandler::SetAxisInput(const sf::String& name, int keyA, int keyB, int gamepad)
{
	if (axisInputs.find(name) != axisInputs.end())
	{
		if (axisInputs[name].keyA == keyA &&
			axisInputs[name].gamepad == gamepad &&
			axisInputs[name].keyB == keyB)
		{
			return;
		}
	}

	AxisInput axis;
	axis.keyA = (sf::Keyboard::Key)keyA;
	axis.keyB = (sf::Keyboard::Key)keyB;

#ifdef USE_GAMEPAD_API
	axis.gamepad = (XAxis)gamepad;
#elif defined(USE_SFML_JOYSTICK)
	axis.gamepad = (sf::Joystick::Axis)gamepad;
	sf::Joystick::update();
#else
	axis.gamepad = (sf::XInputDevice::XAxis)gamepad;
#endif

	memset(axis.lastValue, NULL, sizeof(axis.lastValue));
	memset(axis.value, NULL, sizeof(axis.value));

	axisInputs[name] = axis;
}

bool VInputHandler::GetButtonInput(const sf::String& name, ButtonInput& input)
{
	if (buttonInputs.find(name) != buttonInputs.end())
	{
		input = buttonInputs[name];
		return true;
	}

	return false;
}

bool VInputHandler::GetAxisInput(const sf::String& name, AxisInput& input)
{
	if (axisInputs.find(name) != axisInputs.end())
	{
		input = axisInputs[name];
		return true;
	}

	return false;
}

bool VInputHandler::IsGamepadActive()
{
	return isGamepadActive;
}

#ifdef USE_SFML_JOYSTICK
int VInputHandler::GetJoystickID(int ControllerIndex)
{
	if (ControllerIndex < 0 || ControllerIndex >= CONTROLLER_COUNT)
		return -1;

	return ControllerIndex;
}
void VInputHandler::SetDeadzone(float value)
{
	deadzone = value;
}
float VInputHandler::GetDeadzone()
{
	return deadzone;
}
#endif

bool VInputHandler::IsButtonPressed(const sf::String& name, int controller)
{
	if (buttonInputs.find(name) != buttonInputs.end())
	{
		return buttonInputs[name].pressed[controller];
	}

	return false;
}

bool VInputHandler::IsButtonDown(const sf::String& name, int controller)
{
	if (buttonInputs.find(name) != buttonInputs.end())
	{
		return buttonInputs[name].down[controller];
	}

	return false;
}

bool VInputHandler::IsButtonUp(const sf::String& name, int controller)
{
	if (buttonInputs.find(name) != buttonInputs.end())
	{
		return !IsButtonDown(name);
	}

	return false;
}

bool VInputHandler::IsButtonReleased(const sf::String& name, int controller)
{
	if (buttonInputs.find(name) != buttonInputs.end())
	{
		return buttonInputs[name].released[controller];
	}

	return false;
}

float VInputHandler::CurrentAxisValue(const sf::String& name, int controller)
{
	if (axisInputs.find(name) != axisInputs.end())
	{
		return axisInputs[name].value[controller];
	}

	return 0;
}

float VInputHandler::LastAxisValue(const sf::String& name, int controller)
{
	if (axisInputs.find(name) != axisInputs.end())
	{
		return axisInputs[name].lastValue[controller];
	}

	return 0;
}

float VInputHandler::ScrollWheelDelta()
{
	return scrollWheel;
}

void VInputHandler::ResetScrollWheel()
{
	scrollWheel = 0;
}

void VInputHandler::HandleEvents(const sf::Event& event)
{
	if (event.type == sf::Event::MouseWheelScrolled)
	{
		scrollWheel = event.mouseWheelScroll.delta;
	}
}

void VInputHandler::Update(float dt)
{
#ifdef USE_GAMEPAD_API
	GamepadUpdate();
#elif defined(USE_SFML_JOYSTICK)
	int count = 0;
	memset(JoystickID, NULL, sizeof(JoystickID));
	for (int i = 0; i < sf::Joystick::Count; i++)
	{
		if (count >= CONTROLLER_COUNT)
			break;

		if (sf::Joystick::isConnected(i))
		{
			JoystickID[count] = i + 1;
			count++;
		}
	}
#endif

	sf::Vector2i mousePosition = sf::Mouse::getPosition();

	for (int i = 0; i < CONTROLLER_COUNT; i++)
	{
		for (std::map<sf::String, ButtonInput>::iterator button = buttonInputs.begin(); button != buttonInputs.end(); ++button)
		{
			ButtonInput& b = button->second;

			b.pressed[i] = false;
			b.released[i] = false;

			bool mousePress = sf::Mouse::isButtonPressed(b.mouse) &&
				(mousePosition.x >= window->getPosition().x &&
					mousePosition.y >= window->getPosition().y &&
					mousePosition.x < (window->getPosition().x + (int)window->getSize().x) &&
					mousePosition.y < (window->getPosition().y + (int)window->getSize().y));

			if (sf::Keyboard::isKeyPressed(b.key) || mousePress
#ifdef USE_GAMEPAD_API
				|| (GamepadIsConnected((GAMEPAD_DEVICE)i) && GamepadButtonDown((GAMEPAD_DEVICE)i, b.gamepad))
#elif defined(USE_SFML_JOYSTICK)
				 || (JoystickID[i] > 0 && b.gamepad >= 0 && b.gamepad < sf::Joystick::getButtonCount(JoystickID[i] - 1) && sf::Joystick::isButtonPressed(JoystickID[i] - 1, b.gamepad))
#else
				|| (sf::XInputDevice::isConnected(i) && sf::XInputDevice::isButtonPressed(i, b.gamepad))
#endif
				)
			{
				if (!b.down[i])
					b.pressed[i] = true;
				b.down[i] = true;

				isGamepadActive = !(sf::Keyboard::isKeyPressed(b.key) || sf::Mouse::isButtonPressed(b.mouse));
			}
			else
			{
				if (b.down[i])
					b.released[i] = true;
				b.down[i] = false;
			}
		}

		for (std::map<sf::String, AxisInput>::iterator axis = axisInputs.begin(); axis != axisInputs.end(); ++axis)
		{
			AxisInput& a = axis->second;

			a.lastValue[i] = a.value[i];
			a.value[i] = 0;

			if (a.gamepad >= 0)
			{
#ifdef USE_GAMEPAD_API
				if (GamepadIsConnected((GAMEPAD_DEVICE)i))
				{
					int val1 = 0, val2 = 0;

					const float TriggerMax = 32768.0f;

					switch (a.gamepad)
					{
					case PovX:
					{
						GamepadStickXY((GAMEPAD_DEVICE)i, STICK_LEFT, &val1, &val2);
						break;
					}
					case PovY:
					{
						GamepadStickXY((GAMEPAD_DEVICE)i, STICK_LEFT, &val2, &val1);
						val1 *= -1;
						break;
					}
					case Z:
					{
						GamepadStickXY((GAMEPAD_DEVICE)i, STICK_RIGHT, &val1, &val2);
						break;
					}
					case V:
					{
						GamepadStickXY((GAMEPAD_DEVICE)i, STICK_RIGHT, &val2, &val1);
						val1 *= -1;
						break;
					}
					case L:
					{
						val1 = GamepadTriggerValue((GAMEPAD_DEVICE)i, TRIGGER_LEFT);
						break;
					}
					case R:
					{
						val1 = GamepadTriggerValue((GAMEPAD_DEVICE)i, TRIGGER_RIGHT);
						break;
					}
					}

					float val = val1 * (100.0f / TriggerMax);

					if (fabs(val) > 0.0f)
					{
						a.value[i] = val;
						isGamepadActive = true;
					}
					else
					{
						a.value[i] = 0;
					}
				}

#elif defined(USE_SFML_JOYSTICK)
				float axis = JoystickID[i] > 0 && a.gamepad >= 0 ? sf::Joystick::getAxisPosition(JoystickID[i] - 1, a.gamepad) : 0.0f;
				if (fabsf(axis) >= deadzone) //Deadzone
				{
					a.value[i] = axis;
					isGamepadActive = true;
				}
				else
				{
					a.value[i] = 0;
				}
#else
				float axis = sf::XInputDevice::isConnected(i) ? sf::XInputDevice::getAxisPosition(i, a.gamepad) : 0.0f;
				if ((int)axis != 0)
				{
					a.value[i] = axis;
					isGamepadActive = true;
				}
				else
				{
					a.value[i] = 0;
				}
#endif

				if (a.keyA >= 0)
				{
					if (sf::Keyboard::isKeyPressed(a.keyA))
					{
						a.value[i] = 100.0f;
						isGamepadActive = false;
					}
				}

				if (a.keyB >= 0)
				{
					if (sf::Keyboard::isKeyPressed(a.keyB))
					{
						a.value[i] = -100.0f;
						isGamepadActive = false;
					}
				}
			}
		}
	}

	if (mousePosition - lastMousePos != sf::Vector2i())
	{
		isGamepadActive = false;
	}

	lastMousePos = mousePosition;
}
<|endoftext|>


<commit_before>/* Copyright (c) 2017, EPL-Vizards
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the EPL-Vizards nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL EPL-Vizards BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*!
 * \file QwtBaseModel.cpp
 */

#include "QwtBaseModel.hpp"
#include "MainWindow.hpp"
#include "PlotCreator.hpp"

#include <QPointF>
#include <QtDebug>
#include <QMenu>
#include <QAction>

using namespace EPL_Viz;
using namespace EPL_DataCollect;
using namespace EPL_DataCollect::constants;
using namespace std;

QwtBaseModel::QwtBaseModel(MainWindow *win, QwtPlot *widget) : BaseModel(win, widget) {
  window = win;
  plot   = widget;

  widget->setContextMenuPolicy(Qt::CustomContextMenu);
  widget->setAxisAutoScale(QwtPlot::yLeft, true);
  connect(widget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(showContextMenu(const QPoint &)));

  reset();
}

void QwtBaseModel::init() {
  for (PlotCreator::PlotCreatorData data : registeredCurves) {
    createPlot(data.node, data.index, data.subIndex, data.csName);
  }
  registeredCurves.clear();
}

double QwtBaseModel::getViewportSize() {
  QwtScaleDiv div = plot->axisScaleDiv(QwtPlot::xTop);
  return div.upperBound() - div.lowerBound();
}

/**
 * @brief QwtBaseModel::replot Replots in the main Thread
 */
void QwtBaseModel::replot() {
  postToThread([&] { plot->replot(); }, plot);
}

void QwtBaseModel::update(ProtectedCycle &cycle) {
  (void)cycle;

  // Setting values in curves
  for (QPair<shared_ptr<QwtPlotCurve>, shared_ptr<plugins::TimeSeries>> pair : curves) {
    shared_ptr<QwtPlotCurve>        curve      = pair.first;
    shared_ptr<plugins::TimeSeries> timeSeries = pair.second;

    size_t oldDataCount = curve->dataSize();
    size_t newDataCount = timeSeries->tsData.size();
    qDebug() << "Updating BaseModel with timeseries data of the size " + QString::number(newDataCount) + "and " +
                      QString::number(oldDataCount) + " old values";
    if (oldDataCount == newDataCount)
      return;

    std::vector<double> xValues(newDataCount);
    for (size_t i = 0; i < newDataCount; ++i) {
      xValues[i] = static_cast<double>(i);
    }

    curve->setSamples(xValues.data(), timeSeries->tsData.data(), static_cast<int>(newDataCount));
    curve->attach(plot);
  }

  replot();
}

void QwtBaseModel::registerCurve(PlotCreator::PlotCreatorData data) { registeredCurves.append(data); }

/**
 * @brief QwtBaseModel::createPlot Slot for creating a plot with the given values
 * Wether the CycleStorage name is empty or not, decides if the indices or the string should be used.
 * Calls initTTS()
 * @param nodeID ID of the node
 * @param mainIndex Index of the OD Entry
 * @param subIndex subindex to be plotted
 * @param csName CycleStorage name, ignored if empty
 */
void QwtBaseModel::createPlot(uint8_t nodeID, uint16_t mainIndex, uint16_t subIndex, std::string csName) {
  if (subIndex > UINT8_MAX)
    subIndex = 0;

  auto              ptr = window->getCaptureInstance()->getCycleContainer()->pollCyclePTR();
  CycleStorageBase *cs;

  if (window->getCaptureInstance()->getState() != CaptureInstance::CIstate::RUNNING) {
    cs = window->getCaptureInstance()->getStartCycle()->getCycleStorage(EPL_DC_PLUGIN_TIME_SERIES_CSID);
  } else {
    cs = ptr->getCycleStorage(EPL_DC_PLUGIN_TIME_SERIES_CSID);
  }

  auto *tsp = dynamic_cast<plugins::CSTimeSeriesPtr *>(cs);

  shared_ptr<plugins::TimeSeries> timeSeries;
  if (csName.empty())
    timeSeries = make_shared<plugins::TimeSeries>(nodeID, mainIndex, subIndex);
  else
    timeSeries = make_shared<plugins::TimeSeries>(nodeID, csName);
  tsp->addTS(timeSeries);

  shared_ptr<QwtPlotCurve> curve = make_shared<QwtPlotCurve>();
  curve->setXAxis(QwtPlot::xTop);
  curve->setYAxis(QwtPlot::yLeft);
  QString title;
  if (csName.empty())
    title = "Node: " + QString::number(nodeID) + " Index: 0x" + QString::number(mainIndex, 16) + " SubIndex: 0x" + QString::number(subIndex, 16);
  else
    title = QString::fromStdString(csName);
  curve->setTitle(title);
  curve->attach(plot);

  curves.append(QPair<shared_ptr<QwtPlotCurve>, shared_ptr<plugins::TimeSeries>>(curve, timeSeries));
}

void QwtBaseModel::reset() {
  for (QPair<shared_ptr<QwtPlotCurve>, shared_ptr<plugins::TimeSeries>> pair : curves) {
    pair.first->detach();
  }

  curves.clear();
  registeredCurves.clear();

  maxXValue = 50;
  replot();
}

void QwtBaseModel::showContextMenu(const QPoint &point) {
  (void) point;
  QMenu menu(plot);

  QList<QAction *> actions;
  for (QPair<shared_ptr<QwtPlotCurve>, shared_ptr<plugins::TimeSeries>> pair : curves) {
    QAction *action = new QAction(this);

    action->setText(pair.first->title().text());

    actions.append(action);
  }

  for (PlotCreator::PlotCreatorData data : registeredCurves) {
    QAction *action = new QAction();

    QString title = QString::fromStdString(data.csName);
    if (title.isEmpty())
      title = "Node: " + QString::number(data.node) + " Index: 0x" + QString::number(data.index, 16) + " SubIndex: 0x" + QString::number(data.subIndex, 16);

    action->setText(title);
    action->setDisabled(true);

    actions.append(action);
  }

  if (actions.isEmpty())
    actions.append(new QAction("No Plot"));

  menu.addActions(actions);
  menu.exec();
  actions.clear();
}

<commit_msg>Fixed formatting<commit_after>/* Copyright (c) 2017, EPL-Vizards
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of the EPL-Vizards nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL EPL-Vizards BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
/*!
 * \file QwtBaseModel.cpp
 */

#include "QwtBaseModel.hpp"
#include "MainWindow.hpp"
#include "PlotCreator.hpp"

#include <QAction>
#include <QMenu>
#include <QPointF>
#include <QtDebug>

using namespace EPL_Viz;
using namespace EPL_DataCollect;
using namespace EPL_DataCollect::constants;
using namespace std;

QwtBaseModel::QwtBaseModel(MainWindow *win, QwtPlot *widget) : BaseModel(win, widget) {
  window = win;
  plot   = widget;

  widget->setContextMenuPolicy(Qt::CustomContextMenu);
  widget->setAxisAutoScale(QwtPlot::yLeft, true);
  connect(widget, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(showContextMenu(const QPoint &)));

  reset();
}

void QwtBaseModel::init() {
  for (PlotCreator::PlotCreatorData data : registeredCurves) {
    createPlot(data.node, data.index, data.subIndex, data.csName);
  }
  registeredCurves.clear();
}

double QwtBaseModel::getViewportSize() {
  QwtScaleDiv div = plot->axisScaleDiv(QwtPlot::xTop);
  return div.upperBound() - div.lowerBound();
}

/**
 * @brief QwtBaseModel::replot Replots in the main Thread
 */
void QwtBaseModel::replot() {
  postToThread([&] { plot->replot(); }, plot);
}

void QwtBaseModel::update(ProtectedCycle &cycle) {
  (void)cycle;

  // Setting values in curves
  for (QPair<shared_ptr<QwtPlotCurve>, shared_ptr<plugins::TimeSeries>> pair : curves) {
    shared_ptr<QwtPlotCurve>        curve      = pair.first;
    shared_ptr<plugins::TimeSeries> timeSeries = pair.second;

    size_t oldDataCount = curve->dataSize();
    size_t newDataCount = timeSeries->tsData.size();
    qDebug() << "Updating BaseModel with timeseries data of the size " + QString::number(newDataCount) + "and " +
                      QString::number(oldDataCount) + " old values";
    if (oldDataCount == newDataCount)
      return;

    std::vector<double> xValues(newDataCount);
    for (size_t i = 0; i < newDataCount; ++i) {
      xValues[i] = static_cast<double>(i);
    }

    curve->setSamples(xValues.data(), timeSeries->tsData.data(), static_cast<int>(newDataCount));
    curve->attach(plot);
  }

  replot();
}

void QwtBaseModel::registerCurve(PlotCreator::PlotCreatorData data) { registeredCurves.append(data); }

/**
 * @brief QwtBaseModel::createPlot Slot for creating a plot with the given values
 * Wether the CycleStorage name is empty or not, decides if the indices or the string should be used.
 * Calls initTTS()
 * @param nodeID ID of the node
 * @param mainIndex Index of the OD Entry
 * @param subIndex subindex to be plotted
 * @param csName CycleStorage name, ignored if empty
 */
void QwtBaseModel::createPlot(uint8_t nodeID, uint16_t mainIndex, uint16_t subIndex, std::string csName) {
  if (subIndex > UINT8_MAX)
    subIndex = 0;

  auto              ptr = window->getCaptureInstance()->getCycleContainer()->pollCyclePTR();
  CycleStorageBase *cs;

  if (window->getCaptureInstance()->getState() != CaptureInstance::CIstate::RUNNING) {
    cs = window->getCaptureInstance()->getStartCycle()->getCycleStorage(EPL_DC_PLUGIN_TIME_SERIES_CSID);
  } else {
    cs = ptr->getCycleStorage(EPL_DC_PLUGIN_TIME_SERIES_CSID);
  }

  auto *tsp = dynamic_cast<plugins::CSTimeSeriesPtr *>(cs);

  shared_ptr<plugins::TimeSeries> timeSeries;
  if (csName.empty())
    timeSeries = make_shared<plugins::TimeSeries>(nodeID, mainIndex, subIndex);
  else
    timeSeries = make_shared<plugins::TimeSeries>(nodeID, csName);
  tsp->addTS(timeSeries);

  shared_ptr<QwtPlotCurve> curve = make_shared<QwtPlotCurve>();
  curve->setXAxis(QwtPlot::xTop);
  curve->setYAxis(QwtPlot::yLeft);
  QString title;
  if (csName.empty())
    title = "Node: " + QString::number(nodeID) + " Index: 0x" + QString::number(mainIndex, 16) + " SubIndex: 0x" +
            QString::number(subIndex, 16);
  else
    title = QString::fromStdString(csName);
  curve->setTitle(title);
  curve->attach(plot);

  curves.append(QPair<shared_ptr<QwtPlotCurve>, shared_ptr<plugins::TimeSeries>>(curve, timeSeries));
}

void QwtBaseModel::reset() {
  for (QPair<shared_ptr<QwtPlotCurve>, shared_ptr<plugins::TimeSeries>> pair : curves) {
    pair.first->detach();
  }

  curves.clear();
  registeredCurves.clear();

  maxXValue = 50;
  replot();
}

void QwtBaseModel::showContextMenu(const QPoint &point) {
  (void)point;
  QMenu menu(plot);

  QList<QAction *> actions;
  for (QPair<shared_ptr<QwtPlotCurve>, shared_ptr<plugins::TimeSeries>> pair : curves) {
    QAction *action = new QAction(this);

    action->setText(pair.first->title().text());

    actions.append(action);
  }

  for (PlotCreator::PlotCreatorData data : registeredCurves) {
    QAction *action = new QAction();

    QString title = QString::fromStdString(data.csName);
    if (title.isEmpty())
      title = "Node: " + QString::number(data.node) + " Index: 0x" + QString::number(data.index, 16) + " SubIndex: 0x" +
              QString::number(data.subIndex, 16);

    action->setText(title);
    action->setDisabled(true);

    actions.append(action);
  }

  if (actions.isEmpty())
    actions.append(new QAction("No Plot"));

  menu.addActions(actions);
  menu.exec();
  actions.clear();
}
<|endoftext|>


<commit_before>/*********************************************************************************
- Contact:    Brigitte Cheynis     b.cheynis@ipnl.in2p3.fr
- Link:       http
- Raw data test file :
- Reference run number :
- Run Type:   STANDALONE
- DA Type:    LDC
- Number of events needed: 500
- Input Files:  argument list
- Output Files: local file  V0_Tuning2.dat
                FXS file    V0_Tuning2.dat
- Trigger types used: PHYSICS_EVENT
**********************************************************************************/

/**********************************************************************************
*                                                                                *
* VZERO Detector Algorithm used for tuning FEE parameters                         *
*                                                                                *
* This program reads data on the LDC                                              *
* It cumulates mean ADC responses ,  populates local  "./V0_Tuning2.dat"  file    *
* and exports it to the FES.                             *                        *                    *
* We have 128 channels instead of 64 as expected for V0 due to the two sets of    *
* charge integrators which are used by the FEE ...                                *
* The program reports about its processing progress.                              *
*                                                                                *
***********************************************************************************/

// DATE
#include "event.h"
#include "monitor.h"
#include "daqDA.h"

//AliRoot
#include <AliVZERORawStream.h>
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliDAQ.h>

// standard
#include <stdio.h>
#include <stdlib.h>

//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include <TFile.h>
#include <TH1F.h>
#include <TMath.h>

/* Main routine --- Arguments: list of DATE raw data files */

int main(int argc, char **argv) {

/* magic line from Cvetan */
  gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
                    "*",
                    "TStreamerInfo",
                    "RIO",
                    "TStreamerInfo()");
  int status;

  Float_t ADC_Mean[128];
  for(Int_t i=0; i<128; i++) {
      ADC_Mean[i] = 0.0;
  }

  /* log start of process */
  printf("VZERO DA program started - Tuning FEE parameters\n");

  /* check that we got some arguments = list of files */
  if (argc<2)   {
      printf("Wrong number of arguments\n");
      return -1;}

  /* open result file to be exported to FES */
  FILE *fp=NULL;
  fp=fopen("./V0_Tuning2.dat","a");
  if (fp==NULL) {
      printf("Failed to open result file\n");
      return -1;}

  /* open log file to inform user */
  FILE *flog=NULL;
  flog=fopen("./V00log.txt","a");
  if (flog==NULL) {
      printf("Failed to open log file\n");
      return -1;  }

  /* report progress */
  daqDA_progressReport(10);

  /* init counters on events */
  int nevents_physics=0;
  int nevents_total=0;

  /* read the n data files */
  for (int n=1; n<argc; n++) {

  /* read the data  */
    status=monitorSetDataSource( argv[n] );
  if (status!=0) {
      printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
      return -1; }

  /* report progress */
  daqDA_progressReport(10+50*n/argc);

  /* read the data file */
    for(;;) {
        struct eventHeaderStruct *event;
        eventTypeType eventT;

        /* get next event */
        status=monitorGetEventDynamic((void **)&event);
        if (status==MON_ERR_EOF) break; /* end of monitoring file has been reached */
        if (status!=0) {
            printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
            return -1; }

        /* retry if got no event */
        if (event==NULL) break;

        /* decode event */
        eventT=event->eventType;

        switch (event->eventType){

        case START_OF_RUN:
             break;

        case END_OF_RUN:
	     printf("End Of Run detected\n");
             break;

        case PHYSICS_EVENT:
             nevents_physics++;

	     AliRawReader *rawReader = new AliRawReaderDate((void*)event);

	     AliVZERORawStream* rawStream  = new AliVZERORawStream(rawReader);
	     rawStream->Next();
	     for(Int_t i=0; i<64; i++) {
	        if(!rawStream->GetIntegratorFlag(i,10))
		{
		    ADC_Mean[i]=ADC_Mean[i]+rawStream->GetADC(i);       // even integrator
		}
		else
		{
		    ADC_Mean[i+64]=ADC_Mean[i+64]+rawStream->GetADC(i); // odd integrator
		}
             }
             delete rawStream;
             rawStream = 0x0;
             delete rawReader;
             rawReader = 0x0;
        } // end of switch on event type

        nevents_total++;
        /* free resources */
        free(event);

    }    // end of loop over events
  }      // end of loop over data files

//________________________________________________________________________
//  Computes mean values, dumps them into the output text file

  for(Int_t i=0; i<128; i++) {
      ADC_Mean[i]=ADC_Mean[i]/nevents_physics;
      fprintf(fp," %d %f\n",i,ADC_Mean[i]);
      fprintf(flog," %d %f\n",i,ADC_Mean[i]);
  }
  fprintf(fp," End of current iteration \n");
//________________________________________________________________________

  /* write report */
  fprintf(flog,"Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total);
  printf("Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total);

  /* close result and log files */
  fclose(fp);
  fclose(flog);

  /* report progress */
  daqDA_progressReport(90);

  /* export result file to FES */
  status=daqDA_FES_storeFile("./V0_Tuning2.dat","V00da_results");
  if (status)    {
      printf("Failed to export file : %d\n",status);
      return -1; }

  /* report progress */
  daqDA_progressReport(100);

  return status;
}
<commit_msg>Iteration number stored into output file<commit_after>/*********************************************************************************
- Contact:    Brigitte Cheynis     b.cheynis@ipnl.in2p3.fr
- Link:       http
- Raw data test file :
- Reference run number :
- Run Type:   STANDALONE
- DA Type:    LDC
- Number of events needed: 500
- Input Files:  argument list
- Output Files: local file  V0_Tuning2.dat
                FXS file    V0_Tuning2.dat
- Trigger types used: PHYSICS_EVENT
**********************************************************************************/

/**********************************************************************************
*                                                                                *
* VZERO Detector Algorithm used for tuning FEE parameters                         *
*                                                                                *
* This program reads data on the LDC                                              *
* It cumulates mean ADC responses ,  populates local  "./V0_Tuning2.dat"  file    *
* and exports it to the FES.                             *                        *                    *
* We have 128 channels instead of 64 as expected for V0 due to the two sets of    *
* charge integrators which are used by the FEE ...                                *
* The program reports about its processing progress.                              *
*                                                                                *
***********************************************************************************/

// DATE
#include "event.h"
#include "monitor.h"
#include "daqDA.h"

//AliRoot
#include <AliVZERORawStream.h>
#include <AliRawReaderDate.h>
#include <AliRawReader.h>
#include <AliDAQ.h>

// standard
#include <stdio.h>
#include <stdlib.h>

//ROOT
#include "TROOT.h"
#include "TPluginManager.h"
#include <TFile.h>
#include <TH1F.h>
#include <TMath.h>

/* Main routine --- Arguments: list of DATE raw data files */

int main(int argc, char **argv) {

/* magic line from Cvetan */
  gROOT->GetPluginManager()->AddHandler("TVirtualStreamerInfo",
                    "*",
                    "TStreamerInfo",
                    "RIO",
                    "TStreamerInfo()");
  int status;

  Float_t ADC_Mean[128];
  for(Int_t i=0; i<128; i++) {
      ADC_Mean[i] = 0.0;
  }

  /* log start of process */
  printf("VZERO DA program started - Tuning FEE parameters\n");

  /* check that we got some arguments = list of files */
  if (argc<2)   {
      printf("Wrong number of arguments\n");
      return -1;}

  /* open result file to be exported to FES */
  FILE *fp=NULL;
  fp=fopen("./V0_Tuning2.dat","a");
  if (fp==NULL) {
      printf("Failed to open result file\n");
      return -1;}

  /* open log file to inform user */
  FILE *flog=NULL;
  flog=fopen("./V00log.txt","a");
  if (flog==NULL) {
      printf("Failed to open log file\n");
      return -1;  }

  /* report progress */
  daqDA_progressReport(10);

  /* init counters on events */
  int nevents_physics=0;
  int nevents_total=0;
  int iteration;
  sscanf(argv[1],"%d",&iteration);

  /* read the n data files */
  for (int n=2; n<argc; n++) {

  /* read the data  */
    status=monitorSetDataSource( argv[n] );
  if (status!=0) {
      printf("monitorSetDataSource() failed : %s\n",monitorDecodeError(status));
      return -1; }

  /* report progress */
  daqDA_progressReport(10+50*n/argc);

  /* read the data file */
    for(;;) {
        struct eventHeaderStruct *event;
        eventTypeType eventT;

        /* get next event */
        status=monitorGetEventDynamic((void **)&event);
        if (status==MON_ERR_EOF) break; /* end of monitoring file has been reached */
        if (status!=0) {
            printf("monitorGetEventDynamic() failed : %s\n",monitorDecodeError(status));
            return -1; }

        /* retry if got no event */
        if (event==NULL) break;

        /* decode event */
        eventT=event->eventType;

        switch (event->eventType){

        case START_OF_RUN:
             break;

        case END_OF_RUN:
	     printf("End Of Run detected\n");
             break;

        case PHYSICS_EVENT:
             nevents_physics++;

	     AliRawReader *rawReader = new AliRawReaderDate((void*)event);

	     AliVZERORawStream* rawStream  = new AliVZERORawStream(rawReader);
	     rawStream->Next();
	     for(Int_t i=0; i<64; i++) {
	        if(!rawStream->GetIntegratorFlag(i,10))
		{
		    ADC_Mean[i]=ADC_Mean[i]+rawStream->GetADC(i);       // even integrator
		}
		else
		{
		    ADC_Mean[i+64]=ADC_Mean[i+64]+rawStream->GetADC(i); // odd integrator
		}
             }
             delete rawStream;
             rawStream = 0x0;
             delete rawReader;
             rawReader = 0x0;
        } // end of switch on event type

        nevents_total++;
        /* free resources */
        free(event);

    }    // end of loop over events
  }      // end of loop over data files

//________________________________________________________________________
//  Computes mean values, dumps them into the output text file

  for(Int_t i=0; i<128; i++) {
      ADC_Mean[i]=ADC_Mean[i]/nevents_physics;
      fprintf(fp," %d %d %f\n",iteration,i,ADC_Mean[i]);
      fprintf(flog,"%d %d %f\n",iteration,i,ADC_Mean[i]);
  }

//________________________________________________________________________

  /* write report */
  fprintf(flog,"Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total);
  printf("Run #%s, received %d physics events out of %d\n",getenv("DATE_RUN_NUMBER"),nevents_physics,nevents_total);

  /* close result and log files */
  fclose(fp);
  fclose(flog);

  /* report progress */
  daqDA_progressReport(90);

  /* export result file to FES */
  status=daqDA_FES_storeFile("./V0_Tuning2.dat","V00da_results");
  if (status)    {
      printf("Failed to export file : %d\n",status);
      return -1; }

  /* report progress */
  daqDA_progressReport(100);

  return status;
}
<|endoftext|>