<commit_before>//=============================================================================================================
/**
* @file     mne_bem.cpp
* @author   Jana Kiesel <jana.kiesel@tu-ilmenau.de>;
*           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     June, 2015
*
* @section  LICENSE
*
* Copyright (C) 2015, Jana Kiesel, Christoph Dinh and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief    MNEBem class implementation.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "mne_bem.h"

#include <utils/mnemath.h>
#include <fs/label.h>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace UTILSLIB;
using namespace FSLIB;
using namespace MNELIB;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

MNEBem::MNEBem()
{
}

//*************************************************************************************************************

MNEBem::MNEBem(const MNEBem &p_MNEBem)
: m_qListBemSurface(p_MNEBem.m_qListBemSurface)
{

}

//*************************************************************************************************************

MNEBem::MNEBem(QIODevice &p_IODevice)   //const MNEBem &p_MNEBem
//: m_qListBemSurface()
{
    FiffStream::SPtr t_pStream(new FiffStream(&p_IODevice));
    FiffDirTree t_Tree;

    if(!MNEBem::readFromStream(t_pStream, true, t_Tree, *this))
    {
        t_pStream->device()->close();
        std::cout << "Could not read the bem surfaces\n"; // ToDo throw error
        //ToDo error(me,'Could not read the bem surfaces (%s)',mne_omit_first_line(lasterr));
//        return false;
    }

//    bool testStream =t_pStream->device()->isOpen();
}

//*************************************************************************************************************

MNEBem::~MNEBem()
{

}

//*************************************************************************************************************

void MNEBem::clear()
{
    m_qListBemSurface.clear();
}

//*************************************************************************************************************

bool MNEBem::readFromStream(FiffStream::SPtr& p_pStream, bool add_geom, FiffDirTree& p_Tree, MNEBem& p_Bem)
{
    //
    //   Open the file, create directory
    //
    bool open_here = false;
    QFile t_file;//ToDo TCPSocket;

    if (!p_pStream->device()->isOpen())
    {
        QList<FiffDirEntry> t_Dir;
        QString t_sFileName = p_pStream->streamName();

        t_file.setFileName(t_sFileName);
        p_pStream = FiffStream::SPtr(new FiffStream(&t_file));
        if(!p_pStream->open(p_Tree, t_Dir))
            return false;
        open_here = true;
//        if(t_pDir)
//            delete t_pDir;
    }

    //
    //   Find all BEM surfaces
    //

    QList<FiffDirTree>bem = p_Tree.dir_tree_find(FIFFB_BEM);
    if(bem.isEmpty())
    {
        qCritical() << "No BEM block found!";
        if(open_here)
            p_pStream->device()->close();
        return false;
    }

    QList<FiffDirTree>bemsurf = p_Tree.dir_tree_find(FIFFB_BEM_SURF);
    if(bemsurf.isEmpty())
    {
        qCritical() << "No BEM surfaces found!";
        if(open_here)
            p_pStream->device()->close();
        return false;
    }

    for(int k = 0; k < bemsurf.size(); ++k)
    {
        MNEBemSurface  p_BemSurface;
        printf("\tReading a BEM surface...");
        MNEBem::readBemSurface(p_pStream.data(), bemsurf[k], p_BemSurface);
        p_BemSurface.addTriangleData();
         if (add_geom)
            p_BemSurface.addVertexNormals();
        printf("\t[done]\n" );

        p_Bem.m_qListBemSurface.append(p_BemSurface);
//           src(k) = this;
    }

    printf("\t%d bem surfaces read\n", bemsurf.size());

    if(open_here)
        p_pStream->device()->close();
    return true;
}

//*************************************************************************************************************

bool MNEBem::readBemSurface(FiffStream *p_pStream, const FiffDirTree &p_Tree, MNEBemSurface &p_BemSurface)
{
    p_BemSurface.clear();

    FiffTag::SPtr t_pTag;

    //=====================================================================
    if(!p_Tree.find_tag(p_pStream, FIFF_BEM_SURF_ID, t_pTag))
         p_BemSurface.id = FIFFV_BEM_SURF_ID_UNKNOWN;
    else
         p_BemSurface.id = *t_pTag->toInt();

        qDebug() << "Read BemSurface ID; type:" << t_pTag->getType() << "value:" << *t_pTag->toInt();

    //=====================================================================
    if(!p_Tree.find_tag(p_pStream, FIFF_BEM_SIGMA, t_pTag))
         p_BemSurface.sigma = 1.0;
    else
         p_BemSurface.sigma = *t_pTag->toFloat();

//        qDebug() <<

    //=====================================================================
    if(!p_Tree.find_tag(p_pStream, FIFF_BEM_SURF_NNODE, t_pTag))
    {
        p_pStream->device()->close();
        std::cout << "np not found!";
        return false;
    }
    else
         p_BemSurface.np = *t_pTag->toInt();

//        qDebug() <<

    //=====================================================================
    if(!p_Tree.find_tag(p_pStream, FIFF_BEM_SURF_NTRI, t_pTag))
    {
        p_pStream->device()->close();
        std::cout << "ntri not found!";
        return false;
    }
    else
         p_BemSurface.ntri = *t_pTag->toInt();

//        qDebug() <<

    //=====================================================================
    if(!p_Tree.find_tag(p_pStream, FIFF_MNE_COORD_FRAME, t_pTag))
    {
        qWarning() << "FIFF_MNE_COORD_FRAME not found, trying FIFF_BEM_COORD_FRAME.";
        if(!p_Tree.find_tag(p_pStream, FIFF_BEM_COORD_FRAME, t_pTag))
        {
            p_pStream->device()->close();
            std::cout << "Coordinate frame information not found."; //ToDo: throw error.
            return false;
        }
        else
            p_BemSurface.coord_frame = *t_pTag->toInt();
    }
    else
         p_BemSurface.coord_frame = *t_pTag->toInt();

//        qDebug() <<

    //=====================================================================
    //
    //   Vertices, normals, and triangles
    //
    //=====================================================================
    if(!p_Tree.find_tag(p_pStream, FIFF_BEM_SURF_NODES, t_pTag))
    {
        p_pStream->device()->close();
        std::cout << "Vertex data not found."; //ToDo: throw error.
        return false;
    }

    p_BemSurface.rr = t_pTag->toFloatMatrix().transpose();
    qint32 rows_rr = p_BemSurface.rr.rows();

    if (rows_rr != p_BemSurface.np)
    {
        p_pStream->device()->close();
        std::cout << "Vertex information is incorrect."; //ToDo: throw error.
        return false;
    }
        qDebug() << "Surf Nodes; type:" << t_pTag->getType();

    //=====================================================================
    if(!p_Tree.find_tag(p_pStream, FIFF_BEM_SURF_NORMALS, t_pTag))
    {
        if(!p_Tree.find_tag(p_pStream, FIFF_MNE_SOURCE_SPACE_NORMALS, t_pTag))
        {
            p_pStream->device()->close();
            std::cout << "Vertex normals not found."; //ToDo: throw error.
            return false;
        }

        p_BemSurface.nn = t_pTag->toFloatMatrix().transpose();
    }
    else
    {
        p_BemSurface.nn = t_pTag->toFloatMatrix().transpose();
    }

    if (p_BemSurface.nn.rows() != p_BemSurface.np)
    {
        p_pStream->device()->close();
        std::cout << "Vertex normal information is incorrect."; //ToDo: throw error.
        return false;
    }

    qDebug() << "Bem Vertex Normals; type:" << t_pTag->getType();

    //=====================================================================
    if (p_BemSurface.ntri > 0)
    {
        if(!p_Tree.find_tag(p_pStream, FIFF_BEM_SURF_TRIANGLES, t_pTag))
        {
            if(!p_Tree.find_tag(p_pStream, FIFF_MNE_SOURCE_SPACE_TRIANGLES, t_pTag))
            {
                p_pStream->device()->close();
                std::cout << "Triangulation not found."; //ToDo: throw error.
                return false;
            }
            else
            {
                p_BemSurface.tris = t_pTag->toIntMatrix().transpose();
                p_BemSurface.tris -= MatrixXi::Constant(p_BemSurface.tris.rows(),3,1);//0 based indizes
            }
        }
        else
        {
            p_BemSurface.tris = t_pTag->toIntMatrix().transpose();
            p_BemSurface.tris -= MatrixXi::Constant(p_BemSurface.tris.rows(),3,1);//0 based indizes
        }

        if (p_BemSurface.tris.rows() != p_BemSurface.ntri)
        {
            p_pStream->device()->close();
            std::cout << "Triangulation information is incorrect."; //ToDo: throw error.
            return false;
        }
    }
    else
    {
        MatrixXi p_defaultMatrix(0, 0);
        p_BemSurface.tris = p_defaultMatrix;
    }

    return true;
}

//*************************************************************************************************************

void MNEBem::write(QIODevice &p_IODevice)
{
    //
    //   Open the file, create directory
    //

    // Create the file and save the essentials
    FiffStream::SPtr t_pStream = FiffStream::start_file(p_IODevice);
    printf("Write BEM surface in %s...", t_pStream->streamName().toUtf8().constData(), "\n");
    this->writeToStream(t_pStream.data());
}

//*************************************************************************************************************

void MNEBem::writeToStream(FiffStream* p_pStream)
{
    p_pStream->start_block(FIFFB_BEM);
    for(qint32 h = 0; h < m_qListBemSurface.size(); ++h)
    {
        printf("\tWrite a bem surface... ");
        p_pStream->start_block(FIFFB_BEM_SURF);
        m_qListBemSurface[h].writeToStream(p_pStream);
        p_pStream->end_block(FIFFB_BEM_SURF);
        printf("[done]\n");
    }
    printf("\t%d bem surfaces written\n", m_qListBemSurface.size());
    p_pStream->end_block(FIFFB_BEM);
    p_pStream->end_file();
}

//*************************************************************************************************************

const MNEBemSurface& MNEBem::operator[] (qint32 idx) const
{
    if (idx>=m_qListBemSurface.length())
    {
        qWarning("Warning: Required surface doesn't exist! Returning surface '0'.");
        idx=0;
    }
    return m_qListBemSurface[idx];
}

//*************************************************************************************************************

MNEBemSurface& MNEBem::operator[] (qint32 idx)
{
    if (idx>=m_qListBemSurface.length())
    {
        qWarning("Warning: Required surface doesn't exist! Returning surface '0'.");
        idx=0;
    }
    return m_qListBemSurface[idx];
}

//*************************************************************************************************************

MNEBem &MNEBem::operator<<(const MNEBemSurface &surf)
{
    this->m_qListBemSurface.append(surf);
    return *this;
}

//*************************************************************************************************************

MNEBem &MNEBem::operator<<(const MNEBemSurface *surf)
{
    this->m_qListBemSurface.append(*surf);
    return *this;
}
<commit_msg>warning fix<commit_after>//=============================================================================================================
/**
* @file     mne_bem.cpp
* @author   Jana Kiesel <jana.kiesel@tu-ilmenau.de>;
*           Christoph Dinh <chdinh@nmr.mgh.harvard.edu>;
*           Matti Hamalainen <msh@nmr.mgh.harvard.edu>
* @version  1.0
* @date     June, 2015
*
* @section  LICENSE
*
* Copyright (C) 2015, Jana Kiesel, Christoph Dinh and Matti Hamalainen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that
* the following conditions are met:
*     * Redistributions of source code must retain the above copyright notice, this list of conditions and the
*       following disclaimer.
*     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
*       the following disclaimer in the documentation and/or other materials provided with the distribution.
*     * Neither the name of MNE-CPP authors nor the names of its contributors may be used
*       to endorse or promote products derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*
* @brief    MNEBem class implementation.
*
*/

//*************************************************************************************************************
//=============================================================================================================
// INCLUDES
//=============================================================================================================

#include "mne_bem.h"

#include <utils/mnemath.h>
#include <fs/label.h>

//*************************************************************************************************************
//=============================================================================================================
// USED NAMESPACES
//=============================================================================================================

using namespace UTILSLIB;
using namespace FSLIB;
using namespace MNELIB;

//*************************************************************************************************************
//=============================================================================================================
// DEFINE MEMBER METHODS
//=============================================================================================================

MNEBem::MNEBem()
{
}

//*************************************************************************************************************

MNEBem::MNEBem(const MNEBem &p_MNEBem)
: m_qListBemSurface(p_MNEBem.m_qListBemSurface)
{

}

//*************************************************************************************************************

MNEBem::MNEBem(QIODevice &p_IODevice)   //const MNEBem &p_MNEBem
//: m_qListBemSurface()
{
    FiffStream::SPtr t_pStream(new FiffStream(&p_IODevice));
    FiffDirTree t_Tree;

    if(!MNEBem::readFromStream(t_pStream, true, t_Tree, *this))
    {
        t_pStream->device()->close();
        std::cout << "Could not read the bem surfaces\n"; // ToDo throw error
        //ToDo error(me,'Could not read the bem surfaces (%s)',mne_omit_first_line(lasterr));
//        return false;
    }

//    bool testStream =t_pStream->device()->isOpen();
}

//*************************************************************************************************************

MNEBem::~MNEBem()
{

}

//*************************************************************************************************************

void MNEBem::clear()
{
    m_qListBemSurface.clear();
}

//*************************************************************************************************************

bool MNEBem::readFromStream(FiffStream::SPtr& p_pStream, bool add_geom, FiffDirTree& p_Tree, MNEBem& p_Bem)
{
    //
    //   Open the file, create directory
    //
    bool open_here = false;
    QFile t_file;//ToDo TCPSocket;

    if (!p_pStream->device()->isOpen())
    {
        QList<FiffDirEntry> t_Dir;
        QString t_sFileName = p_pStream->streamName();

        t_file.setFileName(t_sFileName);
        p_pStream = FiffStream::SPtr(new FiffStream(&t_file));
        if(!p_pStream->open(p_Tree, t_Dir))
            return false;
        open_here = true;
//        if(t_pDir)
//            delete t_pDir;
    }

    //
    //   Find all BEM surfaces
    //

    QList<FiffDirTree>bem = p_Tree.dir_tree_find(FIFFB_BEM);
    if(bem.isEmpty())
    {
        qCritical() << "No BEM block found!";
        if(open_here)
            p_pStream->device()->close();
        return false;
    }

    QList<FiffDirTree>bemsurf = p_Tree.dir_tree_find(FIFFB_BEM_SURF);
    if(bemsurf.isEmpty())
    {
        qCritical() << "No BEM surfaces found!";
        if(open_here)
            p_pStream->device()->close();
        return false;
    }

    for(int k = 0; k < bemsurf.size(); ++k)
    {
        MNEBemSurface  p_BemSurface;
        printf("\tReading a BEM surface...");
        MNEBem::readBemSurface(p_pStream.data(), bemsurf[k], p_BemSurface);
        p_BemSurface.addTriangleData();
         if (add_geom)
            p_BemSurface.addVertexNormals();
        printf("\t[done]\n" );

        p_Bem.m_qListBemSurface.append(p_BemSurface);
//           src(k) = this;
    }

    printf("\t%d bem surfaces read\n", bemsurf.size());

    if(open_here)
        p_pStream->device()->close();
    return true;
}

//*************************************************************************************************************

bool MNEBem::readBemSurface(FiffStream *p_pStream, const FiffDirTree &p_Tree, MNEBemSurface &p_BemSurface)
{
    p_BemSurface.clear();

    FiffTag::SPtr t_pTag;

    //=====================================================================
    if(!p_Tree.find_tag(p_pStream, FIFF_BEM_SURF_ID, t_pTag))
         p_BemSurface.id = FIFFV_BEM_SURF_ID_UNKNOWN;
    else
         p_BemSurface.id = *t_pTag->toInt();

        qDebug() << "Read BemSurface ID; type:" << t_pTag->getType() << "value:" << *t_pTag->toInt();

    //=====================================================================
    if(!p_Tree.find_tag(p_pStream, FIFF_BEM_SIGMA, t_pTag))
         p_BemSurface.sigma = 1.0;
    else
         p_BemSurface.sigma = *t_pTag->toFloat();

//        qDebug() <<

    //=====================================================================
    if(!p_Tree.find_tag(p_pStream, FIFF_BEM_SURF_NNODE, t_pTag))
    {
        p_pStream->device()->close();
        std::cout << "np not found!";
        return false;
    }
    else
         p_BemSurface.np = *t_pTag->toInt();

//        qDebug() <<

    //=====================================================================
    if(!p_Tree.find_tag(p_pStream, FIFF_BEM_SURF_NTRI, t_pTag))
    {
        p_pStream->device()->close();
        std::cout << "ntri not found!";
        return false;
    }
    else
         p_BemSurface.ntri = *t_pTag->toInt();

//        qDebug() <<

    //=====================================================================
    if(!p_Tree.find_tag(p_pStream, FIFF_MNE_COORD_FRAME, t_pTag))
    {
        qWarning() << "FIFF_MNE_COORD_FRAME not found, trying FIFF_BEM_COORD_FRAME.";
        if(!p_Tree.find_tag(p_pStream, FIFF_BEM_COORD_FRAME, t_pTag))
        {
            p_pStream->device()->close();
            std::cout << "Coordinate frame information not found."; //ToDo: throw error.
            return false;
        }
        else
            p_BemSurface.coord_frame = *t_pTag->toInt();
    }
    else
         p_BemSurface.coord_frame = *t_pTag->toInt();

//        qDebug() <<

    //=====================================================================
    //
    //   Vertices, normals, and triangles
    //
    //=====================================================================
    if(!p_Tree.find_tag(p_pStream, FIFF_BEM_SURF_NODES, t_pTag))
    {
        p_pStream->device()->close();
        std::cout << "Vertex data not found."; //ToDo: throw error.
        return false;
    }

    p_BemSurface.rr = t_pTag->toFloatMatrix().transpose();
    qint32 rows_rr = p_BemSurface.rr.rows();

    if (rows_rr != p_BemSurface.np)
    {
        p_pStream->device()->close();
        std::cout << "Vertex information is incorrect."; //ToDo: throw error.
        return false;
    }
        qDebug() << "Surf Nodes; type:" << t_pTag->getType();

    //=====================================================================
    if(!p_Tree.find_tag(p_pStream, FIFF_BEM_SURF_NORMALS, t_pTag))
    {
        if(!p_Tree.find_tag(p_pStream, FIFF_MNE_SOURCE_SPACE_NORMALS, t_pTag))
        {
            p_pStream->device()->close();
            std::cout << "Vertex normals not found."; //ToDo: throw error.
            return false;
        }

        p_BemSurface.nn = t_pTag->toFloatMatrix().transpose();
    }
    else
    {
        p_BemSurface.nn = t_pTag->toFloatMatrix().transpose();
    }

    if (p_BemSurface.nn.rows() != p_BemSurface.np)
    {
        p_pStream->device()->close();
        std::cout << "Vertex normal information is incorrect."; //ToDo: throw error.
        return false;
    }

    qDebug() << "Bem Vertex Normals; type:" << t_pTag->getType();

    //=====================================================================
    if (p_BemSurface.ntri > 0)
    {
        if(!p_Tree.find_tag(p_pStream, FIFF_BEM_SURF_TRIANGLES, t_pTag))
        {
            if(!p_Tree.find_tag(p_pStream, FIFF_MNE_SOURCE_SPACE_TRIANGLES, t_pTag))
            {
                p_pStream->device()->close();
                std::cout << "Triangulation not found."; //ToDo: throw error.
                return false;
            }
            else
            {
                p_BemSurface.tris = t_pTag->toIntMatrix().transpose();
                p_BemSurface.tris -= MatrixXi::Constant(p_BemSurface.tris.rows(),3,1);//0 based indizes
            }
        }
        else
        {
            p_BemSurface.tris = t_pTag->toIntMatrix().transpose();
            p_BemSurface.tris -= MatrixXi::Constant(p_BemSurface.tris.rows(),3,1);//0 based indizes
        }

        if (p_BemSurface.tris.rows() != p_BemSurface.ntri)
        {
            p_pStream->device()->close();
            std::cout << "Triangulation information is incorrect."; //ToDo: throw error.
            return false;
        }
    }
    else
    {
        MatrixXi p_defaultMatrix(0, 0);
        p_BemSurface.tris = p_defaultMatrix;
    }

    return true;
}

//*************************************************************************************************************

void MNEBem::write(QIODevice &p_IODevice)
{
    //
    //   Open the file, create directory
    //

    // Create the file and save the essentials
    FiffStream::SPtr t_pStream = FiffStream::start_file(p_IODevice);
    printf("Write BEM surface in %s...\n", t_pStream->streamName().toUtf8().constData());
    this->writeToStream(t_pStream.data());
}

//*************************************************************************************************************

void MNEBem::writeToStream(FiffStream* p_pStream)
{
    p_pStream->start_block(FIFFB_BEM);
    for(qint32 h = 0; h < m_qListBemSurface.size(); ++h)
    {
        printf("\tWrite a bem surface... ");
        p_pStream->start_block(FIFFB_BEM_SURF);
        m_qListBemSurface[h].writeToStream(p_pStream);
        p_pStream->end_block(FIFFB_BEM_SURF);
        printf("[done]\n");
    }
    printf("\t%d bem surfaces written\n", m_qListBemSurface.size());
    p_pStream->end_block(FIFFB_BEM);
    p_pStream->end_file();
}

//*************************************************************************************************************

const MNEBemSurface& MNEBem::operator[] (qint32 idx) const
{
    if (idx>=m_qListBemSurface.length())
    {
        qWarning("Warning: Required surface doesn't exist! Returning surface '0'.");
        idx=0;
    }
    return m_qListBemSurface[idx];
}

//*************************************************************************************************************

MNEBemSurface& MNEBem::operator[] (qint32 idx)
{
    if (idx>=m_qListBemSurface.length())
    {
        qWarning("Warning: Required surface doesn't exist! Returning surface '0'.");
        idx=0;
    }
    return m_qListBemSurface[idx];
}

//*************************************************************************************************************

MNEBem &MNEBem::operator<<(const MNEBemSurface &surf)
{
    this->m_qListBemSurface.append(surf);
    return *this;
}

//*************************************************************************************************************

MNEBem &MNEBem::operator<<(const MNEBemSurface *surf)
{
    this->m_qListBemSurface.append(*surf);
    return *this;
}
<|endoftext|>


<commit_before>#include "Geodude.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1App.h"
#include "p2Defs.h"
#include "j1Scene.h"
#include "j1Input.h"
#include "j1Player.h"
#include "j1Item.h"
#include "j1Collision.h"
#include "j1EntityElementsScene.h"

Geodude::Geodude()
{
}

Geodude::~Geodude()
{
}

bool Geodude::Awake(pugi::xml_node &conf, uint id, iPoint pos)
{
	name = conf.attribute("name").as_string("");
	hp = conf.attribute("hp").as_int(0);
	attack = conf.attribute("attack").as_int(0);
	speed = conf.attribute("speed").as_int(0);
	std::string temp = conf.attribute("dir").as_string("");
	if (temp == "up")
		direction = UP;
	else if (temp == "down")
		direction = DOWN;
	else if (temp == "left")
		direction = LEFT;
	else
		direction = RIGHT;

	cooldown = conf.attribute("cooldown").as_int(0);
	mode_stone = conf.attribute("mode_stone").as_bool(false);
	if(mode_stone)
		position = iPoint(pos.x, pos.y);
	else
		position = iPoint(conf.attribute("pos_x").as_int(0), conf.attribute("pos_y").as_int(0));

	return true;
}

bool Geodude::Start()
{
	state = IDLE;
	scale = App->win->GetScale();
	offset_x = 7;
	offset_y = 7;
	gamestate = TIMETOPLAY;
	movable = true;
	collision_feet = App->collision->AddCollider({ position.x, position.y, 15, 15 }, COLLIDER_POKEMON, this);
	timetoplay = SDL_GetTicks();
	reset_distance = false;
	reset_run = true;

	//Get the animations
	animation = *App->anim_manager->GetAnimStruct(4); //id 4 = Geodude

	return true;
}

bool Geodude::Update()
{
	// STATE MACHINE ------------------
	if (gamestate == INGAME)
	{
		switch (state)
		{
		case IDLE:
		{
			Idle();
			break;
		}
		case WALKING:
		{
			Walking();
			break;
		}
		case ATTACKING:
		{
			Attack();
			break;
		}
		case HIT:
		{
			Movebyhit();
			break;
		}
		case DYING:
		{
			Death();
			break;
		}
		default:
		{
			break;
		}
		}
	}

	else if (gamestate == INMENU)
	{

	}
	else if (gamestate == TIMETOPLAY)
	{
		if (SDL_GetTicks() - timetoplay > 1000)
		{
			gamestate = INGAME;
		}
	}

	//Collision follow the player
	collision_feet->SetPos(position.x - offset_x, position.y - offset_y);
	return true;
}

void Geodude::Draw()
{
	BROFILER_CATEGORY("Draw_SOLDIER", Profiler::Color::Yellow)
		//App->anim_manager->Drawing_Manager(state, direction, position, 6);
		int id;
	switch (state)
	{
	case IDLE:
		id = 0;
		break;
	case WALKING:
		id = 1;
		break;
	case ATTACKING:
		id = 2;
		break;
	case DYING:
		id = 3;
		break;
	case HIT:
		id = 3;
		break;
	default:
		break;
	}

	if (direction == UP)
	{
		anim_rect = animation.anim[id].North_action.GetCurrentFrame();
		pivot = animation.anim[id].North_action.GetCurrentOffset();
	}
	else if (direction == DOWN)
	{
		anim_rect = animation.anim[id].South_action.GetCurrentFrame();
		pivot = animation.anim[id].South_action.GetCurrentOffset();
	}
	else if (direction == LEFT)
	{
		anim_rect = animation.anim[id].West_action.GetCurrentFrame();
		pivot = animation.anim[id].West_action.GetCurrentOffset();
	}
	else if (direction == RIGHT)
	{
		anim_rect = animation.anim[id].East_action.GetCurrentFrame();
		pivot = animation.anim[id].East_action.GetCurrentOffset();
	}

	//DRAW
	App->render->Blit(animation.graphics, position.x - pivot.x, position.y - pivot.y, &anim_rect);
}

bool Geodude::CleanUp()
{
	return false;
}

void Geodude::AddItem(Item* item)
{
	item_inside = item;
	item->canBlit = false;
}

void Geodude::Drop_item()
{
	item_inside->canBlit = true;
	item_inside->position.x = position.x;
	item_inside->position.y = position.y;
	item_inside = NULL;
}

bool Geodude::Idle()
{
	if (movable)
	{
		if (reset_run)
		{
			timetorun = SDL_GetTicks();
			reset_run = false;
		}
		else
		{
			if (SDL_GetTicks() - timetorun > 2000)
			{
				int direc_select = rand() % 4 + 1;
				if (direc_select == 1)
				{
					direction = UP;
				}
				else if (direc_select == 2)
				{
					direction = DOWN;
				}
				else if (direc_select == 3)
				{
					direction = LEFT;
				}
				else if (direc_select == 4)
				{
					direction = RIGHT;
				}
				state = WALKING;
				reset_distance = true;
			}
		}
	}
	return true;
}

bool Geodude::Walking()
{
	walking = false;
	if (reset_distance)
	{
		distance = rand() % 60 + 20;
		dis_moved = 0;
		reset_distance = false;
	}
	Move();

	if (dis_moved >= distance)
	{
		walking = false;
		reset_run = true;
	}

	if (walking == false)
	{
		state = IDLE;
	}

	else
	{
		state = WALKING;
	}
	return true;
}

bool Geodude::Move()
{
	if (direction == LEFT)
	{
		//App->map->MovementCost(position.x - speed, position.y, LEFT)
		if (App->map->MovementCost(collision_feet->rect.x - speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT) == 0)
		{
			position.x -= speed;
			dis_moved++;
		}
		else
		{
			//Function to change direction
			dis_moved++;
		}
		walking = true;
	}

	if (direction == RIGHT)
	{
		//App->map->MovementCost(position.x + (speed + width), position.y, RIGHT)
		if (App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT) == 0)
		{
			position.x += speed;
			dis_moved++;
		}
		else
		{
			dis_moved++;
		}
		walking = true;
	}
	if (direction == UP)
	{
		//App->map->MovementCost(position.x, position.y - speed, UP)
		if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - speed, collision_feet->rect.w, collision_feet->rect.h, UP) == 0)
		{
			position.y -= speed;
			dis_moved++;
		}
		else
		{
			dis_moved++;
		}
		walking = true;
	}
	if (direction == DOWN)
	{
		//App->map->MovementCost(position.x, position.y + (speed + height), DOWN)
		if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + speed, collision_feet->rect.w, collision_feet->rect.h, DOWN) == 0)
		{
			position.y += speed;
			dis_moved++;
		}
		else
		{
			dis_moved++;
		}
		walking = true;
	}

	return true;
}

bool Geodude::Attack()
{
	//CHECK IF ATTACK ANIMATION IS FINISHED
	if (animation.anim[state].East_action.Finished() ||
		animation.anim[state].West_action.Finished() ||
		animation.anim[state].North_action.Finished() ||
		animation.anim[state].South_action.Finished())
	{
		state = IDLE;
	}

	return true;
}

bool Geodude::Death()
{
	if (App->scene->player->bombmanager != nullptr)
	{
		iPoint pos;
		pos.create(position.x - offset_x, position.y - offset_y);
		App->scene->items.push_back(App->entity_elements->CreateItem(2, pos));
	}

	App->entity_elements->DeletePokemon(this);
	return true;
}

bool Geodude::Movebyhit()
{
	if (hp <= 0)
	{
		state = DYING;
		return true;
	}

	if (hurt_timer.ReadSec() >= 0.2)
	{
		state = IDLE;
		return true;
	}

	/*
	if (dir_hit == UP)
	{
		//App->map->MovementCost(position.x, position.y - speed, UP)
		if (App->map->MovementCost(position.x, position.y - 10, offset_x, offset_y, UP) == 0)
		{
			position.y -= 10;
		}
		if (position.y < (previus_position.y - 30))
		{
			state = IDLE;
		}
	}
	if (dir_hit == DOWN)
	{
		//App->map->MovementCost(position.x, position.y + (4 + height), DOWN)
		if (App->map->MovementCost(position.x, position.y + 10, offset_x, offset_y, DOWN) == 0)
		{
			position.y += 10;
		}

		if (position.y > (previus_position.y + 30))
		{
			state = IDLE;
		}
	}
	if (dir_hit == LEFT)
	{
		//App->map->MovementCost(position.x - 4, position.y, LEFT)
		if (App->map->MovementCost(position.x - 10, position.y, offset_x, offset_y, LEFT) == 0)
		{
			position.x -= 10;
		}

		if (position.x < (previus_position.x - 30))
		{
			state = IDLE;
		}
	}
	if (dir_hit == RIGHT)
	{
		//App->map->MovementCost(position.x + (speed + width), position.y, RIGHT)
		if (App->map->MovementCost(position.x + 10, position.y, offset_x, offset_y, RIGHT) == 0)
		{
			position.x += 10;
		}
		if (position.x > (previus_position.x + 30))
		{
			state = IDLE;
		}
	}
	*/

	return true;
}

void Geodude::OnCollision(Collider* c1, Collider* c2)
{
	if (c1 != nullptr && c2 != nullptr)
	{
		if (c1 == collision_feet && c2 == App->scene->player->GetCollisionAttack() && state != HIT)
		{
			animation.anim[3].ResetAnimations();
			hurt_timer.Start();
			state = HIT;
			hp--;
		}

		if (c1 == collision_feet && c2->type == COLLIDER_PLAYER && c1->callback->state != HIT)
		{
			state == ATTACKING;
			animation.anim[state].ResetAnimations();
			Orientate();
		}
	}
}<commit_msg>Geodude Attack Animation finished<commit_after>#include "Geodude.h"
#include "j1Render.h"
#include "j1Textures.h"
#include "j1App.h"
#include "p2Defs.h"
#include "j1Scene.h"
#include "j1Input.h"
#include "j1Player.h"
#include "j1Item.h"
#include "j1Collision.h"
#include "j1EntityElementsScene.h"

Geodude::Geodude()
{
}

Geodude::~Geodude()
{
}

bool Geodude::Awake(pugi::xml_node &conf, uint id, iPoint pos)
{
	name = conf.attribute("name").as_string("");
	hp = conf.attribute("hp").as_int(0);
	attack = conf.attribute("attack").as_int(0);
	speed = conf.attribute("speed").as_int(0);
	std::string temp = conf.attribute("dir").as_string("");
	if (temp == "up")
		direction = UP;
	else if (temp == "down")
		direction = DOWN;
	else if (temp == "left")
		direction = LEFT;
	else
		direction = RIGHT;

	cooldown = conf.attribute("cooldown").as_int(0);
	mode_stone = conf.attribute("mode_stone").as_bool(false);
	if(mode_stone)
		position = iPoint(pos.x, pos.y);
	else
		position = iPoint(conf.attribute("pos_x").as_int(0), conf.attribute("pos_y").as_int(0));

	return true;
}

bool Geodude::Start()
{
	state = IDLE;
	scale = App->win->GetScale();
	offset_x = 7;
	offset_y = 7;
	gamestate = TIMETOPLAY;
	movable = true;
	collision_feet = App->collision->AddCollider({ position.x, position.y, 15, 15 }, COLLIDER_POKEMON, this);
	timetoplay = SDL_GetTicks();
	reset_distance = false;
	reset_run = true;

	//Get the animations
	animation = *App->anim_manager->GetAnimStruct(4); //id 4 = Geodude

	return true;
}

bool Geodude::Update()
{
	// STATE MACHINE ------------------
	if (gamestate == INGAME)
	{
		switch (state)
		{
		case IDLE:
		{
			Idle();
			break;
		}
		case WALKING:
		{
			Walking();
			break;
		}
		case ATTACKING:
		{
			Attack();
			break;
		}
		case HIT:
		{
			Movebyhit();
			break;
		}
		case DYING:
		{
			Death();
			break;
		}
		default:
		{
			break;
		}
		}
	}

	else if (gamestate == INMENU)
	{

	}
	else if (gamestate == TIMETOPLAY)
	{
		if (SDL_GetTicks() - timetoplay > 1000)
		{
			gamestate = INGAME;
		}
	}

	//Collision follow the player
	collision_feet->SetPos(position.x - offset_x, position.y - offset_y);
	return true;
}

void Geodude::Draw()
{
	BROFILER_CATEGORY("Draw_SOLDIER", Profiler::Color::Yellow)
		//App->anim_manager->Drawing_Manager(state, direction, position, 6);
		int id;
	switch (state)
	{
	case IDLE:
		id = 0;
		break;
	case WALKING:
		id = 1;
		break;
	case ATTACKING:
		id = 2;
		break;
	case DYING:
		id = 3;
		break;
	case HIT:
		id = 3;
		break;
	default:
		break;
	}

	if (direction == UP)
	{
		anim_rect = animation.anim[id].North_action.GetCurrentFrame();
		pivot = animation.anim[id].North_action.GetCurrentOffset();
	}
	else if (direction == DOWN)
	{
		anim_rect = animation.anim[id].South_action.GetCurrentFrame();
		pivot = animation.anim[id].South_action.GetCurrentOffset();
	}
	else if (direction == LEFT)
	{
		anim_rect = animation.anim[id].West_action.GetCurrentFrame();
		pivot = animation.anim[id].West_action.GetCurrentOffset();
	}
	else if (direction == RIGHT)
	{
		anim_rect = animation.anim[id].East_action.GetCurrentFrame();
		pivot = animation.anim[id].East_action.GetCurrentOffset();
	}

	//DRAW
	App->render->Blit(animation.graphics, position.x - pivot.x, position.y - pivot.y, &anim_rect);
}

bool Geodude::CleanUp()
{
	return false;
}

void Geodude::AddItem(Item* item)
{
	item_inside = item;
	item->canBlit = false;
}

void Geodude::Drop_item()
{
	item_inside->canBlit = true;
	item_inside->position.x = position.x;
	item_inside->position.y = position.y;
	item_inside = NULL;
}

bool Geodude::Idle()
{
	if (movable)
	{
		if (reset_run)
		{
			timetorun = SDL_GetTicks();
			reset_run = false;
		}
		else
		{
			if (SDL_GetTicks() - timetorun > 2000)
			{
				int direc_select = rand() % 4 + 1;
				if (direc_select == 1)
				{
					direction = UP;
				}
				else if (direc_select == 2)
				{
					direction = DOWN;
				}
				else if (direc_select == 3)
				{
					direction = LEFT;
				}
				else if (direc_select == 4)
				{
					direction = RIGHT;
				}
				state = WALKING;
				reset_distance = true;
			}
		}
	}
	return true;
}

bool Geodude::Walking()
{
	walking = false;
	if (reset_distance)
	{
		distance = rand() % 60 + 20;
		dis_moved = 0;
		reset_distance = false;
	}
	Move();

	if (dis_moved >= distance)
	{
		walking = false;
		reset_run = true;
	}

	if (walking == false)
	{
		state = IDLE;
	}

	else
	{
		state = WALKING;
	}
	return true;
}

bool Geodude::Move()
{
	if (direction == LEFT)
	{
		//App->map->MovementCost(position.x - speed, position.y, LEFT)
		if (App->map->MovementCost(collision_feet->rect.x - speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, LEFT) == 0)
		{
			position.x -= speed;
			dis_moved++;
		}
		else
		{
			//Function to change direction
			dis_moved++;
		}
		walking = true;
	}

	if (direction == RIGHT)
	{
		//App->map->MovementCost(position.x + (speed + width), position.y, RIGHT)
		if (App->map->MovementCost(collision_feet->rect.x + collision_feet->rect.w + speed, collision_feet->rect.y, collision_feet->rect.w, collision_feet->rect.h, RIGHT) == 0)
		{
			position.x += speed;
			dis_moved++;
		}
		else
		{
			dis_moved++;
		}
		walking = true;
	}
	if (direction == UP)
	{
		//App->map->MovementCost(position.x, position.y - speed, UP)
		if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y - speed, collision_feet->rect.w, collision_feet->rect.h, UP) == 0)
		{
			position.y -= speed;
			dis_moved++;
		}
		else
		{
			dis_moved++;
		}
		walking = true;
	}
	if (direction == DOWN)
	{
		//App->map->MovementCost(position.x, position.y + (speed + height), DOWN)
		if (App->map->MovementCost(collision_feet->rect.x, collision_feet->rect.y + collision_feet->rect.h + speed, collision_feet->rect.w, collision_feet->rect.h, DOWN) == 0)
		{
			position.y += speed;
			dis_moved++;
		}
		else
		{
			dis_moved++;
		}
		walking = true;
	}

	return true;
}

bool Geodude::Attack()
{
	//CHECK IF ATTACK ANIMATION IS FINISHED
	if (animation.anim[state].East_action.Finished() ||
		animation.anim[state].West_action.Finished() ||
		animation.anim[state].North_action.Finished() ||
		animation.anim[state].South_action.Finished())
	{
		state = IDLE;
	}

	return true;
}

bool Geodude::Death()
{
	if (App->scene->player->bombmanager != nullptr)
	{
		iPoint pos;
		pos.create(position.x - offset_x, position.y - offset_y);
		App->scene->items.push_back(App->entity_elements->CreateItem(2, pos));
	}

	App->entity_elements->DeletePokemon(this);
	return true;
}

bool Geodude::Movebyhit()
{
	if (hp <= 0)
	{
		state = DYING;
		return true;
	}

	if (hurt_timer.ReadSec() >= 0.2)
	{
		state = IDLE;
		return true;
	}

	/*
	if (dir_hit == UP)
	{
		//App->map->MovementCost(position.x, position.y - speed, UP)
		if (App->map->MovementCost(position.x, position.y - 10, offset_x, offset_y, UP) == 0)
		{
			position.y -= 10;
		}
		if (position.y < (previus_position.y - 30))
		{
			state = IDLE;
		}
	}
	if (dir_hit == DOWN)
	{
		//App->map->MovementCost(position.x, position.y + (4 + height), DOWN)
		if (App->map->MovementCost(position.x, position.y + 10, offset_x, offset_y, DOWN) == 0)
		{
			position.y += 10;
		}

		if (position.y > (previus_position.y + 30))
		{
			state = IDLE;
		}
	}
	if (dir_hit == LEFT)
	{
		//App->map->MovementCost(position.x - 4, position.y, LEFT)
		if (App->map->MovementCost(position.x - 10, position.y, offset_x, offset_y, LEFT) == 0)
		{
			position.x -= 10;
		}

		if (position.x < (previus_position.x - 30))
		{
			state = IDLE;
		}
	}
	if (dir_hit == RIGHT)
	{
		//App->map->MovementCost(position.x + (speed + width), position.y, RIGHT)
		if (App->map->MovementCost(position.x + 10, position.y, offset_x, offset_y, RIGHT) == 0)
		{
			position.x += 10;
		}
		if (position.x > (previus_position.x + 30))
		{
			state = IDLE;
		}
	}
	*/

	return true;
}

void Geodude::OnCollision(Collider* c1, Collider* c2)
{
	if (c1 != nullptr && c2 != nullptr)
	{
		if (c1 == collision_feet && c2 == App->scene->player->GetCollisionAttack() && state != HIT)
		{
			animation.anim[3].ResetAnimations();
			hurt_timer.Start();
			state = HIT;
			hp--;
		}

		if (c1 == collision_feet && c2->type == COLLIDER_PLAYER && c1->callback->state != HIT)
		{
			state = ATTACKING;
			animation.anim[state].ResetAnimations();
			Orientate();
		}
	}
}<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkWriter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/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 notice for more information.

=========================================================================*/
#include "vtkWriter.h"

#include "vtkCommand.h"
#include "vtkDataObject.h"

vtkCxxRevisionMacro(vtkWriter, "1.37");

// Construct with no start and end write methods or arguments.
vtkWriter::vtkWriter()
{
}

vtkWriter::~vtkWriter()
{
}

vtkDataObject *vtkWriter::GetInput()
{
  if (this->NumberOfInputs < 1)
    {
    return NULL;
    }
  return this->Inputs[0];
}

// Write data to output. Method executes subclasses WriteData() method, as
// well as StartMethod() and EndMethod() methods.
void vtkWriter::Write()
{
  vtkDataObject *input = this->GetInput();
  int idx;

  // make sure input is available
  if ( !input )
    {
    vtkErrorMacro(<< "No input!");
    return;
    }

  if ( this->NumberOfInputs == 1 )
    {
    if (this->Inputs[0] != NULL)
      {
      this->Inputs[0]->Update();
      }
    }
  else
    {
    // To avoid serlializing execution of pipelines with ports
    // we need to sort the inputs by locality (ascending).
    this->SortInputsByLocality();
    for (idx = 0; idx < this->NumberOfInputs; ++idx)
      {
      if (this->SortedInputs[idx] != NULL)
        {
        this->SortedInputs[idx]->Update();
        }
      }
    }

  unsigned long lastUpdateTime =  this->Inputs[0]->GetUpdateTime();
  for (idx = 1; idx < this->NumberOfInputs; ++idx)
    {
    unsigned long updateTime = this->Inputs[idx]->GetUpdateTime();
    if ( updateTime > lastUpdateTime )
      {
      lastUpdateTime = updateTime;
      }
    }

  if (lastUpdateTime < this->WriteTime && this->GetMTime() < this->WriteTime)
    {
    // we are up to date
    return;
    }

  this->InvokeEvent(vtkCommand::StartEvent,NULL);
  this->WriteData();
  this->InvokeEvent(vtkCommand::EndEvent,NULL);

  // Release any inputs if marked for release
  for (idx = 0; idx < this->NumberOfInputs; ++idx)
    {
    if (this->Inputs[idx] && this->Inputs[idx]->ShouldIReleaseData())
      {
      this->Inputs[idx]->ReleaseData();
      }
    }

  this->WriteTime.Modified();
}

// Convenient alias for Write() method.
void vtkWriter::Update()
{
  this->Write();
}

void vtkWriter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

}

void vtkWriter::EncodeArrayName(char* resname, const char* name)
{
  if ( !name || !resname )
    {
    return;
    }
  int cc = 0;
  ostrstream str;

  char buffer[10];

  while( name[cc] )
    {
    if ( name[cc] < '0' ||
         name[cc] > '9' && name[cc] < 'A' ||
         name[cc] > 'Z' && name[cc] < 'a' ||
         name[cc] > 'z' )
      {
      sprintf(buffer, "%2X", name[cc]);
      str << "%%" << buffer; // Two % because it goes through printf format
      }
    else
      {
      str << name[cc];
      }
    cc++;
    }
  str << ends;
  strcpy(resname, str.str());
  str.rdbuf()->freeze(0);
}
<commit_msg>BUG: The writer was encoding characters like _ and -<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkWriter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/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 notice for more information.

=========================================================================*/
#include "vtkWriter.h"

#include "vtkCommand.h"
#include "vtkDataObject.h"

vtkCxxRevisionMacro(vtkWriter, "1.38");

// Construct with no start and end write methods or arguments.
vtkWriter::vtkWriter()
{
}

vtkWriter::~vtkWriter()
{
}

vtkDataObject *vtkWriter::GetInput()
{
  if (this->NumberOfInputs < 1)
    {
    return NULL;
    }
  return this->Inputs[0];
}

// Write data to output. Method executes subclasses WriteData() method, as
// well as StartMethod() and EndMethod() methods.
void vtkWriter::Write()
{
  vtkDataObject *input = this->GetInput();
  int idx;

  // make sure input is available
  if ( !input )
    {
    vtkErrorMacro(<< "No input!");
    return;
    }

  if ( this->NumberOfInputs == 1 )
    {
    if (this->Inputs[0] != NULL)
      {
      this->Inputs[0]->Update();
      }
    }
  else
    {
    // To avoid serlializing execution of pipelines with ports
    // we need to sort the inputs by locality (ascending).
    this->SortInputsByLocality();
    for (idx = 0; idx < this->NumberOfInputs; ++idx)
      {
      if (this->SortedInputs[idx] != NULL)
        {
        this->SortedInputs[idx]->Update();
        }
      }
    }

  unsigned long lastUpdateTime =  this->Inputs[0]->GetUpdateTime();
  for (idx = 1; idx < this->NumberOfInputs; ++idx)
    {
    unsigned long updateTime = this->Inputs[idx]->GetUpdateTime();
    if ( updateTime > lastUpdateTime )
      {
      lastUpdateTime = updateTime;
      }
    }

  if (lastUpdateTime < this->WriteTime && this->GetMTime() < this->WriteTime)
    {
    // we are up to date
    return;
    }

  this->InvokeEvent(vtkCommand::StartEvent,NULL);
  this->WriteData();
  this->InvokeEvent(vtkCommand::EndEvent,NULL);

  // Release any inputs if marked for release
  for (idx = 0; idx < this->NumberOfInputs; ++idx)
    {
    if (this->Inputs[idx] && this->Inputs[idx]->ShouldIReleaseData())
      {
      this->Inputs[idx]->ReleaseData();
      }
    }

  this->WriteTime.Modified();
}

// Convenient alias for Write() method.
void vtkWriter::Update()
{
  this->Write();
}

void vtkWriter::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os,indent);

}

void vtkWriter::EncodeArrayName(char* resname, const char* name)
{
  if ( !name || !resname )
    {
    return;
    }
  int cc = 0;
  ostrstream str;

  char buffer[10];

  while( name[cc] )
    {
    // Encode spaces and %'s (and most non-printable ascii characters)
    // The reader does not support spaces in array names.
    if ( name[cc] < 33  || name[cc] > 126 ||
         name[cc] == '\"' || name[cc] == '%' )
      {
      sprintf(buffer, "%2X", name[cc]);
      str << "%%" << buffer; // Two % because it goes through printf format
      }
    else
      {
      str << name[cc];
      }
    cc++;
    }
  str << ends;
  strcpy(resname, str.str());
  str.rdbuf()->freeze(0);
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include "sentence.hpp"
#include "modality.hpp"

class modxml {
	public:
		std::string out_path;
		boost::filesystem::path path;
};

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

	modality::parser mod_parser;

	boost::filesystem::directory_iterator pos("/home/junta-m/work/20110324/TeaM/XML/OC");
	boost::filesystem::directory_iterator last;
	std::vector<boost::filesystem::path> xmls;
	for (; pos!=last ; ++pos) {
		boost::filesystem::path p(*pos);
		xmls.push_back(p);
	}

	boost::filesystem::path out_dir("team");
	std::vector<boost::filesystem::path>::iterator it_xml;
	for (it_xml=xmls.begin() ; it_xml!=xmls.end() ; ++it_xml) {
		std::cerr << it_xml->string()<< std::endl;

		std::vector< std::vector< modality::t_token > > oc_sents = mod_parser.parse_OC(it_xml->string());
		std::vector< nlp::sentence > parsed_sents;
		int cnt = 0;
		BOOST_FOREACH ( std::vector< modality::t_token > oc_sent, oc_sents ) {
			nlp::sentence mod_ipa_sent = mod_parser.make_tagged_ipasents( oc_sent );

			std::stringstream ss;
			ss << (out_dir / it_xml->stem()).string() << "_" << std::setw(3) << std::setfill('0') << cnt << ".depmod";
			std::ofstream os(ss.str().c_str());
			os << mod_ipa_sent.cabocha() << std::endl;
			os.close();
			cnt++;
		}
	}

	return true;
}

<commit_msg>Input single xml<commit_after>#include <iostream>
#include <fstream>
#include <sstream>
#include <boost/program_options.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/filesystem.hpp>
#include <boost/foreach.hpp>
#include "sentence.hpp"
#include "modality.hpp"

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

	boost::program_options::options_description opt("Usage");
	opt.add_options()
		("file,f", boost::program_options::value<std::string>(), "input xml file (required)")
		("outdir,o", boost::program_options::value<std::string>(), "output directory (optional): default same as input xml file")
		("help,h", "Show help messages")
		("version,v", "Show version informaion");

	boost::program_options::variables_map argmap;
	boost::program_options::store(parse_command_line(argc, argv, opt), argmap);
	boost::program_options::notify(argmap);

	std::string xml;
	if (argmap.count("file")) {
		xml = argmap["file"].as<std::string>();
	}
	else {
		std::cerr << "error: input xml file is required" << std::endl;
		exit(-1);
	}
	std::cerr << "input: " << xml << std::endl;
	boost::filesystem::path xml_path(xml);

	std::string outdir;
	if (argmap.count("outdir")) {
		outdir = argmap["outdir"].as<std::string>();
	}
	else {
		outdir = xml_path.parent_path().string();
	}
	std::cerr << "outdir: " << outdir << std::endl;
	boost::filesystem::path outdir_path(outdir);

	modality::parser mod_parser;

	std::vector< std::vector< modality::t_token > > oc_sents = mod_parser.parse_OC(xml_path.string());
	std::vector< nlp::sentence > parsed_sents;
	int cnt = 0;
	BOOST_FOREACH ( std::vector< modality::t_token > oc_sent, oc_sents ) {
		nlp::sentence mod_ipa_sent = mod_parser.make_tagged_ipasents( oc_sent );

		std::stringstream ss;
		ss << (outdir_path / xml_path.stem()).string() << "_" << std::setw(3) << std::setfill('0') << cnt << ".depmod";
		std::cerr << "output: " << ss.str() << std::endl;
		std::ofstream os(ss.str().c_str());
		os << mod_ipa_sent.cabocha() << std::endl;
		os.close();
		cnt++;
	}

	return true;
}

<|endoftext|>


<commit_before>#include "offset.h"

bool siren_offset_install(mrb_state* mrb, struct RClass* rclass)
{
  rclass = mrb_define_module(mrb, "Offset");
  mrb_define_class_method(mrb, rclass, "sweep_vec",  siren_offset_sweep_vec,  ARGS_REQ(2));
  mrb_define_class_method(mrb, rclass, "sweep_path", siren_offset_sweep_path, ARGS_REQ(2) | ARGS_OPT(4));
  mrb_define_class_method(mrb, rclass, "loft",       siren_offset_loft,       ARGS_REQ(1));
  return true;
}

mrb_value siren_offset_sweep_vec(mrb_state* mrb, mrb_value self)
{
  mrb_value target, vec;
  int argc = mrb_get_args(mrb, "oA", &target, &vec);

  TopoDS_Shape* profile = siren_shape_get(mrb, target);

  gp_Vec* _vec = siren_vec_get(mrb, vec);
  gp_Pnt _pt = gp_Pnt(0., 0., 0.).Transformed(profile->Location());

  TopoDS_Edge pe = BRepBuilderAPI_MakeEdge(_pt, gp_Pnt(_vec->X(), _vec->Y(), _vec->Z()));
  TopoDS_Wire path = BRepBuilderAPI_MakeWire(pe);

  BRepOffsetAPI_MakePipe mp(path, *profile);
  mp.Build();

  TopoDS_Shape* shape = new TopoDS_Shape();
  *shape = mp.Shape();

  return siren_shape_new(mrb, shape);
}

mrb_value siren_offset_sweep_path(mrb_state* mrb, mrb_value self)
{

  mrb_value target, pathwire;
  mrb_value cont, corr;
  mrb_float scale_first, scale_last;
  int argc = mrb_get_args(mrb, "oo|ooff", &target, &pathwire, &cont, &corr, &scale_first, &scale_last);

  TopoDS_Shape* shape_profile = siren_shape_get(mrb, target);
  TopoDS_Shape* shape_path = siren_shape_get(mrb, pathwire);

  TopoDS_Wire path;

  if (shape_path->ShapeType() == TopAbs_EDGE) {
    path = BRepBuilderAPI_MakeWire(TopoDS::Edge(*shape_path));
  }
  else if (shape_path->ShapeType() == TopAbs_WIRE) {
    path = TopoDS::Wire(*shape_path);
  }
  else {
    static const char m[] = "Path object is not Edge or Wire.";
    return mrb_exc_new(mrb, E_ARGUMENT_ERROR, m, sizeof(m) - 1);
  }

  mrb_value result = mrb_nil_value();

  if (argc >= 3 && argc <= 6) {

    Standard_Boolean withContact = (Standard_Boolean)mrb_test(cont);
    Standard_Boolean withCorrection = (Standard_Boolean)mrb_test(corr);

    BRepOffsetAPI_MakePipeShell ps(path);

    // get params
    Standard_Real fparam, lparam;
    {
      BRepAdaptor_CompCurve cc(path);
      fparam = cc.FirstParameter();
      lparam = cc.LastParameter();
    }

    if (argc < 6) {
      scale_last  = 1.0;
      if (argc < 5) {
        scale_first = 1.0;
      }
    }

    //Handle(Law_Linear) law = new Law_Linear();
    //law->Set(fparam, scale_first, lparam, scale_last);

    Handle(Law_S) law = new Law_S();
    law->Set(fparam, scale_first, lparam, scale_last);

    //Handle(Law_Composite) law = new Law_Composite(fparam, lparam, 1.0e-6);

    // get start point
    TopoDS_Vertex pfirst; {
      TopoDS_Vertex plast;
      TopExp::Vertices(path, pfirst, plast);
    }

    ps.SetLaw(
        *shape_profile, // セクションプロファイル
        law,           // 掃引規則
        pfirst,        // 開始点
        withContact,   // セクションプロファイルを開始点に移動して掃引する
        withCorrection // セクションプロファイルをパスに応じて回転する
        );

    ps.Build();
    TopoDS_Shape* shape = new TopoDS_Shape();
    *shape = ps.Shape();
    result = siren_shape_new(mrb, shape);
  }
  else {
    BRepOffsetAPI_MakePipe mp(path, *shape_profile);
    mp.Build();
    TopoDS_Shape* shape = new TopoDS_Shape();
    *shape = mp.Shape();
    result = siren_shape_new(mrb, shape);
  }
  return result;
}

mrb_value siren_offset_loft(mrb_state* mrb, mrb_value self)
{
  mrb_value objs;
  mrb_bool smooth, is_solid, is_ruled;
  int argc = mrb_get_args(mrb, "A|bbb", &objs, &smooth,  &is_solid, &is_ruled);
  int lsize = mrb_ary_len(mrb, objs);

  if (lsize < 2) {
    static const char m[] = "Number of objects must be over 2 lines.";
    return mrb_exc_new(mrb, E_ARGUMENT_ERROR, m, sizeof(m) - 1);
  }

  Standard_Boolean is_sm, is_s, is_r;
  is_sm = argc < 2 ? Standard_True : (Standard_Boolean)smooth;
  is_s = argc < 3 ? Standard_False : (Standard_Boolean)is_solid;
  is_r = argc < 4 ? Standard_True : (Standard_Boolean)is_ruled;

  BRepOffsetAPI_ThruSections ts(is_s, is_r);

  for (int i=0; i<lsize; i++) {
    mrb_value line = mrb_ary_ref(mrb, objs, i);
    TopoDS_Shape* shape = siren_shape_get(mrb, line);
    TopoDS_Wire w = TopoDS::Wire(*shape);
    ts.AddWire(w);
  }

  ts.SetSmoothing(is_sm);
  ts.Build();

  TopoDS_Shape* shape = new TopoDS_Shape();
  *shape = ts.Shape();

  return siren_shape_new(mrb, shape);
}

<commit_msg>Fix to use boolean type in sweep_path.<commit_after>#include "offset.h"

bool siren_offset_install(mrb_state* mrb, struct RClass* rclass)
{
  rclass = mrb_define_module(mrb, "Offset");
  mrb_define_class_method(mrb, rclass, "sweep_vec",  siren_offset_sweep_vec,  ARGS_REQ(2));
  mrb_define_class_method(mrb, rclass, "sweep_path", siren_offset_sweep_path, ARGS_REQ(2) | ARGS_OPT(4));
  mrb_define_class_method(mrb, rclass, "loft",       siren_offset_loft,       ARGS_REQ(1));
  return true;
}

mrb_value siren_offset_sweep_vec(mrb_state* mrb, mrb_value self)
{
  mrb_value target, vec;
  int argc = mrb_get_args(mrb, "oA", &target, &vec);

  TopoDS_Shape* profile = siren_shape_get(mrb, target);

  gp_Vec* _vec = siren_vec_get(mrb, vec);
  gp_Pnt _pt = gp_Pnt(0., 0., 0.).Transformed(profile->Location());

  TopoDS_Edge pe = BRepBuilderAPI_MakeEdge(_pt, gp_Pnt(_vec->X(), _vec->Y(), _vec->Z()));
  TopoDS_Wire path = BRepBuilderAPI_MakeWire(pe);

  BRepOffsetAPI_MakePipe mp(path, *profile);
  mp.Build();

  TopoDS_Shape* shape = new TopoDS_Shape();
  *shape = mp.Shape();

  return siren_shape_new(mrb, shape);
}

mrb_value siren_offset_sweep_path(mrb_state* mrb, mrb_value self)
{

  mrb_value target, pathwire;
  mrb_bool cont, corr;
  mrb_float scale_first, scale_last;
  int argc = mrb_get_args(mrb, "oo|bbff", &target, &pathwire, &cont, &corr, &scale_first, &scale_last);

  TopoDS_Shape* shape_profile = siren_shape_get(mrb, target);
  TopoDS_Shape* shape_path = siren_shape_get(mrb, pathwire);

  TopoDS_Wire path;

  if (shape_path->ShapeType() == TopAbs_EDGE) {
    path = BRepBuilderAPI_MakeWire(TopoDS::Edge(*shape_path));
  }
  else if (shape_path->ShapeType() == TopAbs_WIRE) {
    path = TopoDS::Wire(*shape_path);
  }
  else {
    static const char m[] = "Path object is not Edge or Wire.";
    return mrb_exc_new(mrb, E_ARGUMENT_ERROR, m, sizeof(m) - 1);
  }

  mrb_value result = mrb_nil_value();

  if (argc >= 3 && argc <= 6) {

    Standard_Boolean withContact = (Standard_Boolean)cont;
    Standard_Boolean withCorrection = (Standard_Boolean)corr;

    BRepOffsetAPI_MakePipeShell ps(path);

    // get params
    Standard_Real fparam, lparam;
    {
      BRepAdaptor_CompCurve cc(path);
      fparam = cc.FirstParameter();
      lparam = cc.LastParameter();
    }

    if (argc < 6) {
      scale_last  = 1.0;
      if (argc < 5) {
        scale_first = 1.0;
      }
    }

    //Handle(Law_Linear) law = new Law_Linear();
    //law->Set(fparam, scale_first, lparam, scale_last);

    Handle(Law_S) law = new Law_S();
    law->Set(fparam, scale_first, lparam, scale_last);

    //Handle(Law_Composite) law = new Law_Composite(fparam, lparam, 1.0e-6);

    // get start point
    TopoDS_Vertex pfirst; {
      TopoDS_Vertex plast;
      TopExp::Vertices(path, pfirst, plast);
    }

    ps.SetLaw(
        *shape_profile, // セクションプロファイル
        law,           // 掃引規則
        pfirst,        // 開始点
        withContact,   // セクションプロファイルを開始点に移動して掃引する
        withCorrection // セクションプロファイルをパスに応じて回転する
        );

    ps.Build();
    TopoDS_Shape* shape = new TopoDS_Shape();
    *shape = ps.Shape();
    result = siren_shape_new(mrb, shape);
  }
  else {
    BRepOffsetAPI_MakePipe mp(path, *shape_profile);
    mp.Build();
    TopoDS_Shape* shape = new TopoDS_Shape();
    *shape = mp.Shape();
    result = siren_shape_new(mrb, shape);
  }
  return result;
}

mrb_value siren_offset_loft(mrb_state* mrb, mrb_value self)
{
  mrb_value objs;
  mrb_bool smooth, is_solid, is_ruled;
  int argc = mrb_get_args(mrb, "A|bbb", &objs, &smooth,  &is_solid, &is_ruled);
  int lsize = mrb_ary_len(mrb, objs);

  if (lsize < 2) {
    static const char m[] = "Number of objects must be over 2 lines.";
    return mrb_exc_new(mrb, E_ARGUMENT_ERROR, m, sizeof(m) - 1);
  }

  Standard_Boolean is_sm, is_s, is_r;
  is_sm = argc < 2 ? Standard_True : (Standard_Boolean)smooth;
  is_s = argc < 3 ? Standard_False : (Standard_Boolean)is_solid;
  is_r = argc < 4 ? Standard_True : (Standard_Boolean)is_ruled;

  BRepOffsetAPI_ThruSections ts(is_s, is_r);

  for (int i=0; i<lsize; i++) {
    mrb_value line = mrb_ary_ref(mrb, objs, i);
    TopoDS_Shape* shape = siren_shape_get(mrb, line);
    TopoDS_Wire w = TopoDS::Wire(*shape);
    ts.AddWire(w);
  }

  ts.SetSmoothing(is_sm);
  ts.Build();

  TopoDS_Shape* shape = new TopoDS_Shape();
  *shape = ts.Shape();

  return siren_shape_new(mrb, shape);
}

<|endoftext|>


<commit_before>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

#ifdef _MSC_VER
#pragma warning( 4: 4786)
#endif

#include "motd.h"
#include "URLManager.h"
#include "TextUtils.h"

MessageOfTheDay::MessageOfTheDay()
{
}

MessageOfTheDay::~MessageOfTheDay()
{

}

const std::string& MessageOfTheDay::get ( const std::string URL )
{
  data = "";
	return data;

  // get all up on the internet and go get the thing
  if (!URLManager::instance().getURL(URL,data)) {
    data = "Default MOTD";
  } else {
    // trim trailing whitespace
    int l = data.size() - 1;
    while (TextUtils::isWhitespace(data[l])) {
      data.erase(l, 1);
      l--;
    }
  }

  return data;
}
<commit_msg>no need to commit my stilly MOTD disable thingy<commit_after>/* bzflag
* Copyright (c) 1993 - 2004 Tim Riker
*
* This package is free software;  you can redistribute it and/or
* modify it under the terms of the license found in the file
* named COPYING that should have accompanied this file.
*
* THIS PACKAGE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
* WARRANTIES OF MERCHANTIBILITY AND FITNESS FOR A PARTICULAR PURPOSE.
*/

#ifdef _MSC_VER
#pragma warning( 4: 4786)
#endif

#include "motd.h"
#include "URLManager.h"
#include "TextUtils.h"

MessageOfTheDay::MessageOfTheDay()
{
}

MessageOfTheDay::~MessageOfTheDay()
{

}

const std::string& MessageOfTheDay::get ( const std::string URL )
{
  data = "";

  // get all up on the internet and go get the thing
  if (!URLManager::instance().getURL(URL,data)) {
    data = "Default MOTD";
  } else {
    // trim trailing whitespace
    int l = data.size() - 1;
    while (TextUtils::isWhitespace(data[l])) {
      data.erase(l, 1);
      l--;
    }
  }

  return data;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <cstring>
using namespace std;

void p(const string & out) { cout << out << endl; }

int main() {
    string inp;
    while(true) {
        getline(cin, inp);
        if(inp == "exit") {
            p("exit");
            return 0;
        } else if(inp.find("move") != string::npos) {
            p(inp);
        } else if(inp.find("status") != string::npos) {
            p("playing white");
        } else if(inp.find("display") != string::npos) {
            p("display");
            for(int c = 0; c < 8; ++c) {
                for(int r = 0; r < 8; ++r) {
                    p(
                      string("") + (char)('A' + c) + string(" ") + (char)('0' + r + 1) + string(" ") +
                      (r % 2 ? "white" : "black") + string(" ") +
                      (c % 2 ? "pawn" : "queen"));
                }
            }
        }
    }
    return 0;
}
<commit_msg>Remove redundant test<commit_after><|endoftext|>


<commit_before>#include "can/canutil.h"
#include "can/canwrite.h"
#include "util/timer.h"
#include "util/statistics.h"
#include "util/log.h"

#define BUS_STATS_LOG_FREQUENCY_S 5
#define CAN_MESSAGE_TOTAL_BIT_SIZE 128

namespace time = openxc::util::time;
namespace statistics = openxc::util::statistics;

using openxc::util::log::debugNoNewline;
using openxc::util::statistics::DeltaStatistic;

const int openxc::can::CAN_ACTIVE_TIMEOUT_S = 30;

void openxc::can::initializeCommon(CanBus* bus) {
    debugNoNewline("Initializing CAN node %d...", bus->address);
    QUEUE_INIT(CanMessage, &bus->receiveQueue);
    QUEUE_INIT(CanMessage, &bus->sendQueue);
    bus->writeHandler = openxc::can::write::sendMessage;
    bus->lastMessageReceived = 0;
#ifdef __LOG_STATS__
    statistics::initialize(&bus->totalMessageStats);
    statistics::initialize(&bus->droppedMessageStats);
    statistics::initialize(&bus->receivedMessageStats);
    statistics::initialize(&bus->receivedDataStats);
    statistics::initialize(&bus->sendQueueStats);
    statistics::initialize(&bus->receiveQueueStats);
#endif // __LOG_STATS__
}

bool openxc::can::busActive(CanBus* bus) {
    return bus->lastMessageReceived != 0 &&
        time::systemTimeMs() - bus->lastMessageReceived < CAN_ACTIVE_TIMEOUT_S * 1000;
}

int lookup(void* key,
        bool (*comparator)(void* key, int index, void* candidates),
        void* candidates, int candidateCount) {
    for(int i = 0; i < candidateCount; i++) {
        if(comparator(key, i, candidates)) {
            return i;
        }
    }
    return -1;
}

bool signalStateNameComparator(void* name, int index, void* states) {
    return !strcmp((const char*)name, ((CanSignalState*)states)[index].name);
}

CanSignalState* openxc::can::lookupSignalState(const char* name, CanSignal* signal,
        CanSignal* signals, int signalCount) {
    int index = lookup((void*)name, signalStateNameComparator,
            (void*)signal->states, signal->stateCount);
    if(index != -1) {
        return &signal->states[index];
    } else {
        return NULL;
    }
}

bool signalStateValueComparator(void* value, int index, void* states) {
    return (*(int*)value) == ((CanSignalState*)states)[index].value;
}

CanSignalState* openxc::can::lookupSignalState(int value, CanSignal* signal,
        CanSignal* signals, int signalCount) {
    int index = lookup((void*)&value, signalStateValueComparator,
            (void*)signal->states, signal->stateCount);
    if(index != -1) {
        return &signal->states[index];
    } else {
        return NULL;
    }
}

bool signalComparator(void* name, int index, void* signals) {
    return !strcmp((const char*)name, ((CanSignal*)signals)[index].genericName);
}

bool writableSignalComparator(void* name, int index, void* signals) {
    return signalComparator(name, index, signals) &&
            ((CanSignal*)signals)[index].writable;
}

CanSignal* openxc::can::lookupSignal(const char* name, CanSignal* signals, int signalCount,
        bool writable) {
    bool (*comparator)(void* key, int index, void* candidates) = signalComparator;
    if(writable) {
        comparator = writableSignalComparator;
    }
    int index = lookup((void*)name, comparator, (void*)signals, signalCount);
    if(index != -1) {
        return &signals[index];
    } else {
        return NULL;
    }
}

CanSignal* openxc::can::lookupSignal(const char* name, CanSignal* signals, int signalCount) {
    return lookupSignal(name, signals, signalCount, false);
}

bool commandComparator(void* name, int index, void* commands) {
    return !strcmp((const char*)name, ((CanCommand*)commands)[index].genericName);
}

CanCommand* openxc::can::lookupCommand(const char* name, CanCommand* commands, int commandCount) {
    int index = lookup((void*)name, commandComparator, (void*)commands,
            commandCount);
    if(index != -1) {
        return &commands[index];
    } else {
        return NULL;
    }
}

void openxc::can::logBusStatistics(CanBus* buses, const int busCount) {
#ifdef __LOG_STATS__
    static unsigned long lastTimeLogged;

    if(time::systemTimeMs() - lastTimeLogged > BUS_STATS_LOG_FREQUENCY_S * 1000) {
        static DeltaStatistic totalMessageStats;
        static DeltaStatistic receivedMessageStats;
        static DeltaStatistic droppedMessageStats;
        static DeltaStatistic recevedDataStats;
        static bool initializedStats = false;
        if(!initializedStats) {
            statistics::initialize(&totalMessageStats);
            statistics::initialize(&receivedMessageStats);
            statistics::initialize(&droppedMessageStats);
            statistics::initialize(&recevedDataStats);
            initializedStats = true;
        }

        int totalMessages = 0;
        int messagesReceived = 0;
        int messagesDropped = 0;
        int dataReceived = 0;
        for(int i = 0; i < busCount; i++) {
            CanBus* bus = &buses[i];

            statistics::update(&bus->receivedDataStats,
                    bus->messagesReceived * CAN_MESSAGE_TOTAL_BIT_SIZE / 8192);
            statistics::update(&bus->totalMessageStats,
                    bus->messagesReceived + bus->messagesDropped);
            statistics::update(&bus->receivedMessageStats,
                    bus->messagesReceived);
            statistics::update(&bus->droppedMessageStats, bus->messagesDropped);

            statistics::update(&bus->sendQueueStats,
                    QUEUE_LENGTH(CanMessage, &bus->sendQueue));
            statistics::update(&bus->receiveQueueStats,
                    QUEUE_LENGTH(CanMessage, &bus->receiveQueue));

            debug("Average CAN message send queue fill percent on bus %d: %f",
                    bus->address,
                    statistics::exponentialMovingAverage(&bus->sendQueueStats)
                        / QUEUE_MAX_LENGTH(CanMessage) * 100);
            debug("CAN message send queue max fill percent on bus %d: %f",
                    bus->address,
                    (float)statistics::maximum(&bus->sendQueueStats) /
                            QUEUE_MAX_LENGTH(CanMessage) * 100)

            debug("Average CAN message receive queue fill percent on bus %d: %f",
                    bus->address,
                    statistics::exponentialMovingAverage(&bus->receiveQueueStats)
                        / QUEUE_MAX_LENGTH(CanMessage) * 100);
            debug("CAN message receive queue max fill percent on bus %d: %f",
                    bus->address,
                    (float) statistics::maximum(&bus->receiveQueueStats) /
                            QUEUE_MAX_LENGTH(CanMessage) * 100);

            debug("CAN messages received on bus %d: %d",
                    bus->address, bus->totalMessageStats.total);
            debug("CAN messages processed on bus %d: %d",
                    bus->address, bus->receivedMessageStats.total);
            debug("CAN messages dropped on bus %d: %d",
                    bus->address, bus->droppedMessageStats.total);
            if(bus->droppedMessageStats.total > 0) {
                debug("Overall dropped message percent: %f (%d / %d)",
                        (float)bus->droppedMessageStats.total / bus->totalMessageStats.total * 100,
                        bus->droppedMessageStats.total,
                        bus->totalMessageStats.total);
            }
            debug("Overall data received on bus %d: %fKB", bus->address,
                    bus->receivedDataStats.total);
            debug("Average throughput on bus %d: %fKB / s", bus->address,
                    statistics::exponentialMovingAverage(&bus->receivedDataStats)
                        / BUS_STATS_LOG_FREQUENCY_S);
            if(bus->droppedMessageStats.total > 0) {
                debug("Average dropped message percent on bus %d: %f", bus->address,
                        statistics::exponentialMovingAverage(&bus->droppedMessageStats) /
                        statistics::exponentialMovingAverage(&bus->totalMessageStats) * 100);
            }

            totalMessages += bus->totalMessageStats.total;
            messagesReceived += bus->messagesReceived;
            messagesDropped += bus->messagesDropped;
            dataReceived += bus->receivedDataStats.total;
        }
        statistics::update(&totalMessageStats, totalMessages);
        statistics::update(&receivedMessageStats, messagesReceived);
        statistics::update(&droppedMessageStats, messagesDropped);
        statistics::update(&recevedDataStats, dataReceived);

        debug("Total CAN messages dropped on all buses: %d",
                droppedMessageStats.total);
        debug("Average message drop rate across all buses: %d msgs / s",
                (int)(statistics::exponentialMovingAverage(&droppedMessageStats)
                    / BUS_STATS_LOG_FREQUENCY_S));
        debug("Dropped message percent across all buses: %f (%d / %d)",
                (float)droppedMessageStats.total / totalMessageStats.total * 100,
                droppedMessageStats.total, totalMessageStats.total);
        debug("Total CAN messages received since startup on all buses: %d",
                totalMessageStats.total);
        debug("Aggregate message rate across all buses since startup: %d msgs / s",
                (int)(statistics::exponentialMovingAverage(&totalMessageStats)
                    / BUS_STATS_LOG_FREQUENCY_S));
        debug("Aggregate throughput across all buses since startup: %fKB / s",
                statistics::exponentialMovingAverage(&recevedDataStats)
                    / BUS_STATS_LOG_FREQUENCY_S);
        debug("Average dropped message percent across all buses: %f",
                statistics::exponentialMovingAverage(&droppedMessageStats) /
                statistics::exponentialMovingAverage(&totalMessageStats) * 100);

        lastTimeLogged = time::systemTimeMs();
    }
#endif // __LOG_STATS__
}

<commit_msg>Fix a stats log output format string.<commit_after>#include "can/canutil.h"
#include "can/canwrite.h"
#include "util/timer.h"
#include "util/statistics.h"
#include "util/log.h"

#define BUS_STATS_LOG_FREQUENCY_S 5
#define CAN_MESSAGE_TOTAL_BIT_SIZE 128

namespace time = openxc::util::time;
namespace statistics = openxc::util::statistics;

using openxc::util::log::debugNoNewline;
using openxc::util::statistics::DeltaStatistic;

const int openxc::can::CAN_ACTIVE_TIMEOUT_S = 30;

void openxc::can::initializeCommon(CanBus* bus) {
    debugNoNewline("Initializing CAN node %d...", bus->address);
    QUEUE_INIT(CanMessage, &bus->receiveQueue);
    QUEUE_INIT(CanMessage, &bus->sendQueue);
    bus->writeHandler = openxc::can::write::sendMessage;
    bus->lastMessageReceived = 0;
#ifdef __LOG_STATS__
    statistics::initialize(&bus->totalMessageStats);
    statistics::initialize(&bus->droppedMessageStats);
    statistics::initialize(&bus->receivedMessageStats);
    statistics::initialize(&bus->receivedDataStats);
    statistics::initialize(&bus->sendQueueStats);
    statistics::initialize(&bus->receiveQueueStats);
#endif // __LOG_STATS__
}

bool openxc::can::busActive(CanBus* bus) {
    return bus->lastMessageReceived != 0 &&
        time::systemTimeMs() - bus->lastMessageReceived < CAN_ACTIVE_TIMEOUT_S * 1000;
}

int lookup(void* key,
        bool (*comparator)(void* key, int index, void* candidates),
        void* candidates, int candidateCount) {
    for(int i = 0; i < candidateCount; i++) {
        if(comparator(key, i, candidates)) {
            return i;
        }
    }
    return -1;
}

bool signalStateNameComparator(void* name, int index, void* states) {
    return !strcmp((const char*)name, ((CanSignalState*)states)[index].name);
}

CanSignalState* openxc::can::lookupSignalState(const char* name, CanSignal* signal,
        CanSignal* signals, int signalCount) {
    int index = lookup((void*)name, signalStateNameComparator,
            (void*)signal->states, signal->stateCount);
    if(index != -1) {
        return &signal->states[index];
    } else {
        return NULL;
    }
}

bool signalStateValueComparator(void* value, int index, void* states) {
    return (*(int*)value) == ((CanSignalState*)states)[index].value;
}

CanSignalState* openxc::can::lookupSignalState(int value, CanSignal* signal,
        CanSignal* signals, int signalCount) {
    int index = lookup((void*)&value, signalStateValueComparator,
            (void*)signal->states, signal->stateCount);
    if(index != -1) {
        return &signal->states[index];
    } else {
        return NULL;
    }
}

bool signalComparator(void* name, int index, void* signals) {
    return !strcmp((const char*)name, ((CanSignal*)signals)[index].genericName);
}

bool writableSignalComparator(void* name, int index, void* signals) {
    return signalComparator(name, index, signals) &&
            ((CanSignal*)signals)[index].writable;
}

CanSignal* openxc::can::lookupSignal(const char* name, CanSignal* signals, int signalCount,
        bool writable) {
    bool (*comparator)(void* key, int index, void* candidates) = signalComparator;
    if(writable) {
        comparator = writableSignalComparator;
    }
    int index = lookup((void*)name, comparator, (void*)signals, signalCount);
    if(index != -1) {
        return &signals[index];
    } else {
        return NULL;
    }
}

CanSignal* openxc::can::lookupSignal(const char* name, CanSignal* signals, int signalCount) {
    return lookupSignal(name, signals, signalCount, false);
}

bool commandComparator(void* name, int index, void* commands) {
    return !strcmp((const char*)name, ((CanCommand*)commands)[index].genericName);
}

CanCommand* openxc::can::lookupCommand(const char* name, CanCommand* commands, int commandCount) {
    int index = lookup((void*)name, commandComparator, (void*)commands,
            commandCount);
    if(index != -1) {
        return &commands[index];
    } else {
        return NULL;
    }
}

void openxc::can::logBusStatistics(CanBus* buses, const int busCount) {
#ifdef __LOG_STATS__
    static unsigned long lastTimeLogged;

    if(time::systemTimeMs() - lastTimeLogged > BUS_STATS_LOG_FREQUENCY_S * 1000) {
        static DeltaStatistic totalMessageStats;
        static DeltaStatistic receivedMessageStats;
        static DeltaStatistic droppedMessageStats;
        static DeltaStatistic recevedDataStats;
        static bool initializedStats = false;
        if(!initializedStats) {
            statistics::initialize(&totalMessageStats);
            statistics::initialize(&receivedMessageStats);
            statistics::initialize(&droppedMessageStats);
            statistics::initialize(&recevedDataStats);
            initializedStats = true;
        }

        int totalMessages = 0;
        int messagesReceived = 0;
        int messagesDropped = 0;
        int dataReceived = 0;
        for(int i = 0; i < busCount; i++) {
            CanBus* bus = &buses[i];

            statistics::update(&bus->receivedDataStats,
                    bus->messagesReceived * CAN_MESSAGE_TOTAL_BIT_SIZE / 8192);
            statistics::update(&bus->totalMessageStats,
                    bus->messagesReceived + bus->messagesDropped);
            statistics::update(&bus->receivedMessageStats,
                    bus->messagesReceived);
            statistics::update(&bus->droppedMessageStats, bus->messagesDropped);

            statistics::update(&bus->sendQueueStats,
                    QUEUE_LENGTH(CanMessage, &bus->sendQueue));
            statistics::update(&bus->receiveQueueStats,
                    QUEUE_LENGTH(CanMessage, &bus->receiveQueue));

            debug("Average CAN message send queue fill percent on bus %d: %f",
                    bus->address,
                    statistics::exponentialMovingAverage(&bus->sendQueueStats)
                        / QUEUE_MAX_LENGTH(CanMessage) * 100);
            debug("CAN message send queue max fill percent on bus %d: %f",
                    bus->address,
                    (float)statistics::maximum(&bus->sendQueueStats) /
                            QUEUE_MAX_LENGTH(CanMessage) * 100)

            debug("Average CAN message receive queue fill percent on bus %d: %f",
                    bus->address,
                    statistics::exponentialMovingAverage(&bus->receiveQueueStats)
                        / QUEUE_MAX_LENGTH(CanMessage) * 100);
            debug("CAN message receive queue max fill percent on bus %d: %f",
                    bus->address,
                    (float) statistics::maximum(&bus->receiveQueueStats) /
                            QUEUE_MAX_LENGTH(CanMessage) * 100);

            debug("CAN messages received on bus %d: %d",
                    bus->address, bus->totalMessageStats.total);
            debug("CAN messages processed on bus %d: %d",
                    bus->address, bus->receivedMessageStats.total);
            debug("CAN messages dropped on bus %d: %d",
                    bus->address, bus->droppedMessageStats.total);
            if(bus->droppedMessageStats.total > 0) {
                debug("Overall dropped message percent: %f (%d / %d)",
                        (float)bus->droppedMessageStats.total / bus->totalMessageStats.total * 100,
                        bus->droppedMessageStats.total,
                        bus->totalMessageStats.total);
            }
            debug("Overall data received on bus %d: %dKB", bus->address,
                    bus->receivedDataStats.total);
            debug("Average throughput on bus %d: %fKB / s", bus->address,
                    statistics::exponentialMovingAverage(&bus->receivedDataStats)
                        / BUS_STATS_LOG_FREQUENCY_S);
            if(bus->droppedMessageStats.total > 0) {
                debug("Average dropped message percent on bus %d: %f", bus->address,
                        statistics::exponentialMovingAverage(&bus->droppedMessageStats) /
                        statistics::exponentialMovingAverage(&bus->totalMessageStats) * 100);
            }

            totalMessages += bus->totalMessageStats.total;
            messagesReceived += bus->messagesReceived;
            messagesDropped += bus->messagesDropped;
            dataReceived += bus->receivedDataStats.total;
        }
        statistics::update(&totalMessageStats, totalMessages);
        statistics::update(&receivedMessageStats, messagesReceived);
        statistics::update(&droppedMessageStats, messagesDropped);
        statistics::update(&recevedDataStats, dataReceived);

        debug("Total CAN messages dropped on all buses: %d",
                droppedMessageStats.total);
        debug("Average message drop rate across all buses: %d msgs / s",
                (int)(statistics::exponentialMovingAverage(&droppedMessageStats)
                    / BUS_STATS_LOG_FREQUENCY_S));
        debug("Dropped message percent across all buses: %f (%d / %d)",
                (float)droppedMessageStats.total / totalMessageStats.total * 100,
                droppedMessageStats.total, totalMessageStats.total);
        debug("Total CAN messages received since startup on all buses: %d",
                totalMessageStats.total);
        debug("Aggregate message rate across all buses since startup: %d msgs / s",
                (int)(statistics::exponentialMovingAverage(&totalMessageStats)
                    / BUS_STATS_LOG_FREQUENCY_S));
        debug("Aggregate throughput across all buses since startup: %fKB / s",
                statistics::exponentialMovingAverage(&recevedDataStats)
                    / BUS_STATS_LOG_FREQUENCY_S);
        debug("Average dropped message percent across all buses: %f",
                statistics::exponentialMovingAverage(&droppedMessageStats) /
                statistics::exponentialMovingAverage(&totalMessageStats) * 100);

        lastTimeLogged = time::systemTimeMs();
    }
#endif // __LOG_STATS__
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: sdobjfac.cxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-19 00:16:46 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#include <svtools/sbx.hxx>

#include <app.hxx>
#include "sdpage.hxx"
#include "sdobjfac.hxx"
#include "glob.hxx"
#include "anminfo.hxx"
#include "imapinfo.hxx"
#include "drawdoc.hxx"

SdObjectFactory aSdObjectFactory;

/*************************************************************************
|*
|* void SdObjectFactory::MakeUserData()
|*
\************************************************************************/

IMPL_LINK( SdObjectFactory, MakeUserData, SdrObjFactory *, pObjFactory )
{
    if ( pObjFactory->nInventor == SdUDInventor )
    {
        SdrObject* pObj = pObjFactory->pObj;

        switch( pObjFactory->nIdentifier )
        {
            case( SD_ANIMATIONINFO_ID ):
            {
                SdDrawDocument* pDoc = NULL;

                if ( pObj )
                    pDoc = (SdDrawDocument*) pObj->GetModel();

                DBG_ASSERT(pDoc, "kein Model gefunden");

                pObjFactory->pNewData = new SdAnimationInfo(pDoc);
            }
            break;

            case( SD_IMAPINFO_ID ):
                pObjFactory->pNewData = new SdIMapInfo;
            break;

            default:
            break;
        }
    }

    if ( pObjFactory->pNewData )
        return 0;

    if( aOldMakeUserDataLink.IsSet() )
        aOldMakeUserDataLink.Call( this );

    return 0;
}

<commit_msg>INTEGRATION: CWS visibility03 (1.1.1.1.764); FILE MERGED 2005/04/01 16:58:28 mhu 1.1.1.1.764.1: #i45006# Replaced includes svtools/sbx*.hxx with basic/sbx*.hxx<commit_after>/*************************************************************************
 *
 *  $RCSfile: sdobjfac.cxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: obo $ $Date: 2005-04-13 09:34:53 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  This library is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (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.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#include <basic/sbx.hxx>

#include <app.hxx>
#include "sdpage.hxx"
#include "sdobjfac.hxx"
#include "glob.hxx"
#include "anminfo.hxx"
#include "imapinfo.hxx"
#include "drawdoc.hxx"

SdObjectFactory aSdObjectFactory;

/*************************************************************************
|*
|* void SdObjectFactory::MakeUserData()
|*
\************************************************************************/

IMPL_LINK( SdObjectFactory, MakeUserData, SdrObjFactory *, pObjFactory )
{
    if ( pObjFactory->nInventor == SdUDInventor )
    {
        SdrObject* pObj = pObjFactory->pObj;

        switch( pObjFactory->nIdentifier )
        {
            case( SD_ANIMATIONINFO_ID ):
            {
                SdDrawDocument* pDoc = NULL;

                if ( pObj )
                    pDoc = (SdDrawDocument*) pObj->GetModel();

                DBG_ASSERT(pDoc, "kein Model gefunden");

                pObjFactory->pNewData = new SdAnimationInfo(pDoc);
            }
            break;

            case( SD_IMAPINFO_ID ):
                pObjFactory->pNewData = new SdIMapInfo;
            break;

            default:
            break;
        }
    }

    if ( pObjFactory->pNewData )
        return 0;

    if( aOldMakeUserDataLink.IsSet() )
        aOldMakeUserDataLink.Call( this );

    return 0;
}

<|endoftext|>