<commit_before>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/Collision/TriangleMeshTriangleMeshDcdContact.h"
#include "SurgSim/Collision/UnitTests/ContactCalculationTestsCommon.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/Timer.h"

using SurgSim::Math::MeshShape;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Vector3d;

namespace SurgSim
{
namespace Collision
{

TEST(TriangleMeshTriangleMeshContactCalculationPerformanceTests, IntersectionTest)
{

	auto runtime = std::make_shared<SurgSim::Framework::Runtime>("config.txt");
	auto meshA = std::make_shared<MeshShape>();
	meshA->load("MeshShapeData/stapler_collision.ply");

	auto meshB = std::make_shared<MeshShape>();
	meshB->load("MeshShapeData/wound_deformable.ply");

	std::shared_ptr<ShapeCollisionRepresentation> meshARep =
		std::make_shared<ShapeCollisionRepresentation>("Collision Mesh 0");
	meshARep->setShape(meshA);

	std::shared_ptr<ShapeCollisionRepresentation> meshBRep =
		std::make_shared<ShapeCollisionRepresentation>("Collision Mesh 1");
	meshBRep->setShape(meshB);

	TriangleMeshTriangleMeshDcdContact calcContact;
	std::shared_ptr<CollisionPair> pair = std::make_shared<CollisionPair>(meshARep, meshBRep);

	Framework::Timer timer;
	int loops = 100;
	size_t contacts = 0;
	for (int i = 0 ; i < loops; ++i)
	{
		pair->clearContacts();
		meshARep->getCollisions().unsafeGet().clear();
		meshBRep->getCollisions().unsafeGet().clear();
		RigidTransform3d pose =
			Math::makeRigidTransform(Math::makeRotationQuaternion(2.0 * M_PI * i / loops, Vector3d::UnitX().eval()),
			Vector3d(i, -1.5 * i, 0.0));
		meshARep->setLocalPose(pose);
		meshBRep->setLocalPose(pose);
		timer.beginFrame();
		calcContact.calculateContact(pair);
		timer.endFrame();
		contacts += pair->getContacts().size();
	}

	RecordProperty("ContactsPerLoop", boost::to_string(pair->getContacts().size()));
	RecordProperty("DurationPerLoop", boost::to_string(timer.getCumulativeTime() / loops));
	RecordProperty("Loops", boost::to_string(loops));
	RecordProperty("TotalContacts", boost::to_string(contacts));
	RecordProperty("TotalDuration", boost::to_string(timer.getCumulativeTime()));
}

}
}
<commit_msg>Mesh-mesh contact performance test uses same property names.<commit_after>// This file is a part of the OpenSurgSim project.
// Copyright 2013, SimQuest Solutions Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "SurgSim/Collision/TriangleMeshTriangleMeshDcdContact.h"
#include "SurgSim/Collision/UnitTests/ContactCalculationTestsCommon.h"
#include "SurgSim/Framework/Runtime.h"
#include "SurgSim/Framework/Timer.h"

using SurgSim::Math::MeshShape;
using SurgSim::Math::RigidTransform3d;
using SurgSim::Math::Vector3d;

namespace SurgSim
{
namespace Collision
{

TEST(TriangleMeshTriangleMeshContactCalculationPerformanceTests, IntersectionTest)
{

	auto runtime = std::make_shared<SurgSim::Framework::Runtime>("config.txt");
	auto meshA = std::make_shared<MeshShape>();
	meshA->load("MeshShapeData/stapler_collision.ply");

	auto meshB = std::make_shared<MeshShape>();
	meshB->load("MeshShapeData/wound_deformable.ply");

	std::shared_ptr<ShapeCollisionRepresentation> meshARep =
		std::make_shared<ShapeCollisionRepresentation>("Collision Mesh 0");
	meshARep->setShape(meshA);

	std::shared_ptr<ShapeCollisionRepresentation> meshBRep =
		std::make_shared<ShapeCollisionRepresentation>("Collision Mesh 1");
	meshBRep->setShape(meshB);

	TriangleMeshTriangleMeshDcdContact calcContact;
	std::shared_ptr<CollisionPair> pair = std::make_shared<CollisionPair>(meshARep, meshBRep);

	Framework::Timer timer;
	int loops = 100;
	size_t contacts = 0;
	for (int i = 0 ; i < loops; ++i)
	{
		pair->clearContacts();
		meshARep->getCollisions().unsafeGet().clear();
		meshBRep->getCollisions().unsafeGet().clear();
		RigidTransform3d pose =
			Math::makeRigidTransform(Math::makeRotationQuaternion(2.0 * M_PI * i / loops, Vector3d::UnitX().eval()),
			Vector3d(i, -1.5 * i, 0.0));
		meshARep->setLocalPose(pose);
		meshBRep->setLocalPose(pose);
		timer.beginFrame();
		calcContact.calculateContact(pair);
		timer.endFrame();
		contacts += pair->getContacts().size();
	}

	RecordProperty("FrameRate", boost::to_string(timer.getCumulativeTime() / loops));
	RecordProperty("Duration", boost::to_string(timer.getCumulativeTime()));
}

}
}
<|endoftext|>


<commit_before>/*
    ------------------------------------------------------------------

    This file is part of the Open Ephys GUI
    Copyright (C) 2013 Open Ephys

    ------------------------------------------------------------------

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
 */
 #include "EvntTrigAvgCanvas.h"

EvntTrigAvgCanvas::EvntTrigAvgCanvas(EvntTrigAvg* n) :
    processor(n)
{

    viewport = new Viewport();
    scrollBarThickness = viewport->getScrollBarThickness();

    clearHisto = new UtilityButton("CLEAR", Font("Default", 12, Font::plain));
    clearHisto->addListener(this);
    clearHisto->setRadius(3.0f);
    clearHisto->setBounds(80,5,65,15);
    clearHisto->setClickingTogglesState(false);
    addAndMakeVisible(clearHisto);
    setWantsKeyboardFocus(true);

    update();

    processor = n;
    display = new EvntTrigAvgDisplay(this, viewport, n);
    viewport->setScrollBarsShown(true, false,true);
    viewport->setViewedComponent(display,false);
    addAndMakeVisible(viewport);

    int yOffset = 50;
    scale = new Timescale(processor->getWindowSize(),processor->getSampleRate());
    viewport->setBounds(0,yOffset,getWidth()-scrollBarThickness,getHeight()-yOffset);
    display->setBounds(0,100,getWidth()-scrollBarThickness, getHeight()-2*yOffset);
    scale->setBounds(20, getHeight()-40, getWidth()-20-scrollBarThickness, 40);
    addAndMakeVisible(scale,false);

    }

EvntTrigAvgCanvas::~EvntTrigAvgCanvas()
{
    removeAllChildren();
}

void EvntTrigAvgCanvas::beginAnimation()
{
    std::cout << "EvntTrigAvgCanvas beginning animation." << std::endl;

    startCallbacks();
}

void EvntTrigAvgCanvas::endAnimation()
{
    std::cout << "EvntTrigAvgCanvas ending animation." << std::endl;

    stopCallbacks();
}

void EvntTrigAvgCanvas::update()
{
    repaint();
}

void EvntTrigAvgCanvas::refreshState()
{
    resized();
}

void EvntTrigAvgCanvas::resized()
{
    int xOffset= 40;
    int yOffset = 50;
    int drawWidth = getWidth()-20-getWidth()/4;
    viewport->setBounds(0,yOffset,getWidth()-scrollBarThickness,getHeight()-yOffset);
    display->setBounds(0,100,getWidth(), getHeight()-2*yOffset);
    //display->setBounds(0,100,getWidth()-5, getHeight()-40);
    scale->setBounds(20+30, getHeight()-40, getWidth()-20-getWidth()/4, 40);
    repaint();
}

void EvntTrigAvgCanvas::paint(Graphics& g)
{

    g.fillAll(Colours::darkgrey);
    int width=getWidth();
    int height=getHeight();
    int drawWidth = width-20-width/4;
    int xOffset= 20;
    g.setColour(Colours::snow);
    g.drawText("Electrode",5, 5, width/8, 20, juce::Justification::left);
    g.drawText("Trials: " + String(processor->getLastTTLCalculated()),(xOffset+drawWidth)/2-50,5,100,20,Justification::centred);
    g.drawText("Min.", width-180, 5, 60, 20, Justification::right);
    g.drawText("Max", width-120, 5, 60, 20, Justification::right);
    g.drawText("Mean", width-60, 5, 60, 20, Justification::right);
    removeChildComponent(scale);
    scale = new Timescale(processor->getWindowSize(),processor->getSampleRate());
    scale->setBounds(20, getHeight()-40, width-20, 40);
    addAndMakeVisible(scale,true);
}

void EvntTrigAvgCanvas::refresh()
{
    // called every 10 Hz
    display->refresh(); // dont know if this ever gets called

    repaint();
}

bool EvntTrigAvgCanvas::keyPressed(const KeyPress& key)
{
    return false;
}

void EvntTrigAvgCanvas::buttonClicked(Button* button)
{
    if (button == clearHisto){
        histoData.clear();
        minMaxMean.clear();
        processor->setParameter(4,0);
    }
     repaint();
}

//-----------------------------------------------------------------------------------------------------------------//

EvntTrigAvgDisplay::EvntTrigAvgDisplay(EvntTrigAvgCanvas* c, Viewport* v, EvntTrigAvg* p){
    processor=p;
    canvas=c;
    viewport=v;

    channelColours[0]=Colour(224,185,36);
    channelColours[1]=Colour(214,210,182);
    channelColours[2]=Colour(243,119,33);
    channelColours[3]=Colour(186,157,168);
    channelColours[4]=Colour(237,37,36);
    channelColours[5]=Colour(179,122,79);
    channelColours[6]=Colour(217,46,171);
    channelColours[7]=Colour(217, 139,196);
    channelColours[8]=Colour(101,31,255);
    channelColours[9]=Colour(141,111,181);
    channelColours[10]=Colour(48,117,255);
    channelColours[11]=Colour(184,198,224);
    channelColours[12]=Colour(116,227,156);
    channelColours[13]=Colour(150,158,155);
    channelColours[14]=Colour(82,173,0);
    channelColours[15]=Colour(125,99,32);
}

EvntTrigAvgDisplay::~EvntTrigAvgDisplay(){
    deleteAllChildren();
}

void EvntTrigAvgDisplay::visibleAreaChanged (const Rectangle<int>& newVisibleArea){

}

void EvntTrigAvgDisplay::viewedComponentChanged (Component* newComponent){

}

void EvntTrigAvgDisplay::resized()
{
    int width = getWidth();
    for(int i = 0 ; i < graphs.size() ; i++){
        graphs[i]->setBounds(20, 40*(i+1), width-20-width/4, 40);
        graphs[i]->resized();
    }
}

void EvntTrigAvgDisplay::paint(Graphics &g){
    g.fillAll(Colours::darkgrey);
    histoData = processor->getHistoData();
    minMaxMean = processor->getMinMaxMean();
    int width=getWidth();
    int height=getHeight();
    g.setColour(Colours::snow);
    int yFact = -2;
    int xOffset= 20;
    int drawWidth = width-20-width/4;
    int drawHeight = 40;
    std::vector<String> labels = processor->getElectrodeLabels();
    deleteAllChildren();
    graphs.clear();
    int graphCount = 0;
    for (int channelIt = 0 ; channelIt < histoData.size() ; channelIt++){
        for(int sortedId = 0 ; sortedId < histoData[channelIt].size() ; sortedId++){
            GraphUnit* graph = new GraphUnit(menus,channelColours[(channelIt+sizeof(channelColours))%(sizeof(channelColours))],labels[channelIt],minMaxMean[channelIt][sortedId],histoData[channelIt][sortedId]);
            graphs.add(graph);
            graph->setBounds(20, 40*(graphCount), width-20, 40);
            addAndMakeVisible(graph,false);
            graphCount += 1;
        }
    }

    repaint();
}

void EvntTrigAvgDisplay::refresh(){
    for (int i = 0 ; i < graphs.size() ; i++){
        graphs[i]->repaint();
    }
}

//--------------------------------------------------------------------
Timescale::Timescale(int wS, uint64 sR){
    windowSize = wS;
    sampleRate = sR;
}
Timescale::~Timescale(){

}

void Timescale::paint(Graphics& g){
    g.setColour(Colours::snow);
    // HG->setBounds(30,0,getWidth()-210,40);
    int histogramLen = getWidth()-210-10;
    int vertLineLen = 20;
    int textStart = vertLineLen+5;
    g.drawHorizontalLine(0, 30, histogramLen+30);

    g.drawVerticalLine(30, 0, vertLineLen);
    g.drawText(String(-1000.0*float(windowSize)/float(sampleRate)) + " ms", 0, textStart, 60, 10, Justification::centred);
    //g.drawText(<#const juce::String &text#>, <#int x#>, <#int y#>, <#int width#>, <#int height#>, <#juce::Justification justificationType#>)
    g.drawVerticalLine(histogramLen/4+30, 0, vertLineLen);
    g.drawText(String(-1000.0*float(windowSize)/2.0/float(sampleRate)) + " ms", histogramLen/4, textStart, 60, 10, Justification::centred);

    g.drawVerticalLine(histogramLen/2+30, 0, vertLineLen);
    g.drawText(" 0 ms",histogramLen/2, textStart, 60, 10, Justification::centred);

    g.drawVerticalLine(3*histogramLen/4+30, 0, vertLineLen);
    g.drawText(String(1000.0*float(windowSize)/2.0/float(sampleRate)) + " ms", 3*histogramLen/4, textStart, 60, 10, Justification::centred);

    g.drawVerticalLine(histogramLen+30, 0, vertLineLen);
    g.drawText(String(1000.0*float(windowSize)/float(sampleRate)) + " ms", histogramLen, textStart, 60, 10, Justification::centred);

}
void Timescale::resized(){

}

//--------------------------------------------------------------------

GraphUnit::GraphUnit(PopupMenu men, juce::Colour c, String n, std::vector<float> s, std::vector<uint64> f){
    color = c;
    LD = new LabelDisplay(c,n);
    LD->setBounds(0,0,30,40);
    addAndMakeVisible(LD,false);
    HG = new HistoGraph(men,c, s[1], f);
    HG->setBounds(30,0,getWidth()-210,40);
    addAndMakeVisible(HG,false);
    SD = new StatDisplay(c,s);
    SD->setBounds(getWidth()-180,0,180,40);
    addAndMakeVisible(SD,false);
}
GraphUnit::~GraphUnit(){
    deleteAllChildren();
}
void GraphUnit::paint(Graphics& g){
        //g.setOpacity(1);
}
void GraphUnit::resized(){
    LD->setBounds(0,0,30,40);
    SD->setBounds(getWidth()-180,0,180,40);
    HG->setBounds(30,0,getWidth()-210,40);
}

//----------------

LabelDisplay::LabelDisplay(juce::Colour c, String n){
    color = c;
    name = n;
}
LabelDisplay::~LabelDisplay(){

}
void LabelDisplay::paint(Graphics& g){
    g.setColour(color);
    g.drawText(name,0, 0, 30, 40, juce::Justification::left);
}
void LabelDisplay::resized(){

}

//----------------

HistoGraph::HistoGraph(PopupMenu men, juce::Colour c, int m, std::vector<uint64> f){
    //menu = &men;
    color = c;
    histoData = f;
    max = m;
    setMouseClickGrabsKeyboardFocus(true);
}

HistoGraph::~HistoGraph(){

}

void HistoGraph::paint(Graphics& g){
    g.setColour(Colours::snow);
    g.setOpacity(0.5);
    g.drawVerticalLine(getWidth()/2,5, getHeight());

    g.setColour(color);
    for (int i = 1 ; i < histoData.size() ; i++){
        if(max!=0)
            g.drawLine((i-1)*getWidth()/histoData.size(),getHeight()-(histoData.operator[](i-1)*getHeight()/max),(i)*getWidth()/histoData.size(),getHeight()-(histoData.operator[](i)*getHeight()/max));
        else
            g.drawLine((i-1)*getWidth()/histoData.size(),getHeight()-(histoData.operator[](i-1)*getHeight()),(i)*getWidth()/histoData.size(),getHeight()-(histoData.operator[](i)*getHeight()));
    }
}

void HistoGraph::resized(){
    repaint();
}

void HistoGraph::select(){

}

void HistoGraph::deselect(){

}

void HistoGraph::clear(){

}

void HistoGraph::mouseMove(const MouseEvent &event){
    int posX = event.getMouseDownX();
    if(histoData.size()>0){
         int valueY = histoData[float(posX)/float(getWidth())*float(histoData.size())];
        menu.clear();
        menu.addItem(1, "Bin: " + String(int(float(posX)/float(getWidth())*float(histoData.size()))+1)+ " Counts: " + String(valueY),false);
        menu.showAt(this);

    }
}
//----------------

StatDisplay::StatDisplay(juce::Colour c, std::vector<float> s){
    color = c;
    stats = s;
}

StatDisplay::~StatDisplay(){

}

void StatDisplay::paint(Graphics& g){
    g.setColour(color);
    g.drawText(String(stats[0]),0, 0, 60, 40, juce::Justification::right);
    g.drawText(String(stats[1]),60, 0, 60, 40, juce::Justification::right);
    g.drawText(String(stats[2]),120, 0, 60, 40, juce::Justification::right);
    }

void StatDisplay::resized(){

}

<commit_msg>batter about to die to saving anything that might have changed<commit_after>/*
    ------------------------------------------------------------------

    This file is part of the Open Ephys GUI
    Copyright (C) 2013 Open Ephys

    ------------------------------------------------------------------

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

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

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
 */
 #include "EvntTrigAvgCanvas.h"

EvntTrigAvgCanvas::EvntTrigAvgCanvas(EvntTrigAvg* n) :
    processor(n)
{

    viewport = new Viewport();
    scrollBarThickness = viewport->getScrollBarThickness();

    clearHisto = new UtilityButton("CLEAR", Font("Default", 12, Font::plain));
    clearHisto->addListener(this);
    clearHisto->setRadius(3.0f);
    clearHisto->setBounds(80,5,65,15);
    clearHisto->setClickingTogglesState(false);
    addAndMakeVisible(clearHisto);
    setWantsKeyboardFocus(true);

    update();

    processor = n;
    display = new EvntTrigAvgDisplay(this, viewport, n);
    viewport->setScrollBarsShown(true, false,true);
    viewport->setViewedComponent(display,false);
    addAndMakeVisible(viewport);

    int yOffset = 50;
    scale = new Timescale(processor->getWindowSize(),processor->getSampleRate());
    viewport->setBounds(0,yOffset,getWidth(),getHeight()-yOffset);
    display->setBounds(0,100,getWidth()-scrollBarThickness, getHeight()-2*yOffset);
    scale->setBounds(20, getHeight()-40, getWidth()-20-scrollBarThickness, 40);
    addAndMakeVisible(scale,false);

    }

EvntTrigAvgCanvas::~EvntTrigAvgCanvas()
{
    removeAllChildren();
}

void EvntTrigAvgCanvas::beginAnimation()
{
    std::cout << "EvntTrigAvgCanvas beginning animation." << std::endl;

    startCallbacks();
}

void EvntTrigAvgCanvas::endAnimation()
{
    std::cout << "EvntTrigAvgCanvas ending animation." << std::endl;

    stopCallbacks();
}

void EvntTrigAvgCanvas::update()
{
    repaint();
}

void EvntTrigAvgCanvas::refreshState()
{
    resized();
}

void EvntTrigAvgCanvas::resized()
{
    int xOffset= 40;
    int yOffset = 50;
    int drawWidth = getWidth()-20-getWidth()/4;
    viewport->setBounds(0,yOffset,getWidth()-scrollBarThickness,getHeight()-yOffset);
    display->setBounds(0,100,getWidth(), getHeight()-2*yOffset);
    //display->setBounds(0,100,getWidth()-5, getHeight()-40);
    scale->setBounds(20+30, getHeight()-40, getWidth()-20-getWidth()/4, 40);
    repaint();
}

void EvntTrigAvgCanvas::paint(Graphics& g)
{

    g.fillAll(Colours::darkgrey);
    int width=getWidth();
    int height=getHeight();
    int drawWidth = width-20-width/4;
    int xOffset= 20;
    g.setColour(Colours::snow);
    g.drawText("Electrode",5, 5, width/8, 20, juce::Justification::left);
    g.drawText("Trials: " + String(processor->getLastTTLCalculated()),(xOffset+drawWidth)/2-50,5,100,20,Justification::centred);
    g.drawText("Min.", width-180, 5, 60, 20, Justification::right);
    g.drawText("Max", width-120, 5, 60, 20, Justification::right);
    g.drawText("Mean", width-60, 5, 60, 20, Justification::right);
    removeChildComponent(scale);
    scale = new Timescale(processor->getWindowSize(),processor->getSampleRate());
    scale->setBounds(20, getHeight()-40, width-20, 40);
    addAndMakeVisible(scale,true);
}

void EvntTrigAvgCanvas::refresh()
{
    // called every 10 Hz
    display->refresh(); // dont know if this ever gets called

    repaint();
}

bool EvntTrigAvgCanvas::keyPressed(const KeyPress& key)
{
    return false;
}

void EvntTrigAvgCanvas::buttonClicked(Button* button)
{
    if (button == clearHisto){
        histoData.clear();
        minMaxMean.clear();
        processor->setParameter(4,0);
    }
     repaint();
}

//-----------------------------------------------------------------------------------------------------------------//

EvntTrigAvgDisplay::EvntTrigAvgDisplay(EvntTrigAvgCanvas* c, Viewport* v, EvntTrigAvg* p){
    processor=p;
    canvas=c;
    viewport=v;

    channelColours[0]=Colour(224,185,36);
    channelColours[1]=Colour(214,210,182);
    channelColours[2]=Colour(243,119,33);
    channelColours[3]=Colour(186,157,168);
    channelColours[4]=Colour(237,37,36);
    channelColours[5]=Colour(179,122,79);
    channelColours[6]=Colour(217,46,171);
    channelColours[7]=Colour(217, 139,196);
    channelColours[8]=Colour(101,31,255);
    channelColours[9]=Colour(141,111,181);
    channelColours[10]=Colour(48,117,255);
    channelColours[11]=Colour(184,198,224);
    channelColours[12]=Colour(116,227,156);
    channelColours[13]=Colour(150,158,155);
    channelColours[14]=Colour(82,173,0);
    channelColours[15]=Colour(125,99,32);
}

EvntTrigAvgDisplay::~EvntTrigAvgDisplay(){
    deleteAllChildren();
}

void EvntTrigAvgDisplay::visibleAreaChanged (const Rectangle<int>& newVisibleArea){

}

void EvntTrigAvgDisplay::viewedComponentChanged (Component* newComponent){

}

void EvntTrigAvgDisplay::resized()
{
    int width = getWidth();
    for(int i = 0 ; i < graphs.size() ; i++){
        graphs[i]->setBounds(20, 40*(i+1), width-20-width/4, 40);
        graphs[i]->resized();
    }
}

void EvntTrigAvgDisplay::paint(Graphics &g){
    g.fillAll(Colours::darkgrey);
    histoData = processor->getHistoData();
    minMaxMean = processor->getMinMaxMean();
    int width=getWidth();
    int height=getHeight();
    g.setColour(Colours::snow);
    int yFact = -2;
    int xOffset= 20;
    int drawWidth = width-20-width/4;
    int drawHeight = 40;
    std::vector<String> labels = processor->getElectrodeLabels();
    deleteAllChildren();
    graphs.clear();
    int graphCount = 0;
    for (int channelIt = 0 ; channelIt < histoData.size() ; channelIt++){
        for(int sortedId = 0 ; sortedId < histoData[channelIt].size() ; sortedId++){
            GraphUnit* graph = new GraphUnit(menus,channelColours[(channelIt+sizeof(channelColours))%(sizeof(channelColours))],labels[channelIt],minMaxMean[channelIt][sortedId],histoData[channelIt][sortedId]);
            graphs.add(graph);
            graph->setBounds(20, 40*(graphCount), width-20, 40);
            addAndMakeVisible(graph,false);
            graphCount += 1;
        }
    }

    repaint();
}

void EvntTrigAvgDisplay::refresh(){
    for (int i = 0 ; i < graphs.size() ; i++){
        graphs[i]->repaint();
    }
}

//--------------------------------------------------------------------
Timescale::Timescale(int wS, uint64 sR){
    windowSize = wS;
    sampleRate = sR;
}
Timescale::~Timescale(){

}

void Timescale::paint(Graphics& g){
    g.setColour(Colours::snow);
    // HG->setBounds(30,0,getWidth()-210,40);
    int histogramLen = getWidth()-210-10;
    int vertLineLen = 20;
    int textStart = vertLineLen+5;
    g.drawHorizontalLine(0, 30, histogramLen+30);

    g.drawVerticalLine(30, 0, vertLineLen);
    g.drawText(String(-1000.0*float(windowSize)/float(sampleRate)) + " ms", 0, textStart, 60, 10, Justification::centred);
    //g.drawText(<#const juce::String &text#>, <#int x#>, <#int y#>, <#int width#>, <#int height#>, <#juce::Justification justificationType#>)
    g.drawVerticalLine(histogramLen/4+30, 0, vertLineLen);
    g.drawText(String(-1000.0*float(windowSize)/2.0/float(sampleRate)) + " ms", histogramLen/4, textStart, 60, 10, Justification::centred);

    g.drawVerticalLine(histogramLen/2+30, 0, vertLineLen);
    g.drawText(" 0 ms",histogramLen/2, textStart, 60, 10, Justification::centred);

    g.drawVerticalLine(3*histogramLen/4+30, 0, vertLineLen);
    g.drawText(String(1000.0*float(windowSize)/2.0/float(sampleRate)) + " ms", 3*histogramLen/4, textStart, 60, 10, Justification::centred);

    g.drawVerticalLine(histogramLen+30, 0, vertLineLen);
    g.drawText(String(1000.0*float(windowSize)/float(sampleRate)) + " ms", histogramLen, textStart, 60, 10, Justification::centred);

}
void Timescale::resized(){

}

//--------------------------------------------------------------------

GraphUnit::GraphUnit(PopupMenu men, juce::Colour c, String n, std::vector<float> s, std::vector<uint64> f){
    color = c;
    LD = new LabelDisplay(c,n);
    LD->setBounds(0,0,30,40);
    addAndMakeVisible(LD,false);
    HG = new HistoGraph(men,c, s[1], f);
    HG->setBounds(30,0,getWidth()-210,40);
    addAndMakeVisible(HG,false);
    SD = new StatDisplay(c,s);
    SD->setBounds(getWidth()-180,0,180,40);
    addAndMakeVisible(SD,false);
}
GraphUnit::~GraphUnit(){
    deleteAllChildren();
}
void GraphUnit::paint(Graphics& g){
        //g.setOpacity(1);
}
void GraphUnit::resized(){
    LD->setBounds(0,0,30,40);
    SD->setBounds(getWidth()-180,0,180,40);
    HG->setBounds(30,0,getWidth()-210,40);
}

//----------------

LabelDisplay::LabelDisplay(juce::Colour c, String n){
    color = c;
    name = n;
}
LabelDisplay::~LabelDisplay(){

}
void LabelDisplay::paint(Graphics& g){
    g.setColour(color);
    g.drawText(name,0, 0, 30, 40, juce::Justification::left);
}
void LabelDisplay::resized(){

}

//----------------

HistoGraph::HistoGraph(PopupMenu men, juce::Colour c, int m, std::vector<uint64> f){
    //menu = &men;
    color = c;
    histoData = f;
    max = m;
    setMouseClickGrabsKeyboardFocus(true);
}

HistoGraph::~HistoGraph(){

}

void HistoGraph::paint(Graphics& g){
    g.setColour(Colours::snow);
    g.setOpacity(0.5);
    g.drawVerticalLine(getWidth()/2,5, getHeight());

    g.setColour(color);
    for (int i = 1 ; i < histoData.size() ; i++){
        if(max!=0)
            g.drawLine((i-1)*getWidth()/histoData.size(),getHeight()-(histoData.operator[](i-1)*getHeight()/max),(i)*getWidth()/histoData.size(),getHeight()-(histoData.operator[](i)*getHeight()/max));
        else
            g.drawLine((i-1)*getWidth()/histoData.size(),getHeight()-(histoData.operator[](i-1)*getHeight()),(i)*getWidth()/histoData.size(),getHeight()-(histoData.operator[](i)*getHeight()));
    }
}

void HistoGraph::resized(){
    repaint();
}

void HistoGraph::select(){

}

void HistoGraph::deselect(){

}

void HistoGraph::clear(){

}

void HistoGraph::mouseMove(const MouseEvent &event){
    int posX = event.getMouseDownX();
    if(histoData.size()>0){
         int valueY = histoData[float(posX)/float(getWidth())*float(histoData.size())];
        menu.clear();
        menu.addItem(1, "Bin: " + String(int(float(posX)/float(getWidth())*float(histoData.size()))+1)+ " Counts: " + String(valueY),false);
        menu.showAt(this);

    }
}
//----------------

StatDisplay::StatDisplay(juce::Colour c, std::vector<float> s){
    color = c;
    stats = s;
}

StatDisplay::~StatDisplay(){

}

void StatDisplay::paint(Graphics& g){
    g.setColour(color);
    g.drawText(String(stats[0]),0, 0, 60, 40, juce::Justification::right);
    g.drawText(String(stats[1]),60, 0, 60, 40, juce::Justification::right);
    g.drawText(String(stats[2]),120, 0, 60, 40, juce::Justification::right);
    }

void StatDisplay::resized(){

}

<|endoftext|>


<commit_before>/*###################################################
  ##################Cic-Cac-Coe######################
  ######## All rights reserved to SAFAD(C) ##########
  ###########Please read the LICENSE file############
  ###################################################*/

#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>

using namespace std;

//This is our board, 0 => empty, 1 => X, 2 => O
vector<char> originalBoard;
//the game is running or not ? 1 yes , 0 no
int status = 0;
//turns 1 = player1, 2 = player2 OR CPU
char turn = 'X';
//to define the character we put in the column
char block;
//the user input
int selection;
//AI vs Human
int opponent;

int checkGame(vector<char> board);
void run();
//show the board
void ShowBoard() {
    for(int i=0; i<7; i+=3) {
        cout <<  originalBoard[i] <<" | "<< originalBoard[i+1] << "| " << originalBoard[i+2]  << endl;
    }
}

//tell them spike, tell them its a draw !!
void show_draw(){
	cout << "Nothing to see here Peeps, its a Draw" << endl;
}
//show winner !
void show_winner(){
	cout << "Winner is Player " << turn << " congratulations !!" << endl;
}

//check who won !
bool check_winner(vector<char> board){

    for(int i=0; i<7; i+=3) {
        if((board[i] == 'X' && board[i+1] == 'X' && board[i+2] == 'X') || (board[i] == 'O' && board[i+1] == 'O' && board[i+2] == 'O')){
            return true;
        }
    }

    for(int i=0; i<3; i++) {
        if((board[i] == 'X' && board[i+3] == 'X' && board[i+6] == 'X') || (board[i] == 'O' && board[i+3] == 'O' && board[i+6] == 'O')){
            return true;
        }
    }

    for(int i=0; i<3; i+=2) {
        if((board[i] == 'X' && board[4] == 'X' && board[8-i] == 'X') || (board[i] == 'O' && board[4] == 'O' && board[8-i] == 'O')){
            return true;
        }
    }

    return false;
}

bool check_draw(vector<char> board){
    if (std::count(board.begin(), board.end(), 'E') < 0)
    {
        //there still are no more moves
        //now lets see if someone one
        if (!check_winner(board)) {
            return true;
        }
    }

	return false;

}

//validates the user input
bool validate_selection(int selection){
	//first we check if it is out of range
	if (selection > 8 || selection < 0)
	{
		return false;
	}
	if(originalBoard[selection] == 'X' || originalBoard[selection] == 'O'){
		return false;
	}
	else {
		return true;
	}
}

//function to switch from player one to two and vice versa
void switch_turns(){
	turn = (turn == 'X') ? 'O' : 'X';
	run();
}

void check_status(vector<char> board){
	int gameStatus = checkGame(board);
	//before we switch turns, we check if the user won or not
	if(gameStatus == 0){
		switch_turns();

	}
	//what if the game is a Draw ?
	else if(gameStatus == 2){
		show_draw();
		status = 0;
	}
	else if(gameStatus == 1){
		//winnnnnn
		show_winner();
		status = 0;
	}
}

vector<int> getAllPossibleMoves(vector<char> board){
	vector<int> spaces;
	for (int i = 0; i < 9; ++i)
	{
		if (board[i] == 'E')
		{
			//this is the chosen one
			spaces.push_back(i);
		}
	}
	return spaces;
}

//we use this function to check the game status, is it won, or draw
//int unfinished = 0, won = 1, draw = 2;

int checkGame(vector<char> board){
	if(check_winner(board)){
		return 1;
	}
	//what if the game is a Draw ?
	else if(check_draw(board)){
		return 2;

	}
	return 0;
}

int getScore(vector<char> board, char turn){
	int bestScore = 0,
		iterations = 0,
		MAXWIN = 100,
		penalty = -5;
	//here, we read all the possible moves, and choose the best based on the score
	//score, MAXWIN = 100, DRAW = 0, MAXLOSE = -5
	//The MAXWIN score is acheived by doing the least of iterations
	//MAXLOSE score is achieved by doing the most of iterations, this means the computer, if he is going to lose, choose the longest path
	//How to calculate score: MAXWIN += -5*(iterations); MAXLOSE += 5*(iterations);
	//first we get all the possible moves
	vector<int> moves = getAllPossibleMoves(board);
	//now we loop through every possibility
	for(std::vector<int>::size_type i = 0; i != moves.size(); i++)
	{
		//okay so for this we clone the board, add our move
		vector<char> newBoard(board);
		//then we add a move
		newBoard[moves[i]] = turn;

		//now we check if the game is won or a draw
		if (checkGame(newBoard) == 1){
			//this move, wins the game, but who won?
			//if the AI wins : calculate the score, if it is better, save it as best score
			//if the opponent wins : we calculate the lose score, compare it if it is better, then save it..
			int score;
			if (turn == 'O')
			{
				//its me mittens!
				score =  MAXWIN + penalty*iterations;
			}else{
				//its the human being...
				score = -MAXWIN + penalty*iterations;

			}
			bestScore = (bestScore < score) ? score : bestScore;
		}else if (checkGame(newBoard) == 2){
			//its a draw, we see if the bestScore is a losing score, we rather draw than lose..
			bestScore = (bestScore < 0) ? 0 : bestScore;
		}else{
			//the game is unfinished
			++iterations;
			//now we create a new board, and get its best score..
			vector<char> clonedBoard(newBoard);
			char newTurn = (turn == 'X') ? 'O' : 'X';
			int score = getScore(clonedBoard,newTurn);

			bestScore = (bestScore < score) ? score : bestScore;
		}

	}
	return bestScore;
}
bool opponentMove(vector<char> board){
	bool win = false;
	vector<int> opponentMoves = getAllPossibleMoves(board);
	for(std::vector<int>::size_type i = 0; i != opponentMoves.size(); i++) {
		vector<char> newBoard(originalBoard);
		newBoard[opponentMoves[i]] = 'X';
		if (checkGame(newBoard) == 1)
		{
			win = true;
			break;
		}
	}
	return win;
}
int nextMove(){
	//first we see, if the game has just begun
	//first we generate a list of all possible moves
	//then we loop over it over each choice, if the game can be lost on the next human move
	//priority = 0 if draw, 1 if lose, 2 if win;
	int bestScore = 0,
		bestPriority,
		bestMove = 0;

	vector<int> moves = getAllPossibleMoves(originalBoard);
	int size = moves.size();

	if (size == 8)
	{
		int random = rand() % moves[7] + moves[0];
		return moves[random];

	}
	//now we see what the opponent would pick..
	if (opponentMove(originalBoard))
	{
		/* code */
	}
	for(std::vector<int>::size_type i = 0; i != size; i++) {
	    vector<char> newBoard(originalBoard);
		newBoard[moves[i]] = 'O';
		//now we check whether the move wins us or not
		int priority = checkGame(newBoard);
		if (priority > bestPriority && priority != 0)
		{
			bestPriority = priority;
			bestMove = moves[i];
		}
		else if (priority == 0)
		{
			//the game is unfinished, if true it means he can win
			if (!opponentMove(newBoard) && priority > bestPriority)
			{
				bestPriority = priority;
				bestMove = moves[i];
			}
		}
	}
	return bestMove;
}
void AI(){
	//cout << "Calculating..." << endl;
	int next = nextMove();
	//now we use it on screen
	if(validate_selection(next)){
		originalBoard[next] = 'O';
		check_status(originalBoard);
	}
	else{
		AI();
	}
}

void player(){
	cout << "Player " << turn << " Please enter a valid number (0-8) :" <<endl;
	cin >> selection;
	if(validate_selection(selection)){
		originalBoard[selection] = turn;
		check_status(originalBoard);
	}else{
		//his choice is invalid
		cout << "invalid move" << endl;
		player();
	}
}

//function to show the board
void run(){
	ShowBoard();
	//Artificial Inteligence :)
	if(opponent == 2 && turn == 'O'){
		AI();
	}
	else{
		player();
	}

}

int main(){
	//we first populate the board with dummy strings
	char dummy[9] = {'E','E','E','E','E','E','E','E','E'};

	for(int index=0;index<9; ++index)
	{
		originalBoard.push_back(dummy[index]);
	}

	if(status == 0){
		cout << "Play VS :" << endl;
		cout << "1. Human" << endl;
		cout << "2. AI (CPU)" << endl;
		cin >> opponent;
		status = 1;
	}
	run();
}

<commit_msg>Few optimisations here and there, especially on the board logic<commit_after>/*###################################################
  ##################Cic-Cac-Coe######################
  ######## All rights reserved to SAFAD(C) ##########
  ###########Please read the LICENSE file############
  ###################################################*/

#include <iostream>
#include <cstdlib>
#include <vector>
#include <algorithm>

using namespace std;

//This is our board, 0 => empty, 1 => X, 2 => O
vector<int> originalBoard;
//the game is running or not ? 1 yes , 0 no
int status = 0;
//turns 1 = player1, 2 = player2 OR CPU
char turn = 1;
//to define the character we put in the column
char block;
//the user input
int selection;
//AI vs Human
int opponent;

int checkGame(vector<int> board);
void run();
//show the board
char ReplaceBlocks(int blockId){
	switch(blockId) {
        case 1:
            return 'X'; //it is the first player..
        case 0:
            return ' '; //an empty block
        case 2:
            return 'O'; //second player here..
    }
    return ' ';

}
void DrawBoard() {
    for(int i=0; i<7; i+=3) {
        cout << " " <<  ReplaceBlocks(originalBoard[i]) <<" | "<< ReplaceBlocks(originalBoard[i+1]) << " | " << ReplaceBlocks(originalBoard[i+2])  << endl;
        if (i != 6)
        {
        	cout << "---+---+---" <<endl;
        }
    }
}

//tell them spike, tell them its a draw !!
void show_draw(){
	cout << "Nothing to see here Peeps, its a Draw" << endl;
}
//show winner !
void show_winner(){
	cout << "Winner is Player " << turn << " congratulations !!" << endl;
}

//check who won !
bool check_winner(vector<int> board){

    for(int i=0; i<7; i+=3) {
        if((board[i] == 2 && board[i+1] == 2 && board[i+2] == 2) || (board[i] == 1 && board[i+1] == 1 && board[i+2] == 1)){
            return true;
        }
    }

    for(int i=0; i<3; i++) {
        if((board[i] == 2 && board[i+3] == 2 && board[i+6] == 2) || (board[i] == 1 && board[i+3] == 1 && board[i+6] == 1)){
            return true;
        }
    }

    for(int i=0; i<3; i+=2) {
        if((board[i] == 2 && board[4] == 2 && board[8-i] == 2) || (board[i] == 1 && board[4] == 1 && board[8-i] == 1)){
            return true;
        }
    }

    return false;
}

bool check_draw(vector<int> board){
    if (std::count(board.begin(), board.end(), '0') < 0)
    {
        //there still are no more moves
        //now lets see if someone one
        if (!check_winner(board)) {
            return true;
        }
    }

	return false;

}

//validates the user input
bool validate_selection(int selection){
	//first we check if it is out of range
	if (selection > 8 || selection < 0)
	{
		return false;
	}
	if(originalBoard[selection] == 1 || originalBoard[selection] == 2){
		return false;
	}
	else {
		return true;
	}
}

//function to switch from player one to two and vice versa
void switch_turns(){
	turn = (turn == 1) ? 2 : 1;
	run();
}

void check_status(vector<int> board){
	int gameStatus = checkGame(board);
	//before we switch turns, we check if the user won or not
	if(gameStatus == 0){
		switch_turns();

	}
	//what if the game is a Draw ?
	else if(gameStatus == 2){
		show_draw();
		status = 0;
	}
	else if(gameStatus == 1){
		//winnnnnn
		show_winner();
		status = 0;
	}
}

vector<int> getAllPossibleMoves(vector<int> board){
	vector<int> spaces;
	for (int i = 0; i < 9; ++i)
	{
		if (board[i] == '0')
		{
			//this is the chosen one
			spaces.push_back(i);
		}
	}
	return spaces;
}

//we use this function to check the game status, is it won, or draw
//int unfinished = 0, won = 1, draw = 2;

int checkGame(vector<int> board){
	if(check_winner(board)){
		return 1;
	}
	//what if the game is a Draw ?
	else if(check_draw(board)){
		return 2;

	}
	return 0;
}

int getScore(vector<int> board, char turn){
	int bestScore = 0,
		iterations = 0,
		MAXWIN = 100,
		penalty = -5;
	//here, we read all the possible moves, and choose the best based on the score
	//score, MAXWIN = 100, DRAW = 0, MAXLOSE = -5
	//The MAXWIN score is acheived by doing the least of iterations
	//MAXLOSE score is achieved by doing the most of iterations, this means the computer, if he is going to lose, choose the longest path
	//How to calculate score: MAXWIN += -5*(iterations); MAXLOSE += 5*(iterations);
	//first we get all the possible moves
	vector<int> moves = getAllPossibleMoves(board);
	//now we loop through every possibility
	for(std::vector<int>::size_type i = 0; i != moves.size(); i++)
	{
		//okay so for this we clone the board, add our move
		vector<int> newBoard(board);
		//then we add a move
		newBoard[moves[i]] = turn;

		//now we check if the game is won or a draw
		if (checkGame(newBoard) == 1){
			//this move, wins the game, but who won?
			//if the AI wins : calculate the score, if it is better, save it as best score
			//if the opponent wins : we calculate the lose score, compare it if it is better, then save it..
			int score;
			if (turn == 2)
			{
				//its me mittens!
				score =  MAXWIN + penalty*iterations;
			}else{
				//its the human being...
				score = -MAXWIN + penalty*iterations;

			}
			bestScore = (bestScore < score) ? score : bestScore;
		}else if (checkGame(newBoard) == 2){
			//its a draw, we see if the bestScore is a losing score, we rather draw than lose..
			bestScore = (bestScore < 0) ? 0 : bestScore;
		}else{
			//the game is unfinished
			++iterations;
			//now we create a new board, and get its best score..
			vector<int> clonedBoard(newBoard);
			char newTurn = (turn == 1) ? 2 : 1;
			int score = getScore(clonedBoard,newTurn);

			bestScore = (bestScore < score) ? score : bestScore;
		}

	}
	return bestScore;
}
bool opponentMove(vector<int> board){
	bool win = false;
	vector<int> opponentMoves = getAllPossibleMoves(board);
	for(std::vector<int>::size_type i = 0; i != opponentMoves.size(); i++) {
		vector<int> newBoard(originalBoard);
		newBoard[opponentMoves[i]] = 1;
		if (checkGame(newBoard) == 1)
		{
			win = true;
			break;
		}
	}
	return win;
}
int nextMove(){
	//first we see, if the game has just begun
	//first we generate a list of all possible moves
	//then we loop over it over each choice, if the game can be lost on the next human move
	//priority = 0 if draw, 1 if lose, 2 if win;
	int bestScore = 0,
		bestPriority,
		bestMove = 0;

	vector<int> moves = getAllPossibleMoves(originalBoard);
	int size = moves.size();

	if (size == 8)
	{
		int random = rand() % moves[7] + moves[0];
		return moves[random];

	}
	//now we see what the opponent would pick..
	if (opponentMove(originalBoard))
	{
		/* code */
	}
	for(std::vector<int>::size_type i = 0; i != size; i++) {
	    vector<int> newBoard(originalBoard);
		newBoard[moves[i]] = 2;
		//now we check whether the move wins us or not
		int priority = checkGame(newBoard);
		if (priority > bestPriority && priority != 0)
		{
			bestPriority = priority;
			bestMove = moves[i];
		}
		else if (priority == 0)
		{
			//the game is unfinished, if true it means he can win
			if (!opponentMove(newBoard) && priority > bestPriority)
			{
				bestPriority = priority;
				bestMove = moves[i];
			}
		}
	}
	return bestMove;
}
void AI(){
	//cout << "Calculating..." << endl;
	int next = nextMove();
	//now we use it on screen
	if(validate_selection(next)){
		originalBoard[next] = 2;
		check_status(originalBoard);
	}
	else{
		AI();
	}
}

void player(){
	cout << "Player " << turn << " Please enter a valid number (0-8) :" <<endl;
	cin >> selection;
	if(validate_selection(selection)){
		originalBoard[selection] = turn;
		check_status(originalBoard);
	}else{
		//his choice is invalid
		cout << "invalid move" << endl;
		player();
	}
}

//function to show the board
void run(){
	DrawBoard();
	//Artificial Inteligence :)
	if(opponent == 2 && turn == 2){
		AI();
	}
	else{
		player();
	}

}

int main(){
	//we first populate the board with dummy strings
	char dummy[9] = {'0','0','0','0','0','0','0','0','0'};

	for(int index=0;index<9; ++index)
	{
		originalBoard.push_back(dummy[index]);
	}

	if(status == 0){
		cout << "Play VS :" << endl;
		cout << "1. Human" << endl;
		cout << "2. AI (CPU)" << endl;
		cin >> opponent;
		status = 1;
	}
	run();
}

<|endoftext|>


<commit_before>#include "DisplayDashboardView.h"
#include <QDebug>

namespace
{
    const double RED_SLOPE = -1;
    const int RED_INITIAL = 220;
    const double GREEN_SLOPE = 1.7;
    const int GREEN_INITIAL = 10;
    const int BLUE_INITIAL = 20;
    const QString DEFAULT_STYLESHEET = "QProgressBar:horizontal {\
            border: 1px solid white;\
            border-radius: 7px;\
            background: black;\
            }\
            QProgressBar::chunk:horizontal{\
            border-radius: 7px;\
            background: ";
}

DisplayDashboardView::DisplayDashboardView(AuxBmsPresenter& auxBmsPresenter,
        BatteryPresenter& batteryPresenter,
        BatteryFaultsPresenter& batteryFaultsPresenter,
        DriverControlsPresenter& driverControlsPresenter,
        KeyMotorPresenter& keyMotorPresenter,
        LightsPresenter& lightsPresenter,
        MpptPresenter& mpptPresenter,
        MotorDetailsPresenter& motorDetailsPresenter,
        MotorFaultsPresenter& motorFaultsPresenter,
        I_DisplayDashboardUI& ui,
        MotorFaultList& motorZeroFaultsList,
        MotorFaultList& motorOneFaultsList,
        BatteryFaultList& batteryFaultsList)
    : auxBmsPresenter_(auxBmsPresenter)
    , batteryPresenter_(batteryPresenter)
    , batteryFaultsPresenter_(batteryFaultsPresenter)
    , driverControlsPresenter_(driverControlsPresenter)
    , keyMotorPresenter_(keyMotorPresenter)
    , lightsPresenter_(lightsPresenter)
    , mpptPresenter_(mpptPresenter)
    , motorDetailsPresenter_(motorDetailsPresenter)
    , motorFaultsPresenter_(motorFaultsPresenter)
    , ui_(ui)
    , motorZeroFaultsList_(motorZeroFaultsList)
    , motorOneFaultsList_(motorOneFaultsList)
    , batteryFaultsList_(batteryFaultsList)
{
    connectAuxBms(auxBmsPresenter_);
    connectBattery(batteryPresenter_);
    connectBatteryFaults(batteryFaultsPresenter_);
    connectDriverControls(driverControlsPresenter_);
    connectKeyMotor(keyMotorPresenter_);
    connectLights(lightsPresenter_);
    connectMppt(mpptPresenter_);
    connectMotorDetails(motorDetailsPresenter_);
    connectMotorFaults(motorFaultsPresenter_);
    //ui_.showMaximized();
    ui_.show();
}
DisplayDashboardView::~DisplayDashboardView()
{}

void DisplayDashboardView::connectAuxBms(AuxBmsPresenter& auxBmsPresenter)
{
    connect(&auxBmsPresenter, SIGNAL(prechargeStateReceived(QString)),
            this, SLOT(prechargeStateReceived(QString)));
}

void DisplayDashboardView::connectBattery(BatteryPresenter& batteryPresenter)
{
    // TODO update to new battery data (depends on what should be shown in UI)
    connect(&batteryPresenter, SIGNAL(aliveReceived(bool)),
            this, SLOT(aliveReceived(bool)));
    connect(&batteryPresenter, SIGNAL(packNetPowerReceived(double)),
            this, SLOT(packNetPowerReceived(double)));
    connect(&batteryPresenter, SIGNAL(packStateOfChargeReceived(double)),
            this, SLOT(packStateOfChargeReceived(double)));
    connect(&batteryPresenter, SIGNAL(highTemperatureReceived(int)),
            this, SLOT(highTemperatureReceived(int)));
    connect(&batteryPresenter, SIGNAL(lowCellVoltageReceived(int)),
            this, SLOT(lowCellVoltageReceived(int)));
    connect(&batteryPresenter, SIGNAL(averageTemperatureReceived(int)),
            this, SLOT(averageTemperatureReceived(int)));
    connect(&batteryPresenter, SIGNAL(averageCellVoltageReceived(int)),
            this, SLOT(averageCellVoltageReceived(int)));
}

void DisplayDashboardView::connectBatteryFaults(BatteryFaultsPresenter& batteryFaultsPresenter)
{
    connect(&batteryFaultsPresenter, SIGNAL(errorFlagsReceived(BatteryErrorFlags)),
            this, SLOT(errorFlagsReceived(BatteryErrorFlags)));
    connect(&batteryFaultsPresenter, SIGNAL(limitFlagsReceived(BatteryLimitFlags)),
            this, SLOT(limitFlagsReceived(BatteryLimitFlags)));
}

void DisplayDashboardView::connectDriverControls(DriverControlsPresenter& driverControlsPresenter)
{
    connect(&driverControlsPresenter, SIGNAL(resetReceived(bool)),
            this, SLOT(resetReceived(bool)));
}

void DisplayDashboardView::connectKeyMotor(KeyMotorPresenter& keyMotorPresenter)
{
    connect(&keyMotorPresenter, SIGNAL(motorSetPowerReceived(double)),
            this, SLOT(motorSetPowerReceived(double)));
    connect(&keyMotorPresenter, SIGNAL(motorSetCurrentReceived(double)),
            this, SLOT(motorSetCurrentReceived(double)));
    connect(&keyMotorPresenter, SIGNAL(motorActualSpeedReceived(double)),
            this, SLOT(motorActualSpeedReceived(double)));
    connect(&keyMotorPresenter, SIGNAL(motorBusVoltageReceived(double)),
            this, SLOT(motorBusVoltageReceived(double)));
    connect(&keyMotorPresenter, SIGNAL(motorBusCurrentReceived(double)),
            this, SLOT(motorBusCurrentReceived(double)));
}

void DisplayDashboardView::connectLights(LightsPresenter& lightsPresenter)
{
    connect(&lightsPresenter, SIGNAL(lowBeamsReceived(bool)),
            this, SLOT(lowBeamsReceived(bool)));
    connect(&lightsPresenter, SIGNAL(highBeamsReceived(bool)),
            this, SLOT(highBeamsReceived(bool)));
    connect(&lightsPresenter, SIGNAL(leftSignalReceived(bool)),
            this, SLOT(leftSignalReceived(bool)));
    connect(&lightsPresenter, SIGNAL(rightSignalReceived(bool)),
            this, SLOT(rightSignalReceived(bool)));
    connect(&lightsPresenter, SIGNAL(lightAliveReceived(bool)),
            this, SLOT(lightAliveReceived(bool)));
}

void DisplayDashboardView::connectMppt(MpptPresenter& mpptPresenter)
{
    connect(&mpptPresenter, SIGNAL(mpptReceived(int, Mppt)),
            this, SLOT(mpptReceived(int, Mppt)));
    connect(&mpptPresenter, SIGNAL(mpptPowerReceived(double)),
            this, SLOT(mpptPowerReceived(double)));
}

void DisplayDashboardView::connectMotorDetails(MotorDetailsPresenter& motorDetailsPresenter)
{
}

void DisplayDashboardView::connectMotorFaults(MotorFaultsPresenter& motorFaultsPresenter)
{
    connect(&motorFaultsPresenter, SIGNAL(motorZeroErrorFlagsReceived(ErrorFlags)),
            this, SLOT(motorZeroErrorFlagsReceived(ErrorFlags)));
    connect(&motorFaultsPresenter, SIGNAL(motorZeroLimitFlagsReceived(LimitFlags)),
            this, SLOT(motorZeroLimitFlagsReceived(LimitFlags)));
    connect(&motorFaultsPresenter, SIGNAL(motorOneErrorFlagsReceived(ErrorFlags)),
            this, SLOT(motorOneErrorFlagsReceived(ErrorFlags)));
    connect(&motorFaultsPresenter, SIGNAL(motorOneLimitFlagsReceived(LimitFlags)),
            this, SLOT(motorOneLimitFlagsReceived(LimitFlags)));
}

void DisplayDashboardView::updateFaultLabel(QLabel & dashboardLabel, FaultLabel faultLabel)
{
    if (faultLabel.priority() >= 0)
    {
        dashboardLabel.setStyleSheet("font: 12pt \"Burlingame Pro\";\n color:" + faultLabel.color().name() + ";");
        dashboardLabel.setText(faultLabel.text());
    }
    else
    {
        dashboardLabel.setText("");
    }
}

void DisplayDashboardView::aliveReceived(bool)
{
}
void DisplayDashboardView::prechargeStateReceived(QString prechargeState)
{
    ui_.prechargeStateLabel().setText(prechargeState);
}

void DisplayDashboardView::packNetPowerReceived(double netPower)
{
    ui_.netPowerLabel().setText(QString::number(netPower, 'f', 2));
}

/*
 * TODO UI has to be updated w.r.t. the changes in the protocol
 */
void DisplayDashboardView::packStateOfChargeReceived(double packSocPercentage)
{
    ui_.stateOfChargeCapacityWidget().setValue(packSocPercentage);

    // The rgb values for the progressbar are calculated with the intention of displaying a colour closer to red
    // for low values and a colour closer to green for higher values. These are calculated using linear equations
    // with a slope and intercept.

    // Default colour
    int red = RED_INITIAL;
    int green = GREEN_INITIAL;
    int blue = BLUE_INITIAL;

    // Calculated color
    red += int(RED_SLOPE * packSocPercentage);
    green += int(GREEN_SLOPE * packSocPercentage);

    QString r = QString::number(red);
    QString g = QString::number(green);
    QString b = QString::number(blue);

    QString rgb = QString("rgb(%1,%2,%3);").arg(r, g, b);

    ui_.stateOfChargeCapacityWidget().setStyleSheet(DEFAULT_STYLESHEET + rgb + "}");
}
void DisplayDashboardView::highTemperatureReceived(int maxCellTemp)
{
    ui_.maxCellTemperatureLabel().setNum(maxCellTemp);
}
void DisplayDashboardView::lowCellVoltageReceived(int lowestCellVoltage)
{
    ui_.lowestCellVoltageLabel().setNum(lowestCellVoltage);
}
void DisplayDashboardView::averageTemperatureReceived(int averageCellTemp)
{
    ui_.avgCellTemperatureLabel().setNum(averageCellTemp);
}
void DisplayDashboardView::averageCellVoltageReceived(int averageVoltage)
{
    ui_.avgCellVoltageLabel().setNum(averageVoltage);
}
void DisplayDashboardView::errorFlagsReceived(BatteryErrorFlags batteryErrorFlags)
{
    batteryFaultsList_.updateErrors(batteryErrorFlags);
    updateFaultLabel(ui_.batteryFaultsLabel(), batteryFaultsList_.getHighestActivePriorityLabel());
}
void DisplayDashboardView::limitFlagsReceived(BatteryLimitFlags batteryLimitFlags)
{
    batteryFaultsList_.updateLimits(batteryLimitFlags);
    updateFaultLabel(ui_.batteryFaultsLabel(), batteryFaultsList_.getHighestActivePriorityLabel());
}

void DisplayDashboardView::resetReceived(bool reset)
{
    if (reset)
    {
        ui_.motorResetButtonWidget().setStyleSheet("background: url(:/Resources/MotorResetButton.png)");
    }
    else
    {
        ui_.motorResetButtonWidget().setStyleSheet("");
    }
}
void DisplayDashboardView::motorSetPowerReceived(double setPower)
{
    ui_.motorPowerLabel().setText(QString::number(setPower, 'f', 2));
}
void DisplayDashboardView::motorSetCurrentReceived(double setCurrent)
{
    ui_.setCurrentLabel().setText(QString::number(setCurrent, 'f', 3));
}
void DisplayDashboardView::motorActualSpeedReceived(double actualSpeed)
{
    ui_.actualSpeedLabel().setText(QString::number(actualSpeed, 'f', 1));
}
void DisplayDashboardView::motorBusVoltageReceived(double busVoltage)
{
    ui_.busVoltageLabel().setText(QString::number(busVoltage, 'f', 2));
}
void DisplayDashboardView::motorBusCurrentReceived(double busCurrent)
{
    ui_.busCurrentLabel().setText(QString::number(busCurrent, 'f', 3));
}

void DisplayDashboardView::lowBeamsReceived(bool lowBeams)
{
    if (lowBeams)
    {
        ui_.lowHeadlightIndicatorWidget().setStyleSheet("background: url(:/Resources/LowHeadlightIndicator.png)");
    }
    else
    {
        ui_.lowHeadlightIndicatorWidget().setStyleSheet("");
    }
}
void DisplayDashboardView::highBeamsReceived(bool highBeams)
{
    if (highBeams)
    {
        ui_.highHeadlightIndicatorWidget().setStyleSheet("background: url(:/Resources/HighHeadlightIndicator.png)");
    }
    else
    {
        ui_.highHeadlightIndicatorWidget().setStyleSheet("");
    }
}
void DisplayDashboardView::leftSignalReceived(bool leftSignal)
{
    if (leftSignal)
    {
        ui_.leftTurnSignalWidget().setStyleSheet("background: url(:/Resources/TurnSignalLeft.png);");
    }
    else
    {
        ui_.leftTurnSignalWidget().setStyleSheet("");
    }
}
void DisplayDashboardView::rightSignalReceived(bool rightSignal)
{
    if (rightSignal)
    {
        ui_.rightTurnSignalWidget().setStyleSheet("background: url(:/Resources/TurnSignalRight.png);");
    }
    else
    {
        ui_.rightTurnSignalWidget().setStyleSheet("");
    }
}
void DisplayDashboardView::lightAliveReceived(bool)
{
    // TODO
}
void DisplayDashboardView::mpptReceived(int i, Mppt mppt)
{
    if (i == 0)
    {
        ui_.array0CurrentLabel().setNum(mppt.arrayCurrent());
        ui_.array0VoltageLabel().setNum(mppt.arrayVoltage());
        mpptZeroPower_ = mppt.arrayCurrent() * mppt.arrayVoltage();
    }
    else if (i == 1)
    {
        ui_.array1CurrentLabel().setNum(mppt.arrayCurrent());
        ui_.array1VoltageLabel().setNum(mppt.arrayVoltage());
        mpptOnePower_ = mppt.arrayCurrent() * mppt.arrayVoltage();
    }
    else if (i == 2)
    {
        ui_.array2CurrentLabel().setNum(mppt.arrayCurrent());
        ui_.array2VoltageLabel().setNum(mppt.arrayVoltage());
        mpptTwoPower_ = mppt.arrayCurrent() * mppt.arrayVoltage();
    }

    mpptPowerReceived(mpptZeroPower_ + mpptOnePower_ + mpptTwoPower_);
}

void DisplayDashboardView::mpptPowerReceived(double mpptPower)
{
    ui_.powerInLabel().setText(QString::number(mpptPower, 'f', 0));
    ui_.powerOutLabel().setNum(ui_.netPowerLabel().text().toDouble() - mpptPower);
}

void DisplayDashboardView::motorZeroErrorFlagsReceived(ErrorFlags motorZeroErrorFlags)
{
    motorZeroFaultsList_.updateErrors(motorZeroErrorFlags);
    updateFaultLabel(ui_.motorZeroFaultsLabel(), motorZeroFaultsList_.getHighestActivePriorityLabel());
}
void DisplayDashboardView::motorZeroLimitFlagsReceived(LimitFlags motorZeroLimitFlags)
{
    motorZeroFaultsList_.updateLimits(motorZeroLimitFlags);
    updateFaultLabel(ui_.motorZeroFaultsLabel(), motorZeroFaultsList_.getHighestActivePriorityLabel());
}
void DisplayDashboardView::motorOneErrorFlagsReceived(ErrorFlags motorOneErrorFlags)
{
    motorOneFaultsList_.updateErrors(motorOneErrorFlags);
    updateFaultLabel(ui_.motorOneFaultsLabel(), motorOneFaultsList_.getHighestActivePriorityLabel());
}
void DisplayDashboardView::motorOneLimitFlagsReceived(LimitFlags motorOneLimitFlags)
{
    motorOneFaultsList_.updateLimits(motorOneLimitFlags);
    updateFaultLabel(ui_.motorOneFaultsLabel(), motorOneFaultsList_.getHighestActivePriorityLabel());
}
<commit_msg>formatting<commit_after>#include "DisplayDashboardView.h"
#include <QDebug>

namespace
{
    const double RED_SLOPE = -1;
    const int RED_INITIAL = 220;
    const double GREEN_SLOPE = 1.7;
    const int GREEN_INITIAL = 10;
    const int BLUE_INITIAL = 20;
    const QString DEFAULT_STYLESHEET = "QProgressBar:horizontal {\
            border: 1px solid white;\
            border-radius: 7px;\
            background: black;\
            }\
            QProgressBar::chunk:horizontal{\
            border-radius: 7px;\
            background: ";
}

DisplayDashboardView::DisplayDashboardView(AuxBmsPresenter& auxBmsPresenter,
        BatteryPresenter& batteryPresenter,
        BatteryFaultsPresenter& batteryFaultsPresenter,
        DriverControlsPresenter& driverControlsPresenter,
        KeyMotorPresenter& keyMotorPresenter,
        LightsPresenter& lightsPresenter,
        MpptPresenter& mpptPresenter,
        MotorDetailsPresenter& motorDetailsPresenter,
        MotorFaultsPresenter& motorFaultsPresenter,
        I_DisplayDashboardUI& ui,
        MotorFaultList& motorZeroFaultsList,
        MotorFaultList& motorOneFaultsList,
        BatteryFaultList& batteryFaultsList)
    : auxBmsPresenter_(auxBmsPresenter)
    , batteryPresenter_(batteryPresenter)
    , batteryFaultsPresenter_(batteryFaultsPresenter)
    , driverControlsPresenter_(driverControlsPresenter)
    , keyMotorPresenter_(keyMotorPresenter)
    , lightsPresenter_(lightsPresenter)
    , mpptPresenter_(mpptPresenter)
    , motorDetailsPresenter_(motorDetailsPresenter)
    , motorFaultsPresenter_(motorFaultsPresenter)
    , ui_(ui)
    , motorZeroFaultsList_(motorZeroFaultsList)
    , motorOneFaultsList_(motorOneFaultsList)
    , batteryFaultsList_(batteryFaultsList)
{
    connectAuxBms(auxBmsPresenter_);
    connectBattery(batteryPresenter_);
    connectBatteryFaults(batteryFaultsPresenter_);
    connectDriverControls(driverControlsPresenter_);
    connectKeyMotor(keyMotorPresenter_);
    connectLights(lightsPresenter_);
    connectMppt(mpptPresenter_);
    connectMotorDetails(motorDetailsPresenter_);
    connectMotorFaults(motorFaultsPresenter_);
    //ui_.showMaximized();
    ui_.show();
}
DisplayDashboardView::~DisplayDashboardView()
{}

void DisplayDashboardView::connectAuxBms(AuxBmsPresenter& auxBmsPresenter)
{
    connect(&auxBmsPresenter, SIGNAL(prechargeStateReceived(QString)),
            this, SLOT(prechargeStateReceived(QString)));
}

void DisplayDashboardView::connectBattery(BatteryPresenter& batteryPresenter)
{
    // TODO update to new battery data (depends on what should be shown in UI)
    connect(&batteryPresenter, SIGNAL(aliveReceived(bool)),
            this, SLOT(aliveReceived(bool)));
    connect(&batteryPresenter, SIGNAL(packNetPowerReceived(double)),
            this, SLOT(packNetPowerReceived(double)));
    connect(&batteryPresenter, SIGNAL(packStateOfChargeReceived(double)),
            this, SLOT(packStateOfChargeReceived(double)));
    connect(&batteryPresenter, SIGNAL(highTemperatureReceived(int)),
            this, SLOT(highTemperatureReceived(int)));
    connect(&batteryPresenter, SIGNAL(lowCellVoltageReceived(int)),
            this, SLOT(lowCellVoltageReceived(int)));
    connect(&batteryPresenter, SIGNAL(averageTemperatureReceived(int)),
            this, SLOT(averageTemperatureReceived(int)));
    connect(&batteryPresenter, SIGNAL(averageCellVoltageReceived(int)),
            this, SLOT(averageCellVoltageReceived(int)));
}

void DisplayDashboardView::connectBatteryFaults(BatteryFaultsPresenter& batteryFaultsPresenter)
{
    connect(&batteryFaultsPresenter, SIGNAL(errorFlagsReceived(BatteryErrorFlags)),
            this, SLOT(errorFlagsReceived(BatteryErrorFlags)));
    connect(&batteryFaultsPresenter, SIGNAL(limitFlagsReceived(BatteryLimitFlags)),
            this, SLOT(limitFlagsReceived(BatteryLimitFlags)));
}

void DisplayDashboardView::connectDriverControls(DriverControlsPresenter& driverControlsPresenter)
{
    connect(&driverControlsPresenter, SIGNAL(resetReceived(bool)),
            this, SLOT(resetReceived(bool)));
}

void DisplayDashboardView::connectKeyMotor(KeyMotorPresenter& keyMotorPresenter)
{
    connect(&keyMotorPresenter, SIGNAL(motorSetPowerReceived(double)),
            this, SLOT(motorSetPowerReceived(double)));
    connect(&keyMotorPresenter, SIGNAL(motorSetCurrentReceived(double)),
            this, SLOT(motorSetCurrentReceived(double)));
    connect(&keyMotorPresenter, SIGNAL(motorActualSpeedReceived(double)),
            this, SLOT(motorActualSpeedReceived(double)));
    connect(&keyMotorPresenter, SIGNAL(motorBusVoltageReceived(double)),
            this, SLOT(motorBusVoltageReceived(double)));
    connect(&keyMotorPresenter, SIGNAL(motorBusCurrentReceived(double)),
            this, SLOT(motorBusCurrentReceived(double)));
}

void DisplayDashboardView::connectLights(LightsPresenter& lightsPresenter)
{
    connect(&lightsPresenter, SIGNAL(lowBeamsReceived(bool)),
            this, SLOT(lowBeamsReceived(bool)));
    connect(&lightsPresenter, SIGNAL(highBeamsReceived(bool)),
            this, SLOT(highBeamsReceived(bool)));
    connect(&lightsPresenter, SIGNAL(leftSignalReceived(bool)),
            this, SLOT(leftSignalReceived(bool)));
    connect(&lightsPresenter, SIGNAL(rightSignalReceived(bool)),
            this, SLOT(rightSignalReceived(bool)));
    connect(&lightsPresenter, SIGNAL(lightAliveReceived(bool)),
            this, SLOT(lightAliveReceived(bool)));
}

void DisplayDashboardView::connectMppt(MpptPresenter& mpptPresenter)
{
    connect(&mpptPresenter, SIGNAL(mpptReceived(int, Mppt)),
            this, SLOT(mpptReceived(int, Mppt)));
    connect(&mpptPresenter, SIGNAL(mpptPowerReceived(double)),
            this, SLOT(mpptPowerReceived(double)));
}

void DisplayDashboardView::connectMotorDetails(MotorDetailsPresenter& motorDetailsPresenter)
{
}

void DisplayDashboardView::connectMotorFaults(MotorFaultsPresenter& motorFaultsPresenter)
{
    connect(&motorFaultsPresenter, SIGNAL(motorZeroErrorFlagsReceived(ErrorFlags)),
            this, SLOT(motorZeroErrorFlagsReceived(ErrorFlags)));
    connect(&motorFaultsPresenter, SIGNAL(motorZeroLimitFlagsReceived(LimitFlags)),
            this, SLOT(motorZeroLimitFlagsReceived(LimitFlags)));
    connect(&motorFaultsPresenter, SIGNAL(motorOneErrorFlagsReceived(ErrorFlags)),
            this, SLOT(motorOneErrorFlagsReceived(ErrorFlags)));
    connect(&motorFaultsPresenter, SIGNAL(motorOneLimitFlagsReceived(LimitFlags)),
            this, SLOT(motorOneLimitFlagsReceived(LimitFlags)));
}

void DisplayDashboardView::updateFaultLabel(QLabel& dashboardLabel, FaultLabel faultLabel)
{
    if (faultLabel.priority() >= 0)
    {
        dashboardLabel.setStyleSheet("font: 12pt \"Burlingame Pro\";\n color:" + faultLabel.color().name() + ";");
        dashboardLabel.setText(faultLabel.text());
    }
    else
    {
        dashboardLabel.setText("");
    }
}

void DisplayDashboardView::aliveReceived(bool)
{
}
void DisplayDashboardView::prechargeStateReceived(QString prechargeState)
{
    ui_.prechargeStateLabel().setText(prechargeState);
}

void DisplayDashboardView::packNetPowerReceived(double netPower)
{
    ui_.netPowerLabel().setText(QString::number(netPower, 'f', 2));
}

/*
 * TODO UI has to be updated w.r.t. the changes in the protocol
 */
void DisplayDashboardView::packStateOfChargeReceived(double packSocPercentage)
{
    ui_.stateOfChargeCapacityWidget().setValue(packSocPercentage);

    // The rgb values for the progressbar are calculated with the intention of displaying a colour closer to red
    // for low values and a colour closer to green for higher values. These are calculated using linear equations
    // with a slope and intercept.

    // Default colour
    int red = RED_INITIAL;
    int green = GREEN_INITIAL;
    int blue = BLUE_INITIAL;

    // Calculated color
    red += int(RED_SLOPE * packSocPercentage);
    green += int(GREEN_SLOPE * packSocPercentage);

    QString r = QString::number(red);
    QString g = QString::number(green);
    QString b = QString::number(blue);

    QString rgb = QString("rgb(%1,%2,%3);").arg(r, g, b);

    ui_.stateOfChargeCapacityWidget().setStyleSheet(DEFAULT_STYLESHEET + rgb + "}");
}
void DisplayDashboardView::highTemperatureReceived(int maxCellTemp)
{
    ui_.maxCellTemperatureLabel().setNum(maxCellTemp);
}
void DisplayDashboardView::lowCellVoltageReceived(int lowestCellVoltage)
{
    ui_.lowestCellVoltageLabel().setNum(lowestCellVoltage);
}
void DisplayDashboardView::averageTemperatureReceived(int averageCellTemp)
{
    ui_.avgCellTemperatureLabel().setNum(averageCellTemp);
}
void DisplayDashboardView::averageCellVoltageReceived(int averageVoltage)
{
    ui_.avgCellVoltageLabel().setNum(averageVoltage);
}
void DisplayDashboardView::errorFlagsReceived(BatteryErrorFlags batteryErrorFlags)
{
    batteryFaultsList_.updateErrors(batteryErrorFlags);
    updateFaultLabel(ui_.batteryFaultsLabel(), batteryFaultsList_.getHighestActivePriorityLabel());
}
void DisplayDashboardView::limitFlagsReceived(BatteryLimitFlags batteryLimitFlags)
{
    batteryFaultsList_.updateLimits(batteryLimitFlags);
    updateFaultLabel(ui_.batteryFaultsLabel(), batteryFaultsList_.getHighestActivePriorityLabel());
}

void DisplayDashboardView::resetReceived(bool reset)
{
    if (reset)
    {
        ui_.motorResetButtonWidget().setStyleSheet("background: url(:/Resources/MotorResetButton.png)");
    }
    else
    {
        ui_.motorResetButtonWidget().setStyleSheet("");
    }
}
void DisplayDashboardView::motorSetPowerReceived(double setPower)
{
    ui_.motorPowerLabel().setText(QString::number(setPower, 'f', 2));
}
void DisplayDashboardView::motorSetCurrentReceived(double setCurrent)
{
    ui_.setCurrentLabel().setText(QString::number(setCurrent, 'f', 3));
}
void DisplayDashboardView::motorActualSpeedReceived(double actualSpeed)
{
    ui_.actualSpeedLabel().setText(QString::number(actualSpeed, 'f', 1));
}
void DisplayDashboardView::motorBusVoltageReceived(double busVoltage)
{
    ui_.busVoltageLabel().setText(QString::number(busVoltage, 'f', 2));
}
void DisplayDashboardView::motorBusCurrentReceived(double busCurrent)
{
    ui_.busCurrentLabel().setText(QString::number(busCurrent, 'f', 3));
}

void DisplayDashboardView::lowBeamsReceived(bool lowBeams)
{
    if (lowBeams)
    {
        ui_.lowHeadlightIndicatorWidget().setStyleSheet("background: url(:/Resources/LowHeadlightIndicator.png)");
    }
    else
    {
        ui_.lowHeadlightIndicatorWidget().setStyleSheet("");
    }
}
void DisplayDashboardView::highBeamsReceived(bool highBeams)
{
    if (highBeams)
    {
        ui_.highHeadlightIndicatorWidget().setStyleSheet("background: url(:/Resources/HighHeadlightIndicator.png)");
    }
    else
    {
        ui_.highHeadlightIndicatorWidget().setStyleSheet("");
    }
}
void DisplayDashboardView::leftSignalReceived(bool leftSignal)
{
    if (leftSignal)
    {
        ui_.leftTurnSignalWidget().setStyleSheet("background: url(:/Resources/TurnSignalLeft.png);");
    }
    else
    {
        ui_.leftTurnSignalWidget().setStyleSheet("");
    }
}
void DisplayDashboardView::rightSignalReceived(bool rightSignal)
{
    if (rightSignal)
    {
        ui_.rightTurnSignalWidget().setStyleSheet("background: url(:/Resources/TurnSignalRight.png);");
    }
    else
    {
        ui_.rightTurnSignalWidget().setStyleSheet("");
    }
}
void DisplayDashboardView::lightAliveReceived(bool)
{
    // TODO
}
void DisplayDashboardView::mpptReceived(int i, Mppt mppt)
{
    if (i == 0)
    {
        ui_.array0CurrentLabel().setNum(mppt.arrayCurrent());
        ui_.array0VoltageLabel().setNum(mppt.arrayVoltage());
        mpptZeroPower_ = mppt.arrayCurrent() * mppt.arrayVoltage();
    }
    else if (i == 1)
    {
        ui_.array1CurrentLabel().setNum(mppt.arrayCurrent());
        ui_.array1VoltageLabel().setNum(mppt.arrayVoltage());
        mpptOnePower_ = mppt.arrayCurrent() * mppt.arrayVoltage();
    }
    else if (i == 2)
    {
        ui_.array2CurrentLabel().setNum(mppt.arrayCurrent());
        ui_.array2VoltageLabel().setNum(mppt.arrayVoltage());
        mpptTwoPower_ = mppt.arrayCurrent() * mppt.arrayVoltage();
    }

    mpptPowerReceived(mpptZeroPower_ + mpptOnePower_ + mpptTwoPower_);
}

void DisplayDashboardView::mpptPowerReceived(double mpptPower)
{
    ui_.powerInLabel().setText(QString::number(mpptPower, 'f', 0));
    ui_.powerOutLabel().setNum(ui_.netPowerLabel().text().toDouble() - mpptPower);
}

void DisplayDashboardView::motorZeroErrorFlagsReceived(ErrorFlags motorZeroErrorFlags)
{
    motorZeroFaultsList_.updateErrors(motorZeroErrorFlags);
    updateFaultLabel(ui_.motorZeroFaultsLabel(), motorZeroFaultsList_.getHighestActivePriorityLabel());
}
void DisplayDashboardView::motorZeroLimitFlagsReceived(LimitFlags motorZeroLimitFlags)
{
    motorZeroFaultsList_.updateLimits(motorZeroLimitFlags);
    updateFaultLabel(ui_.motorZeroFaultsLabel(), motorZeroFaultsList_.getHighestActivePriorityLabel());
}
void DisplayDashboardView::motorOneErrorFlagsReceived(ErrorFlags motorOneErrorFlags)
{
    motorOneFaultsList_.updateErrors(motorOneErrorFlags);
    updateFaultLabel(ui_.motorOneFaultsLabel(), motorOneFaultsList_.getHighestActivePriorityLabel());
}
void DisplayDashboardView::motorOneLimitFlagsReceived(LimitFlags motorOneLimitFlags)
{
    motorOneFaultsList_.updateLimits(motorOneLimitFlags);
    updateFaultLabel(ui_.motorOneFaultsLabel(), motorOneFaultsList_.getHighestActivePriorityLabel());
}
<|endoftext|>


<commit_before>/*
*  Copyright 2014 Matthias Fuchs
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/

#include "stromx/raspi/impl/Gpio.h"

#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define LOW  0
#define HIGH 1

namespace stromx
{
namespace raspi
{
namespace impl
{

int GPIOExport(int pin)
{
#define BUFFER_MAX 3
    char buffer[BUFFER_MAX];
    ssize_t bytes_written;
    int fd;

    fd = open("/sys/class/gpio/export", O_WRONLY);
    if (-1 == fd)
    {
        fprintf(stderr, "Failed to open export for writing!\n");
        return(-1);
    }

    bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pin);
    write(fd, buffer, bytes_written);
    close(fd);
    return(0);
}

int GPIOUnexport(int pin)
{
    char buffer[BUFFER_MAX];
    ssize_t bytes_written;
    int fd;

    fd = open("/sys/class/gpio/unexport", O_WRONLY);
    if (-1 == fd)
    {
        fprintf(stderr, "Failed to open unexport for writing!\n");
        return(-1);
    }

    bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pin);
    write(fd, buffer, bytes_written);
    close(fd);
    return(0);
}

int GPIODirection(int pin, int dir)
{
    static const char s_directions_str[]  = "in\0out";

#define DIRECTION_MAX 35
    char path[DIRECTION_MAX];
    int fd;

    snprintf(path, DIRECTION_MAX, "/sys/class/gpio/gpio%d/direction", pin);
    fd = open(path, O_WRONLY);
    if (-1 == fd)
    {
        fprintf(stderr, "Failed to open gpio direction for writing!\n");
        return(-1);
    }

    if (-1 == write(fd, &s_directions_str[IN == dir ? 0 : 3], IN == dir ? 2 : 3))
    {
        fprintf(stderr, "Failed to set direction!\n");
        return(-1);
    }

    close(fd);
    return(0);
}

int GPIOEdge(int pin, int edge)
{
    static const char s_edge_str[]  = "rising\0falling";

#define EDGE_MAX 30
    char path[EDGE_MAX];
    int fd;

    snprintf(path, EDGE_MAX, "/sys/class/gpio/gpio%d/edge", pin);
    fd = open(path, O_WRONLY);
    if (-1 == fd)
    {
        fprintf(stderr, "Failed to open gpio edge for writing!\n");
        return(-1);
    }

    if (-1 == write(fd, &s_edge_str[RISING == edge ? 0 : 7], RISING == edge ? 6 : 7))
    {
        fprintf(stderr, "Failed to set edge!\n");
        return(-1);
    }

    close(fd);
    return(0);
}

int GPIORead(int pin)
{
#define VALUE_MAX 30
    char path[VALUE_MAX];
    char value_str[3];
    int fd;

    snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin);
    fd = open(path, O_RDONLY);
    if (-1 == fd)
    {
        fprintf(stderr, "Failed to open gpio value for reading!\n");
        return(-1);
    }

    if (-1 == read(fd, value_str, 3))
    {
        fprintf(stderr, "Failed to read value!\n");
        return(-1);
    }

    close(fd);

    return(atoi(value_str));
}

int GPIOWrite(int pin, int value)
{
    static const char s_values_str[] = "01";

    char path[VALUE_MAX];
    int fd;

    snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin);
    fd = open(path, O_WRONLY);
    if (-1 == fd)
    {
        fprintf(stderr, "Failed to open gpio value for writing!\n");
        return(-1);
    }

    if (1 != write(fd, &s_values_str[LOW == value ? 0 : 1], 1))
    {
        fprintf(stderr, "Failed to write value!\n");
        return(-1);
    }

    close(fd);
    return(0);
}

int GPIOOpen(int pin, int& socket)
{
    char path[VALUE_MAX];
    int fd;

    snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin);
    fd = open(path, O_RDONLY| O_NONBLOCK);
    if (-1 == fd)
    {
        fprintf(stderr, "Failed to open gpio value for reading!\n");
        return(-1);
    }

    socket = fd;
    return(0);
}

int GPIOCreatePipe(int& readEnd, int& writeEnd)
{
    int pipefd[2] = {0, 0};
    int rc;
    rc = pipe(pipefd);

    if (-1 == rc)
    {
        fprintf(stderr, "Failed to create pipe!\n");
        return(-1);
    }

    readEnd = pipefd[0];
    writeEnd = pipefd[1];
    return(0);
}

int GPIOPoll(int gpio, int readEnd, bool & interrupt)
{
    struct pollfd fdset[2];
    int nfds = 2;
    int rc;
    interrupt = false;

    memset((void*)fdset, 0, sizeof(fdset));

    fdset[0].fd = readEnd;
    fdset[0].events = POLLIN;

    fdset[1].fd = gpio;
    fdset[1].events = POLLPRI;

    rc = poll(fdset, nfds, -1);

    if (rc < 0)
    {
        fprintf(stderr, "Failed to poll!\n");
        return(-1);
    }

    if (fdset[1].revents & POLLPRI)
    {
        fprintf(stdout, "GPIO interrupt!\n");
    }

    if (fdset[0].revents & POLLIN)
    {
        interrupt = true;
        fprintf(stdout, "Pipe interrupt!\n");
    }

    return(0);
}

int GPIOCloseSocket(int socket)
{
    if (close(socket))
    {
        fprintf(stderr, "Failed to close socket!\n");
    }

    return(0);
}

int GPIOSendInterrupt(int writeEnd)
{
    if (write(writeEnd, "\n", 1) != 1)
    {
        fprintf(stderr, "Failed to send interrupt!\n");
    }

    return(0);
}

}
}
}
<commit_msg>Read gpio socket after polling<commit_after>/*
*  Copyright 2014 Matthias Fuchs
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/

#include "stromx/raspi/impl/Gpio.h"

#include <fcntl.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#define LOW  0
#define HIGH 1

namespace stromx
{
namespace raspi
{
namespace impl
{

int GPIOExport(int pin)
{
#define BUFFER_MAX 3
    char buffer[BUFFER_MAX];
    ssize_t bytes_written;
    int fd;

    fd = open("/sys/class/gpio/export", O_WRONLY);
    if (-1 == fd)
    {
        fprintf(stderr, "Failed to open export for writing!\n");
        return(-1);
    }

    bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pin);
    write(fd, buffer, bytes_written);
    close(fd);
    return(0);
}

int GPIOUnexport(int pin)
{
    char buffer[BUFFER_MAX];
    ssize_t bytes_written;
    int fd;

    fd = open("/sys/class/gpio/unexport", O_WRONLY);
    if (-1 == fd)
    {
        fprintf(stderr, "Failed to open unexport for writing!\n");
        return(-1);
    }

    bytes_written = snprintf(buffer, BUFFER_MAX, "%d", pin);
    write(fd, buffer, bytes_written);
    close(fd);
    return(0);
}

int GPIODirection(int pin, int dir)
{
    static const char s_directions_str[]  = "in\0out";

#define DIRECTION_MAX 35
    char path[DIRECTION_MAX];
    int fd;

    snprintf(path, DIRECTION_MAX, "/sys/class/gpio/gpio%d/direction", pin);
    fd = open(path, O_WRONLY);
    if (-1 == fd)
    {
        fprintf(stderr, "Failed to open gpio direction for writing!\n");
        return(-1);
    }

    if (-1 == write(fd, &s_directions_str[IN == dir ? 0 : 3], IN == dir ? 2 : 3))
    {
        fprintf(stderr, "Failed to set direction!\n");
        return(-1);
    }

    close(fd);
    return(0);
}

int GPIOEdge(int pin, int edge)
{
    static const char s_edge_str[]  = "rising\0falling";

#define EDGE_MAX 30
    char path[EDGE_MAX];
    int fd;

    snprintf(path, EDGE_MAX, "/sys/class/gpio/gpio%d/edge", pin);
    fd = open(path, O_WRONLY);
    if (-1 == fd)
    {
        fprintf(stderr, "Failed to open gpio edge for writing!\n");
        return(-1);
    }

    if (-1 == write(fd, &s_edge_str[RISING == edge ? 0 : 7], RISING == edge ? 6 : 7))
    {
        fprintf(stderr, "Failed to set edge!\n");
        return(-1);
    }

    close(fd);
    return(0);
}

int GPIORead(int pin)
{
#define VALUE_MAX 30
    char path[VALUE_MAX];
    char value_str[3];
    int fd;

    snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin);
    fd = open(path, O_RDONLY);
    if (-1 == fd)
    {
        fprintf(stderr, "Failed to open gpio value for reading!\n");
        return(-1);
    }

    if (-1 == read(fd, value_str, 3))
    {
        fprintf(stderr, "Failed to read value!\n");
        return(-1);
    }

    close(fd);

    return(atoi(value_str));
}

int GPIOWrite(int pin, int value)
{
    static const char s_values_str[] = "01";

    char path[VALUE_MAX];
    int fd;

    snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin);
    fd = open(path, O_WRONLY);
    if (-1 == fd)
    {
        fprintf(stderr, "Failed to open gpio value for writing!\n");
        return(-1);
    }

    if (1 != write(fd, &s_values_str[LOW == value ? 0 : 1], 1))
    {
        fprintf(stderr, "Failed to write value!\n");
        return(-1);
    }

    close(fd);
    return(0);
}

int GPIOOpen(int pin, int& socket)
{
    char path[VALUE_MAX];
    int fd;

    snprintf(path, VALUE_MAX, "/sys/class/gpio/gpio%d/value", pin);
    fd = open(path, O_RDONLY| O_NONBLOCK);
    if (-1 == fd)
    {
        fprintf(stderr, "Failed to open gpio value for reading!\n");
        return(-1);
    }

    socket = fd;
    return(0);
}

int GPIOCreatePipe(int& readEnd, int& writeEnd)
{
    int pipefd[2] = {0, 0};
    int rc;
    rc = pipe(pipefd);

    if (-1 == rc)
    {
        fprintf(stderr, "Failed to create pipe!\n");
        return(-1);
    }

    readEnd = pipefd[0];
    writeEnd = pipefd[1];
    return(0);
}

int GPIOPoll(int gpio, int readEnd, bool & interrupt)
{
#define MAX_BUF 64
    struct pollfd fdset[2];
    int nfds = 2;
    int rc;
    char *buf[MAX_BUF];
    interrupt = false;

    memset((void*)fdset, 0, sizeof(fdset));

    fdset[0].fd = readEnd;
    fdset[0].events = POLLIN;

    fdset[1].fd = gpio;
    fdset[1].events = POLLPRI;

    rc = poll(fdset, nfds, -1);

    if (rc < 0)
    {
        fprintf(stderr, "Failed to poll!\n");
        return(-1);
    }

    if (fdset[1].revents & POLLPRI)
    {
        fprintf(stdout, "GPIO interrupt!\n");
        read(fdset[1].fd, buf, MAX_BUF);
    }

    if (fdset[0].revents & POLLIN)
    {
        interrupt = true;
        fprintf(stdout, "Pipe interrupt!\n");
        read(fdset[0].fd, buf, 1);
    }

    return(0);
}

int GPIOCloseSocket(int socket)
{
    if (close(socket))
    {
        fprintf(stderr, "Failed to close socket!\n");
    }

    return(0);
}

int GPIOSendInterrupt(int writeEnd)
{
    if (write(writeEnd, "\n", 1) != 1)
    {
        fprintf(stderr, "Failed to send interrupt!\n");
    }

    return(0);
}

}
}
}
<|endoftext|>


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

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkShapedNeighborhoodIteratorTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 "itkNeighborhoodIteratorTestCommon.txx"
#include "itkShapedNeighborhoodIterator.h"

int itkShapedNeighborhoodIteratorTest(int, char* [] )
{

  TestImageType::Pointer img = GetTestImage(10, 10, 5, 3);
  itk::ShapedNeighborhoodIterator<TestImageType>::IndexType loc;
  loc[0] = 4; loc[1] = 4; loc[2] = 2; loc[3] = 1;

  // radius of the iterator
  itk::ShapedNeighborhoodIterator<TestImageType>::RadiusType radius;
  radius[0] = radius[1] = radius[2] = radius[3] = 1;

  // region over which the iterator is defined
  itk::ShapedNeighborhoodIterator<TestImageType>::RegionType reg;
  itk::ShapedNeighborhoodIterator<TestImageType>::SizeType sz;
  itk::ShapedNeighborhoodIterator<TestImageType>::IndexType idx;
  idx[0] = idx[1] = idx[2] = 0;  idx[3] = 1;
  sz[0] = sz[1] = 10; sz[2] = 5; sz[3] = 1;
  reg.SetIndex(idx); reg.SetSize(sz);

  // initialize an iterator
  println("Creating ShapedNeighborhoodIterator");
  itk::ShapedNeighborhoodIterator<TestImageType>
    it(radius, img, reg);
  it.Print(std::cout);

  println("Moving iterator using SetLocation()");
  it.SetLocation(loc);
  it.Print(std::cout);

  println("Initializing ShapedNeighborhoodIterator");

  println("Activating some offsets");
  println("...turn on [0,0,0,0], the center pixel");
  itk::ShapedNeighborhoodIterator<TestImageType>::OffsetType off;
  off[0] = 0; off[1] = 0; off[2] = 0; off[3] = 0;
  it.ActivateOffset(off);
  it.Print(std::cout);

  println("...turn on [1,0,0,0]");
  off[0] = 1; off[1] = 0; off[2] = 0; off[3] = 0;
  it.ActivateOffset(off);
  it.Print(std::cout);

  println("...turn on [1,0,0,0] again");
  off[0] = 1; off[1] = 0; off[2] = 0; off[3] = 0;
  it.ActivateOffset(off);
  it.Print(std::cout);

  println("...turn on [-1,0,0,0]");
  off[0] = -1; off[1] = 0; off[2] = 0; off[3] = 0;
  it.ActivateOffset(off);
  it.Print(std::cout);

  println("...turn on [0,-1,0,0]");
  off[0] = 0; off[1] = -1; off[2] = 0; off[3] = 0;
  it.ActivateOffset(off);
  it.Print(std::cout);

  println("...turn on [0,1,0,0]");
  off[0] = 0; off[1] = 1; off[2] = 0; off[3] = 0;
  it.ActivateOffset(off);
  it.Print(std::cout);

  println("Testing iteration through the neighborhood.");
  itk::ShapedNeighborhoodIterator<TestImageType>::Iterator
    ci = it.Begin();

  println("Testing using IsAtEnd()");
  while (! ci.IsAtEnd())
    {
      std::cout << ci.GetNeighborhoodIndex() << " -> "
                << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl;
      ci++;
    }

  println("Testing using != it.End()");
  for (ci = it.Begin(); ci != it.End(); ++ci)
    {
      std::cout << ci.GetNeighborhoodIndex() << " -> "
                << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl;
    }

  println("Testing reverse iteration using != it.Begin()");
  ci = it.End();
  --ci;
  while (ci != it.Begin())
    {
      std::cout << ci.GetNeighborhoodIndex() << " -> "
                << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl;
      ci--;
    }
  std::cout << ci.GetNeighborhoodIndex() << " -> "
            << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl;

  println("Testing read through GetPixel(itk::Offset(0,0,0,0))");
  TestImageType::IndexType voff;
  voff[0] = 1; voff[1] = 1; voff[2] = 1; voff[3] = 1;
  off[0] = 0; off[1] = 0; off[2] = 0; off[3] = 0;
  std::cout << it.GetPixel(off) << std::endl;

  println("Testing read through GetPixel(unsigned int)");
  std::cout << it.GetPixel(it.GetNeighborhoodIndex(off)) << std::endl;

  println("Testing write through iterator dereference");
  for (ci = it.Begin(); ci != it.End(); ++ci)
    {
      ci.Set(voff);
    }
  for (ci = it.Begin(); ci != it.End(); ++ci)
    {
      std::cout << ci.GetNeighborhoodIndex() << " -> "
                << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl;
    }

  println("Testing write through SetPixel(itk::Offset(0,0,0,0))");
  voff[0] = 45000;
  it.SetPixel(off, voff);
   for (ci = it.Begin(); ci != it.End(); ++ci)
    {
      std::cout << ci.GetNeighborhoodIndex() << " -> "
                << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl;
    }

   println("Testing iteration through the image");
   off[0] = 0; off[1] =0; off[2] = 0; off[3] = 0;
   for (it.GoToBegin(); !it.IsAtEnd(); ++it)
     {
       std::cout << it.GetPixel(off) << std::endl;
     }

   println("Testing reverse iteration through the image");
   off[0] = 0; off[1] =0; off[2] = 0; off[3] = 0;
   for (it.GoToEnd(), --it; !it.IsAtBegin(); --it)
     {
       std::cout << it.GetPixel(off) << std::endl;
     }
   std::cout << it.GetPixel(off) << std::endl;

  return 0;
}
<commit_msg>ENH: Now testing assignment operator<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkShapedNeighborhoodIteratorTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm 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 "itkNeighborhoodIteratorTestCommon.txx"
#include "itkShapedNeighborhoodIterator.h"

int itkShapedNeighborhoodIteratorTest(int, char* [] )
{

  TestImageType::Pointer img = GetTestImage(10, 10, 5, 3);
  itk::ShapedNeighborhoodIterator<TestImageType>::IndexType loc;
  loc[0] = 4; loc[1] = 4; loc[2] = 2; loc[3] = 1;

  // radius of the iterator
  itk::ShapedNeighborhoodIterator<TestImageType>::RadiusType radius;
  radius[0] = radius[1] = radius[2] = radius[3] = 1;

  // region over which the iterator is defined
  itk::ShapedNeighborhoodIterator<TestImageType>::RegionType reg;
  itk::ShapedNeighborhoodIterator<TestImageType>::SizeType sz;
  itk::ShapedNeighborhoodIterator<TestImageType>::IndexType idx;
  idx[0] = idx[1] = idx[2] = 0;  idx[3] = 1;
  sz[0] = sz[1] = 10; sz[2] = 5; sz[3] = 1;
  reg.SetIndex(idx); reg.SetSize(sz);

  // initialize an iterator
  println("Creating ShapedNeighborhoodIterator");
  itk::ShapedNeighborhoodIterator<TestImageType>
    it(radius, img, reg);
  it.Print(std::cout);

  println("Moving iterator using SetLocation()");
  it.SetLocation(loc);
  it.Print(std::cout);

  println("Initializing ShapedNeighborhoodIterator");

  println("Activating some offsets");
  println("...turn on [0,0,0,0], the center pixel");
  itk::ShapedNeighborhoodIterator<TestImageType>::OffsetType off;
  off[0] = 0; off[1] = 0; off[2] = 0; off[3] = 0;
  it.ActivateOffset(off);
  it.Print(std::cout);

  println("...turn on [1,0,0,0]");
  off[0] = 1; off[1] = 0; off[2] = 0; off[3] = 0;
  it.ActivateOffset(off);
  it.Print(std::cout);

  println("...turn on [1,0,0,0] again");
  off[0] = 1; off[1] = 0; off[2] = 0; off[3] = 0;
  it.ActivateOffset(off);
  it.Print(std::cout);

  println("...turn on [-1,0,0,0]");
  off[0] = -1; off[1] = 0; off[2] = 0; off[3] = 0;
  it.ActivateOffset(off);
  it.Print(std::cout);

  println("...turn on [0,-1,0,0]");
  off[0] = 0; off[1] = -1; off[2] = 0; off[3] = 0;
  it.ActivateOffset(off);
  it.Print(std::cout);

  println("...turn on [0,1,0,0]");
  off[0] = 0; off[1] = 1; off[2] = 0; off[3] = 0;
  it.ActivateOffset(off);
  it.Print(std::cout);

  println("Testing iteration through the neighborhood.");
  itk::ShapedNeighborhoodIterator<TestImageType>::Iterator
    ci = it.Begin();

  println("Testing using IsAtEnd()");
  while (! ci.IsAtEnd())
    {
      std::cout << ci.GetNeighborhoodIndex() << " -> "
                << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl;
      ci++;
    }

  println("Testing using != it.End()");
  for (ci = it.Begin(); ci != it.End(); ++ci)
    {
      std::cout << ci.GetNeighborhoodIndex() << " -> "
                << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl;
    }

  println("Testing reverse iteration using != it.Begin()");
  ci = it.End();
  --ci;
  while (ci != it.Begin())
    {
      std::cout << ci.GetNeighborhoodIndex() << " -> "
                << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl;
      ci--;
    }
  std::cout << ci.GetNeighborhoodIndex() << " -> "
            << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl;

  println("Testing read through GetPixel(itk::Offset(0,0,0,0))");
  TestImageType::IndexType voff;
  voff[0] = 1; voff[1] = 1; voff[2] = 1; voff[3] = 1;
  off[0] = 0; off[1] = 0; off[2] = 0; off[3] = 0;
  std::cout << it.GetPixel(off) << std::endl;

  println("Testing read through GetPixel(unsigned int)");
  std::cout << it.GetPixel(it.GetNeighborhoodIndex(off)) << std::endl;

  println("Testing write through iterator dereference");
  for (ci = it.Begin(); ci != it.End(); ++ci)
    {
      ci.Set(voff);
    }
  for (ci = it.Begin(); ci != it.End(); ++ci)
    {
      std::cout << ci.GetNeighborhoodIndex() << " -> "
                << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl;
    }

  println("Testing write through SetPixel(itk::Offset(0,0,0,0))");
  voff[0] = 45000;
  it.SetPixel(off, voff);
   for (ci = it.Begin(); ci != it.End(); ++ci)
    {
      std::cout << ci.GetNeighborhoodIndex() << " -> "
                << ci.GetNeighborhoodOffset() << " = " << ci.Get() << std::endl;
    }

   println("Testing iteration through the image");
   off[0] = 0; off[1] =0; off[2] = 0; off[3] = 0;
   for (it.GoToBegin(); !it.IsAtEnd(); ++it)
     {
       std::cout << it.GetPixel(off) << std::endl;
     }

   println("Testing reverse iteration through the image");
   off[0] = 0; off[1] =0; off[2] = 0; off[3] = 0;
   for (it.GoToEnd(), --it; !it.IsAtBegin(); --it)
     {
       std::cout << it.GetPixel(off) << std::endl;
     }
   std::cout << it.GetPixel(off) << std::endl;

   println("testing operator=");
   itk::ShapedNeighborhoodIterator<TestImageType> oeIt;
   oeIt = it;

   it.Print(std::cout);
   oeIt.Print(std::cout);

  return 0;
}
<|endoftext|>