<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "maemoinstalltosysrootstep.h"

#include "maemoglobal.h"
#include "maemopackagecreationstep.h"
#include "maemoqtversion.h"

#include <utils/fileutils.h>

#include <qt4projectmanager/qt4buildconfiguration.h>
#include <qt4projectmanager/qt4target.h>
#include <qtsupport/baseqtversion.h>
#include <remotelinux/deployablefile.h>
#include <remotelinux/deploymentinfo.h>
#include <remotelinux/remotelinuxdeployconfiguration.h>

#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QLatin1Char>
#include <QtCore/QProcess>
#include <QtCore/QWeakPointer>

using namespace ProjectExplorer;
using namespace Qt4ProjectManager;
using namespace RemoteLinux;

namespace Madde {
namespace Internal {

class AbstractMaemoInstallPackageToSysrootWidget : public BuildStepConfigWidget
{
    Q_OBJECT
public:
    AbstractMaemoInstallPackageToSysrootWidget(AbstractMaemoInstallPackageToSysrootStep *step)
        : m_step(step)
    {
        BuildStepList * const list
             = qobject_cast<BuildStepList *>(m_step->parent());
        connect(list, SIGNAL(stepInserted(int)), SIGNAL(updateSummary()));
        connect(list, SIGNAL(stepMoved(int,int)), SIGNAL(updateSummary()));
        connect(list, SIGNAL(aboutToRemoveStep(int)), SLOT(handleStepToBeRemoved(int)));
        connect(list, SIGNAL(stepRemoved(int)), SIGNAL(updateSummary()));
    }

    virtual QString summaryText() const
    {
        if (!m_step->deployConfiguration()->earlierBuildStep<AbstractMaemoPackageCreationStep>(m_step)) {
            return QLatin1String("")
                + tr("Cannot deploy to sysroot: No packaging step found.")
                + QLatin1String("");
        }
        return QLatin1String("") + displayName() + QLatin1String("");
    }

private:
    Q_SLOT void handleStepToBeRemoved(int step)
    {
        BuildStepList * const list
            = qobject_cast<BuildStepList *>(m_step->parent());
        if (list->steps().at(step) == m_step)
            disconnect(list, 0, this, 0);
    }

    const AbstractMaemoInstallPackageToSysrootStep * const m_step;
};

class MaemoInstallDebianPackageToSysrootWidget : public AbstractMaemoInstallPackageToSysrootWidget
{
    Q_OBJECT
public:
    MaemoInstallDebianPackageToSysrootWidget(AbstractMaemoInstallPackageToSysrootStep *step)
        : AbstractMaemoInstallPackageToSysrootWidget(step) {}

    virtual QString displayName() const { return MaemoInstallDebianPackageToSysrootStep::displayName(); }
};

class MaemoInstallRpmPackageToSysrootWidget : public AbstractMaemoInstallPackageToSysrootWidget
{
    Q_OBJECT
public:
    MaemoInstallRpmPackageToSysrootWidget(AbstractMaemoInstallPackageToSysrootStep *step)
        : AbstractMaemoInstallPackageToSysrootWidget(step) {}

    virtual QString displayName() const { return MaemoInstallRpmPackageToSysrootStep::displayName(); }
};

class MaemoCopyFilesToSysrootWidget : public BuildStepConfigWidget
{
    Q_OBJECT
public:
    MaemoCopyFilesToSysrootWidget(const BuildStep *buildStep)
        : m_buildStep(buildStep)
    {
        if (m_buildStep) {
            connect(m_buildStep.data(), SIGNAL(displayNameChanged()),
                SIGNAL(updateSummary()));
        }
    }
    virtual QString summaryText() const {
        return QLatin1String("") + displayName() + QLatin1String(""); }
    virtual QString displayName() const {
        return m_buildStep ? m_buildStep.data()->displayName() : QString();
    }
private:
    const QWeakPointer<const BuildStep> m_buildStep;
};

AbstractMaemoInstallPackageToSysrootStep::AbstractMaemoInstallPackageToSysrootStep(BuildStepList *bsl,
    const QString &id)
        : BuildStep(bsl, id)
{
}

AbstractMaemoInstallPackageToSysrootStep::AbstractMaemoInstallPackageToSysrootStep(BuildStepList *bsl,
    AbstractMaemoInstallPackageToSysrootStep *other)
        : BuildStep(bsl, other)
{
}

RemoteLinuxDeployConfiguration *AbstractMaemoInstallPackageToSysrootStep::deployConfiguration() const
{
    return qobject_cast<RemoteLinuxDeployConfiguration *>(BuildStep::deployConfiguration());
}

bool AbstractMaemoInstallPackageToSysrootStep::init()
{
    const Qt4BuildConfiguration * const bc
        = qobject_cast<Qt4BaseTarget *>(target())->activeQt4BuildConfiguration();
    if (!bc) {
        addOutput(tr("Cannot install to sysroot without build configuration."),
            ErrorMessageOutput);
        return false;
    }

    const AbstractMaemoPackageCreationStep * const pStep
        = deployConfiguration()->earlierBuildStep<AbstractMaemoPackageCreationStep>(this);
    if (!pStep) {
        addOutput(tr("Cannot install package to sysroot without packaging step."),
            ErrorMessageOutput);
        return false;
    }

    if (!bc->qtVersion()) {
        addOutput(tr("Cannot install package to sysroot without a Qt version."),
            ErrorMessageOutput);
        return false;
    }

    m_qmakeCommand = bc->qtVersion()->qmakeCommand();
    m_packageFilePath = pStep->packageFilePath();
    return true;
}

void AbstractMaemoInstallPackageToSysrootStep::run(QFutureInterface<bool> &fi)
{
    m_installerProcess = new QProcess;
    connect(m_installerProcess, SIGNAL(readyReadStandardOutput()),
        SLOT(handleInstallerStdout()));
    connect(m_installerProcess, SIGNAL(readyReadStandardError()),
        SLOT(handleInstallerStderr()));

    emit addOutput(tr("Installing package to sysroot ..."), MessageOutput);
    const int packageFileSize = QFileInfo(m_packageFilePath).size() / (1024*1024);
    const QStringList args = madArguments() << m_packageFilePath;
    MaemoGlobal::callMadAdmin(*m_installerProcess, args, m_qmakeCommand, true);
    if (!m_installerProcess->waitForFinished((2*packageFileSize + 10)*1000)
            || m_installerProcess->exitStatus() != QProcess::NormalExit
            || m_installerProcess->exitCode() != 0) {
        emit addOutput(tr("Installation to sysroot failed, continuing anyway."),
            ErrorMessageOutput);
        if (m_installerProcess->state() != QProcess::NotRunning) {
            m_installerProcess->terminate();
            m_installerProcess->waitForFinished();
            m_installerProcess->kill();
        }
        fi.reportResult(true);
        return;
    }

    fi.reportResult(true);
    m_installerProcess->deleteLater();
    m_installerProcess = 0;
}

void AbstractMaemoInstallPackageToSysrootStep::handleInstallerStdout()
{
    if (m_installerProcess)
        emit addOutput(QString::fromLocal8Bit(m_installerProcess->readAllStandardOutput()), NormalOutput);
}

void AbstractMaemoInstallPackageToSysrootStep::handleInstallerStderr()
{
    if (m_installerProcess)
        emit addOutput(QString::fromLocal8Bit(m_installerProcess->readAllStandardError()), ErrorOutput);
}

MaemoInstallDebianPackageToSysrootStep::MaemoInstallDebianPackageToSysrootStep(BuildStepList *bsl)
    : AbstractMaemoInstallPackageToSysrootStep(bsl, Id)
{
    setDisplayName(displayName());
}

MaemoInstallDebianPackageToSysrootStep::MaemoInstallDebianPackageToSysrootStep(BuildStepList *bsl,
    MaemoInstallDebianPackageToSysrootStep *other)
        : AbstractMaemoInstallPackageToSysrootStep(bsl, other)
{
    setDisplayName(displayName());
}

BuildStepConfigWidget *MaemoInstallDebianPackageToSysrootStep::createConfigWidget()
{
    return new MaemoInstallDebianPackageToSysrootWidget(this);
}

QStringList MaemoInstallDebianPackageToSysrootStep::madArguments() const
{
    return QStringList() << QLatin1String("xdpkg") << QLatin1String("--no-force-downgrade")
        << QLatin1String("-i");
}

const QString MaemoInstallDebianPackageToSysrootStep::Id
    = QLatin1String("MaemoInstallDebianPackageToSysrootStep");

QString MaemoInstallDebianPackageToSysrootStep::displayName()
{
    return tr("Install Debian package to sysroot");
}

MaemoInstallRpmPackageToSysrootStep::MaemoInstallRpmPackageToSysrootStep(BuildStepList *bsl)
    : AbstractMaemoInstallPackageToSysrootStep(bsl, Id)
{
    setDisplayName(displayName());
}

MaemoInstallRpmPackageToSysrootStep::MaemoInstallRpmPackageToSysrootStep(BuildStepList *bsl,
    MaemoInstallRpmPackageToSysrootStep *other)
        : AbstractMaemoInstallPackageToSysrootStep(bsl, other)
{
    setDisplayName(displayName());
}

BuildStepConfigWidget *MaemoInstallRpmPackageToSysrootStep::createConfigWidget()
{
    return new MaemoInstallRpmPackageToSysrootWidget(this);
}

QStringList MaemoInstallRpmPackageToSysrootStep::madArguments() const
{
    return QStringList() << QLatin1String("xrpm") << QLatin1String("-i");
}

const QString MaemoInstallRpmPackageToSysrootStep::Id
    = QLatin1String("MaemoInstallRpmPackageToSysrootStep");

QString MaemoInstallRpmPackageToSysrootStep::displayName()
{
    return tr("Install RPM package to sysroot");
}

MaemoCopyToSysrootStep::MaemoCopyToSysrootStep(BuildStepList *bsl)
    : BuildStep(bsl, Id)
{
    setDisplayName(displayName());
}

MaemoCopyToSysrootStep::MaemoCopyToSysrootStep(BuildStepList *bsl,
    MaemoCopyToSysrootStep *other)
        : BuildStep(bsl, other)
{
    setDisplayName(displayName());
}

bool MaemoCopyToSysrootStep::init()
{
    const Qt4BuildConfiguration * const bc
        = qobject_cast<Qt4BaseTarget *>(target())->activeQt4BuildConfiguration();
    if (!bc) {
        addOutput(tr("Cannot copy to sysroot without build configuration."),
            ErrorMessageOutput);
        return false;
    }

    const MaemoQtVersion * const qtVersion = dynamic_cast<MaemoQtVersion *>(bc->qtVersion());
    if (!qtVersion) {
        addOutput(tr("Cannot copy to sysroot without valid Qt version."),
            ErrorMessageOutput);
        return false;
    }
    m_systemRoot = qtVersion->systemRoot();
    return true;
}

void MaemoCopyToSysrootStep::run(QFutureInterface<bool> &fi)
{
    emit addOutput(tr("Copying files to sysroot ..."), MessageOutput);
    QDir sysrootDir(m_systemRoot);
    const QSharedPointer<DeploymentInfo> deploymentInfo
        = qobject_cast<RemoteLinuxDeployConfiguration *>(deployConfiguration())->deploymentInfo();
    const QChar sep = QLatin1Char('/');
    for (int i = 0; i < deploymentInfo->deployableCount(); ++i) {
        const DeployableFile &deployable = deploymentInfo->deployableAt(i);
        const QFileInfo localFileInfo(deployable.localFilePath);
        const QString targetFilePath = m_systemRoot + sep
            + deployable.remoteDir + sep + localFileInfo.fileName();
        sysrootDir.mkpath(deployable.remoteDir.mid(1));
        QString errorMsg;
        Utils::FileUtils::removeRecursively(targetFilePath, &errorMsg);
        if (!Utils::FileUtils::copyRecursively(deployable.localFilePath,
                targetFilePath, &errorMsg)) {
            emit addOutput(tr("Sysroot installation failed: %1\n"
                " Continuing anyway.").arg(errorMsg), ErrorMessageOutput);
        }
        QCoreApplication::processEvents();
        if (fi.isCanceled()) {
            fi.reportResult(false);
            return;
        }
    }
    fi.reportResult(true);
}

BuildStepConfigWidget *MaemoCopyToSysrootStep::createConfigWidget()
{
    return new MaemoCopyFilesToSysrootWidget(this);
}

const QString MaemoCopyToSysrootStep::Id
    = QLatin1String("MaemoCopyToSysrootStep");
QString MaemoCopyToSysrootStep::displayName()
{
    return tr("Copy files to sysroot");
}

MaemoMakeInstallToSysrootStep::MaemoMakeInstallToSysrootStep(BuildStepList *bsl)
    : AbstractProcessStep(bsl, Id)
{
    setDefaultDisplayName(displayName());
}

MaemoMakeInstallToSysrootStep::MaemoMakeInstallToSysrootStep(BuildStepList *bsl,
        MaemoMakeInstallToSysrootStep *other)
    : AbstractProcessStep(bsl, other)
{
    setDefaultDisplayName(displayName());
}

bool MaemoMakeInstallToSysrootStep::init()
{
    const Qt4BuildConfiguration * const bc
        = qobject_cast<Qt4BuildConfiguration *>(target()->activeBuildConfiguration());
    if (!bc) {
        addOutput("Cannot deploy: No active build dconfiguration.",
            ErrorMessageOutput);
        return false;
    }
    const QtSupport::BaseQtVersion * const qtVersion = bc->qtVersion();
    if (!qtVersion) {
        addOutput("Cannot deploy: Unusable build configuration.",
            ErrorMessageOutput);
        return false;

    }
    Utils::Environment env = bc->environment();
    MaemoGlobal::addMaddeEnvironment(env, qtVersion->qmakeCommand());
    QString command = MaemoGlobal::madCommand(qtVersion->qmakeCommand());
    QStringList args = QStringList() << QLatin1String("-t")
        << MaemoGlobal::targetName(qtVersion->qmakeCommand()) << QLatin1String("make")
        << QLatin1String("install") << (QLatin1String("INSTALL_ROOT=") + qtVersion->systemRoot());
    MaemoGlobal::transformMaddeCall(command, args, qtVersion->qmakeCommand());
    processParameters()->setCommand(command);
    processParameters()->setArguments(args.join(QLatin1String(" ")));
    processParameters()->setEnvironment(env);
    processParameters()->setWorkingDirectory(bc->buildDirectory());
    return true;
}

BuildStepConfigWidget *MaemoMakeInstallToSysrootStep::createConfigWidget()
{
    return new MaemoCopyFilesToSysrootWidget(this);
}

const QString MaemoMakeInstallToSysrootStep::Id
    = QLatin1String("MaemoMakeInstallToSysrootStep");
QString MaemoMakeInstallToSysrootStep::displayName()
{
    return tr("Copy files to sysroot");
}

} // namespace Internal
} // namespace Madde

#include "maemoinstalltosysrootstep.moc"
<commit_msg>Fremantle: Don't use unsupported "mad" option.<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (info@qt.nokia.com)
**
**
** GNU Lesser General Public License Usage
**
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this file.
** Please review the following information to ensure the GNU Lesser General
** Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
** If you have questions regarding the use of this file, please contact
** Nokia at info@qt.nokia.com.
**
**************************************************************************/

#include "maemoinstalltosysrootstep.h"

#include "maemoglobal.h"
#include "maemopackagecreationstep.h"
#include "maemoqtversion.h"
#include "qt4maemotarget.h"

#include <utils/fileutils.h>

#include <qt4projectmanager/qt4buildconfiguration.h>
#include <qt4projectmanager/qt4target.h>
#include <qtsupport/baseqtversion.h>
#include <remotelinux/deployablefile.h>
#include <remotelinux/deploymentinfo.h>
#include <remotelinux/remotelinuxdeployconfiguration.h>

#include <QtCore/QDir>
#include <QtCore/QFileInfo>
#include <QtCore/QLatin1Char>
#include <QtCore/QProcess>
#include <QtCore/QWeakPointer>

using namespace ProjectExplorer;
using namespace Qt4ProjectManager;
using namespace RemoteLinux;

namespace Madde {
namespace Internal {

class AbstractMaemoInstallPackageToSysrootWidget : public BuildStepConfigWidget
{
    Q_OBJECT
public:
    AbstractMaemoInstallPackageToSysrootWidget(AbstractMaemoInstallPackageToSysrootStep *step)
        : m_step(step)
    {
        BuildStepList * const list
             = qobject_cast<BuildStepList *>(m_step->parent());
        connect(list, SIGNAL(stepInserted(int)), SIGNAL(updateSummary()));
        connect(list, SIGNAL(stepMoved(int,int)), SIGNAL(updateSummary()));
        connect(list, SIGNAL(aboutToRemoveStep(int)), SLOT(handleStepToBeRemoved(int)));
        connect(list, SIGNAL(stepRemoved(int)), SIGNAL(updateSummary()));
    }

    virtual QString summaryText() const
    {
        if (!m_step->deployConfiguration()->earlierBuildStep<AbstractMaemoPackageCreationStep>(m_step)) {
            return QLatin1String("")
                + tr("Cannot deploy to sysroot: No packaging step found.")
                + QLatin1String("");
        }
        return QLatin1String("") + displayName() + QLatin1String("");
    }

private:
    Q_SLOT void handleStepToBeRemoved(int step)
    {
        BuildStepList * const list
            = qobject_cast<BuildStepList *>(m_step->parent());
        if (list->steps().at(step) == m_step)
            disconnect(list, 0, this, 0);
    }

    const AbstractMaemoInstallPackageToSysrootStep * const m_step;
};

class MaemoInstallDebianPackageToSysrootWidget : public AbstractMaemoInstallPackageToSysrootWidget
{
    Q_OBJECT
public:
    MaemoInstallDebianPackageToSysrootWidget(AbstractMaemoInstallPackageToSysrootStep *step)
        : AbstractMaemoInstallPackageToSysrootWidget(step) {}

    virtual QString displayName() const { return MaemoInstallDebianPackageToSysrootStep::displayName(); }
};

class MaemoInstallRpmPackageToSysrootWidget : public AbstractMaemoInstallPackageToSysrootWidget
{
    Q_OBJECT
public:
    MaemoInstallRpmPackageToSysrootWidget(AbstractMaemoInstallPackageToSysrootStep *step)
        : AbstractMaemoInstallPackageToSysrootWidget(step) {}

    virtual QString displayName() const { return MaemoInstallRpmPackageToSysrootStep::displayName(); }
};

class MaemoCopyFilesToSysrootWidget : public BuildStepConfigWidget
{
    Q_OBJECT
public:
    MaemoCopyFilesToSysrootWidget(const BuildStep *buildStep)
        : m_buildStep(buildStep)
    {
        if (m_buildStep) {
            connect(m_buildStep.data(), SIGNAL(displayNameChanged()),
                SIGNAL(updateSummary()));
        }
    }
    virtual QString summaryText() const {
        return QLatin1String("") + displayName() + QLatin1String(""); }
    virtual QString displayName() const {
        return m_buildStep ? m_buildStep.data()->displayName() : QString();
    }
private:
    const QWeakPointer<const BuildStep> m_buildStep;
};

AbstractMaemoInstallPackageToSysrootStep::AbstractMaemoInstallPackageToSysrootStep(BuildStepList *bsl,
    const QString &id)
        : BuildStep(bsl, id)
{
}

AbstractMaemoInstallPackageToSysrootStep::AbstractMaemoInstallPackageToSysrootStep(BuildStepList *bsl,
    AbstractMaemoInstallPackageToSysrootStep *other)
        : BuildStep(bsl, other)
{
}

RemoteLinuxDeployConfiguration *AbstractMaemoInstallPackageToSysrootStep::deployConfiguration() const
{
    return qobject_cast<RemoteLinuxDeployConfiguration *>(BuildStep::deployConfiguration());
}

bool AbstractMaemoInstallPackageToSysrootStep::init()
{
    const Qt4BuildConfiguration * const bc
        = qobject_cast<Qt4BaseTarget *>(target())->activeQt4BuildConfiguration();
    if (!bc) {
        addOutput(tr("Cannot install to sysroot without build configuration."),
            ErrorMessageOutput);
        return false;
    }

    const AbstractMaemoPackageCreationStep * const pStep
        = deployConfiguration()->earlierBuildStep<AbstractMaemoPackageCreationStep>(this);
    if (!pStep) {
        addOutput(tr("Cannot install package to sysroot without packaging step."),
            ErrorMessageOutput);
        return false;
    }

    if (!bc->qtVersion()) {
        addOutput(tr("Cannot install package to sysroot without a Qt version."),
            ErrorMessageOutput);
        return false;
    }

    m_qmakeCommand = bc->qtVersion()->qmakeCommand();
    m_packageFilePath = pStep->packageFilePath();
    return true;
}

void AbstractMaemoInstallPackageToSysrootStep::run(QFutureInterface<bool> &fi)
{
    m_installerProcess = new QProcess;
    connect(m_installerProcess, SIGNAL(readyReadStandardOutput()),
        SLOT(handleInstallerStdout()));
    connect(m_installerProcess, SIGNAL(readyReadStandardError()),
        SLOT(handleInstallerStderr()));

    emit addOutput(tr("Installing package to sysroot ..."), MessageOutput);
    const int packageFileSize = QFileInfo(m_packageFilePath).size() / (1024*1024);
    const QStringList args = madArguments() << m_packageFilePath;
    MaemoGlobal::callMadAdmin(*m_installerProcess, args, m_qmakeCommand, true);
    if (!m_installerProcess->waitForFinished((2*packageFileSize + 10)*1000)
            || m_installerProcess->exitStatus() != QProcess::NormalExit
            || m_installerProcess->exitCode() != 0) {
        emit addOutput(tr("Installation to sysroot failed, continuing anyway."),
            ErrorMessageOutput);
        if (m_installerProcess->state() != QProcess::NotRunning) {
            m_installerProcess->terminate();
            m_installerProcess->waitForFinished();
            m_installerProcess->kill();
        }
        fi.reportResult(true);
        return;
    }

    fi.reportResult(true);
    m_installerProcess->deleteLater();
    m_installerProcess = 0;
}

void AbstractMaemoInstallPackageToSysrootStep::handleInstallerStdout()
{
    if (m_installerProcess)
        emit addOutput(QString::fromLocal8Bit(m_installerProcess->readAllStandardOutput()), NormalOutput);
}

void AbstractMaemoInstallPackageToSysrootStep::handleInstallerStderr()
{
    if (m_installerProcess)
        emit addOutput(QString::fromLocal8Bit(m_installerProcess->readAllStandardError()), ErrorOutput);
}

MaemoInstallDebianPackageToSysrootStep::MaemoInstallDebianPackageToSysrootStep(BuildStepList *bsl)
    : AbstractMaemoInstallPackageToSysrootStep(bsl, Id)
{
    setDisplayName(displayName());
}

MaemoInstallDebianPackageToSysrootStep::MaemoInstallDebianPackageToSysrootStep(BuildStepList *bsl,
    MaemoInstallDebianPackageToSysrootStep *other)
        : AbstractMaemoInstallPackageToSysrootStep(bsl, other)
{
    setDisplayName(displayName());
}

BuildStepConfigWidget *MaemoInstallDebianPackageToSysrootStep::createConfigWidget()
{
    return new MaemoInstallDebianPackageToSysrootWidget(this);
}

QStringList MaemoInstallDebianPackageToSysrootStep::madArguments() const
{
    QStringList args;
    args << QLatin1String("xdpkg");
    if (qobject_cast<Qt4HarmattanTarget *>(target()))
        args << QLatin1String("--no-force-downgrade");
    args << QLatin1String("-i");
    return args;
}

const QString MaemoInstallDebianPackageToSysrootStep::Id
    = QLatin1String("MaemoInstallDebianPackageToSysrootStep");

QString MaemoInstallDebianPackageToSysrootStep::displayName()
{
    return tr("Install Debian package to sysroot");
}

MaemoInstallRpmPackageToSysrootStep::MaemoInstallRpmPackageToSysrootStep(BuildStepList *bsl)
    : AbstractMaemoInstallPackageToSysrootStep(bsl, Id)
{
    setDisplayName(displayName());
}

MaemoInstallRpmPackageToSysrootStep::MaemoInstallRpmPackageToSysrootStep(BuildStepList *bsl,
    MaemoInstallRpmPackageToSysrootStep *other)
        : AbstractMaemoInstallPackageToSysrootStep(bsl, other)
{
    setDisplayName(displayName());
}

BuildStepConfigWidget *MaemoInstallRpmPackageToSysrootStep::createConfigWidget()
{
    return new MaemoInstallRpmPackageToSysrootWidget(this);
}

QStringList MaemoInstallRpmPackageToSysrootStep::madArguments() const
{
    return QStringList() << QLatin1String("xrpm") << QLatin1String("-i");
}

const QString MaemoInstallRpmPackageToSysrootStep::Id
    = QLatin1String("MaemoInstallRpmPackageToSysrootStep");

QString MaemoInstallRpmPackageToSysrootStep::displayName()
{
    return tr("Install RPM package to sysroot");
}

MaemoCopyToSysrootStep::MaemoCopyToSysrootStep(BuildStepList *bsl)
    : BuildStep(bsl, Id)
{
    setDisplayName(displayName());
}

MaemoCopyToSysrootStep::MaemoCopyToSysrootStep(BuildStepList *bsl,
    MaemoCopyToSysrootStep *other)
        : BuildStep(bsl, other)
{
    setDisplayName(displayName());
}

bool MaemoCopyToSysrootStep::init()
{
    const Qt4BuildConfiguration * const bc
        = qobject_cast<Qt4BaseTarget *>(target())->activeQt4BuildConfiguration();
    if (!bc) {
        addOutput(tr("Cannot copy to sysroot without build configuration."),
            ErrorMessageOutput);
        return false;
    }

    const MaemoQtVersion * const qtVersion = dynamic_cast<MaemoQtVersion *>(bc->qtVersion());
    if (!qtVersion) {
        addOutput(tr("Cannot copy to sysroot without valid Qt version."),
            ErrorMessageOutput);
        return false;
    }
    m_systemRoot = qtVersion->systemRoot();
    return true;
}

void MaemoCopyToSysrootStep::run(QFutureInterface<bool> &fi)
{
    emit addOutput(tr("Copying files to sysroot ..."), MessageOutput);
    QDir sysrootDir(m_systemRoot);
    const QSharedPointer<DeploymentInfo> deploymentInfo
        = qobject_cast<RemoteLinuxDeployConfiguration *>(deployConfiguration())->deploymentInfo();
    const QChar sep = QLatin1Char('/');
    for (int i = 0; i < deploymentInfo->deployableCount(); ++i) {
        const DeployableFile &deployable = deploymentInfo->deployableAt(i);
        const QFileInfo localFileInfo(deployable.localFilePath);
        const QString targetFilePath = m_systemRoot + sep
            + deployable.remoteDir + sep + localFileInfo.fileName();
        sysrootDir.mkpath(deployable.remoteDir.mid(1));
        QString errorMsg;
        Utils::FileUtils::removeRecursively(targetFilePath, &errorMsg);
        if (!Utils::FileUtils::copyRecursively(deployable.localFilePath,
                targetFilePath, &errorMsg)) {
            emit addOutput(tr("Sysroot installation failed: %1\n"
                " Continuing anyway.").arg(errorMsg), ErrorMessageOutput);
        }
        QCoreApplication::processEvents();
        if (fi.isCanceled()) {
            fi.reportResult(false);
            return;
        }
    }
    fi.reportResult(true);
}

BuildStepConfigWidget *MaemoCopyToSysrootStep::createConfigWidget()
{
    return new MaemoCopyFilesToSysrootWidget(this);
}

const QString MaemoCopyToSysrootStep::Id
    = QLatin1String("MaemoCopyToSysrootStep");
QString MaemoCopyToSysrootStep::displayName()
{
    return tr("Copy files to sysroot");
}

MaemoMakeInstallToSysrootStep::MaemoMakeInstallToSysrootStep(BuildStepList *bsl)
    : AbstractProcessStep(bsl, Id)
{
    setDefaultDisplayName(displayName());
}

MaemoMakeInstallToSysrootStep::MaemoMakeInstallToSysrootStep(BuildStepList *bsl,
        MaemoMakeInstallToSysrootStep *other)
    : AbstractProcessStep(bsl, other)
{
    setDefaultDisplayName(displayName());
}

bool MaemoMakeInstallToSysrootStep::init()
{
    const Qt4BuildConfiguration * const bc
        = qobject_cast<Qt4BuildConfiguration *>(target()->activeBuildConfiguration());
    if (!bc) {
        addOutput("Cannot deploy: No active build dconfiguration.",
            ErrorMessageOutput);
        return false;
    }
    const QtSupport::BaseQtVersion * const qtVersion = bc->qtVersion();
    if (!qtVersion) {
        addOutput("Cannot deploy: Unusable build configuration.",
            ErrorMessageOutput);
        return false;

    }
    Utils::Environment env = bc->environment();
    MaemoGlobal::addMaddeEnvironment(env, qtVersion->qmakeCommand());
    QString command = MaemoGlobal::madCommand(qtVersion->qmakeCommand());
    QStringList args = QStringList() << QLatin1String("-t")
        << MaemoGlobal::targetName(qtVersion->qmakeCommand()) << QLatin1String("make")
        << QLatin1String("install") << (QLatin1String("INSTALL_ROOT=") + qtVersion->systemRoot());
    MaemoGlobal::transformMaddeCall(command, args, qtVersion->qmakeCommand());
    processParameters()->setCommand(command);
    processParameters()->setArguments(args.join(QLatin1String(" ")));
    processParameters()->setEnvironment(env);
    processParameters()->setWorkingDirectory(bc->buildDirectory());
    return true;
}

BuildStepConfigWidget *MaemoMakeInstallToSysrootStep::createConfigWidget()
{
    return new MaemoCopyFilesToSysrootWidget(this);
}

const QString MaemoMakeInstallToSysrootStep::Id
    = QLatin1String("MaemoMakeInstallToSysrootStep");
QString MaemoMakeInstallToSysrootStep::displayName()
{
    return tr("Copy files to sysroot");
}

} // namespace Internal
} // namespace Madde

#include "maemoinstalltosysrootstep.moc"
<|endoftext|>


<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// Generates a track chain aropund the track system
//
// =============================================================================

#include <cstdio>

#include "subsys/trackChain/TrackChain.h"
#include "physics/ChBody.h"

namespace chrono {

TrackChain::TrackChain(const std::string& filename)
{
  FILE* fp = fopen(filename.c_str(), "r");

  char readBuffer[65536];

  fclose(fp);

  Create();
}

int TrackChain::Create()
{
  /*
  // load data
  m_PinDist = d["Pin Distance"].GetDouble();
  m_collision_filename = d["Collision"]["Filename"].GetString();
  m_visual_filename = d["Visualization"]["Filename"].GetString();

  // load visualization mesh
  ChTriangleMeshConnected triangles;
  triangles.LoadWavefrontMesh(utils::GetModelDataFile(m_visual_filename), false, false);
  m_geom_visual = ChSharedPtr<ChTriangleMeshShape>(new ChTriangleMeshShape);
  m_geom_visual->SetMesh(triangles);
  m_geom_visual->SetName("shoe");

  */

  return 0;
}

void TrackChain::Initialize(std::vector<ChBody>& control_bodies,
							std::vector<double> clearance,
							const ChVector<>& start_loc)
{
  // Express the steering reference frame in the absolute coordinate system.
  // ChFrame<> idler_to_abs(location, rotation);
  // idler_to_abs.ConcatenatePreTransformation(chassis->GetFrame_REF_to_abs());

}

void TrackChain::AddVisualizationIdler()
{

}

} // end namespace chrono
<commit_msg>assign values to static variables add geometry assets to a single track shoe<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// Generates a track chain aropund the track system
//
// =============================================================================

#include <cstdio>

#include "TrackChain.h"

#include "physics/ChBody.h"
#include "assets/ChCylinderShape.h"
#include "assets/ChTriangleMeshShape.h"
#include "assets/ChTexture.h"
#include "assets/ChColorAsset.h"

#include "utils/ChUtilsData.h"
#include "utils/ChUtilsInputOutput.h"

namespace chrono {

// static variables
const std::string TrackChain::m_collision_filename = "wheel_L_POV_geom";
const std::string TrackChain::m_visual_filename = utils::GetModelDataFile("hmmwv/wheel_L.obj");

static const double m_mass = 45.0;
static const ChVector<> m_inertia(2.0,3.0,4.0);
static const double m_width_max = 0.4;
static const double m_PinDist = 0.3;		// linear distance between a shoe's two pin joint center
static const double m_th = 0.2;

TrackChain::TrackChain( )
{
  m_shoes.clear();
  m_shoes.push_back(ChSharedPtr<ChBody>(new ChBody));

   // 0 = none, 1 = primitive, 2 = mesh
  m_visType = 0;
  // Attach visualization
  switch (m_visType) {
  case 1:
  {
    ChSharedPtr<ChBoxShape> box(new ChBoxShape);
    box->GetBoxGeometry().SetLengths(ChVector<>(m_PinDist/2.0, m_th/2.0, m_width_max/2.0) );
    m_shoes[0]->AddAsset(box);

    ChSharedPtr<ChTexture> tex(new ChTexture);
    tex->SetTextureFilename(GetChronoDataFile("bluwhite.png"));
    m_shoes[0]->AddAsset(tex);

    break;
  }
  case 2:
  {
    geometry::ChTriangleMeshConnected trimesh;
    trimesh.LoadWavefrontMesh(getMeshFile(), false, false);

    ChSharedPtr<ChTriangleMeshShape> trimesh_shape(new ChTriangleMeshShape);
    trimesh_shape->SetMesh(trimesh);
    trimesh_shape->SetName(getMeshName());
    m_gear->AddAsset(trimesh_shape);

    ChSharedPtr<ChColorAsset> mcolor(new ChColorAsset(0.3f, 0.3f, 0.3f));
    m_gear->AddAsset(mcolor);

    break;
  }
  }
}

int TrackChain::Create()
{
  /*
  // load data
  m_PinDist = d["Pin Distance"].GetDouble();
  m_collision_filename = d["Collision"]["Filename"].GetString();
  m_visual_filename = d["Visualization"]["Filename"].GetString();

  // load visualization mesh
  ChTriangleMeshConnected triangles;
  triangles.LoadWavefrontMesh(utils::GetModelDataFile(m_visual_filename), false, false);
  m_geom_visual = ChSharedPtr<ChTriangleMeshShape>(new ChTriangleMeshShape);
  m_geom_visual->SetMesh(triangles);
  m_geom_visual->SetName("shoe");

  */

  return 0;
}

void TrackChain::Initialize(std::vector<ChBody>& control_bodies,
							std::vector<double> clearance,
							const ChVector<>& start_loc)
{
  // Express the steering reference frame in the absolute coordinate system.
  // ChFrame<> idler_to_abs(location, rotation);
  // idler_to_abs.ConcatenatePreTransformation(chassis->GetFrame_REF_to_abs());

}

void TrackChain::AddVisualizationIdler()
{

}

} // end namespace chrono
<|endoftext|>


<commit_before>/* See other files here for the LICENCE that applies here. */
/* See header file .hpp for info */

#include "otcli.hpp"
#include "othint.hpp"
#include "cmd.hpp"

#include "lib_common1.hpp"

namespace nOT {
namespace nNewcli {

INJECT_OT_COMMON_USING_NAMESPACE_COMMON_1; // <=== namespaces

int cOTCli::Run(const vector<string> args_without_programname) {
	LoadScript("autostart-dev.local", "autostart script"); // todo depending on execution mode? +devel ?

	auto args = args_without_programname;

	int status = 0;
	if (args.size() == 0) {
		throw std::runtime_error("Main program called with 0 arguments (not even program name).");
	}

	size_t nr=0;
	for(auto arg: args) {
		if (arg=="--complete-shell") {
			nOT::nOTHint::cInteractiveShell shell;
			//shell.runEditline();

			using namespace nOT::nNewcli;

			string input = "msg sendfrom rafal";

			shared_ptr<cCmdParser> newcli(new cCmdParser);
			newcli->Test();
			newcli->StartProcessing(input);
			//cCmdProcessing proc = newcli.StartProcessing(input);

		}
		else if (arg=="--complete-one") { // otcli "--complete-one" "ot msg sendfr"
			string v;  bool ok=1;  try { v=args.at(nr+1); } catch(...) { ok=0; } //
			if (ok) {
				nOT::nOTHint::cInteractiveShell shell;
				shell.runOnce(v);
			}
			else {
				_erro("Missing variables for command line argument '"<<arg<<"'");
				status = 1;
			}
		}
		++nr;
	}

	_note("Exiting application with status="<<status);
	return status;
}

bool cOTCli::LoadScript_Main(const std::string &thefile_name) {
	using std::string;
	std::string cmd="";
	std::ifstream thefile( thefile_name.c_str() );
	bool anything=false; // did we run any speciall test
	bool force_continue=false; // should we continue to main program forcefully
	bool read_anything=false;
	while (  (!thefile.eof()) && (thefile.good())  ) {
		getline(thefile, cmd);
		_dbg2("cmd="+cmd);
		if (!read_anything) { read_anything=true; _dbg1("Started reading data from "+thefile_name); }
		if (cmd=="quit") {
			_note("COMMAND: "<<cmd<<" - QUIT");
			return false;
		}
		else if (cmd=="tree") {
			_note("Will test new functions and exit");
			_note("TTTTTTTT");
			nOT::nOTHint::cHintManager hint;
			hint.TestNewFunction_Tree();
			_note("That is all, goodby");
		}
		else if ((cmd=="hello")) {
			_note("COMMAND: Hello world.");
		}
		else if ((cmd=="continue")||(cmd=="cont")) {
			_dbg1("Will continue");
			force_continue = true;
		}
	} // entire file
	bool will_continue = (!anything) || force_continue ;
	if (!will_continue) _note("Will exit then.");
	return will_continue;
} // LocalDeveloperCommands()

void cOTCli::LoadScript(const std::string &script_filename, const std::string &title) {
	_note("Script " + script_filename + " ("+title+")");
	try {
		LoadScript_Main(script_filename);
	}
	catch(const std::exception &e) {
		_erro("\n*** In SCRIPT "+script_filename+" got an exception: " << e.what());
	}
	catch(...) {
		_erro("\n*** In SCRIPT "+script_filename+" got an UNKNOWN exception!");
	}
}

}; // namespace nNewcli
}; // namespace OT

<commit_msg>Use of run arguments<commit_after>/* See other files here for the LICENCE that applies here. */
/* See header file .hpp for info */

#include "otcli.hpp"
#include "othint.hpp"
#include "cmd.hpp"

#include "lib_common1.hpp"

namespace nOT {
namespace nNewcli {

INJECT_OT_COMMON_USING_NAMESPACE_COMMON_1; // <=== namespaces

int cOTCli::Run(const vector<string> args_without_programname) {
	LoadScript("autostart-dev.local", "autostart script"); // todo depending on execution mode? +devel ?

	auto args = args_without_programname;

	int status = 0;
	if (args.size() == 0) {
		throw std::runtime_error("Main program called with 0 arguments (not even program name).");
	}

	size_t nr=0;
	for(auto arg: args) {
		if (arg=="--complete-shell") {
			nOT::nOTHint::cInteractiveShell shell;

			switch (gRunOptions.mRunMode){
				case gRunOptions.eRunModeNormal :
					shell.runEditline();
					break;
				case gRunOptions.eRunModeDemo :
					shell.runEditline();
					break;
				case gRunOptions.eRunModeCurrent :
					using namespace nOT::nNewcli;

					string input = "msg sendfrom rafal";

					shared_ptr<cCmdParser> newcli(new cCmdParser);
					newcli->Test();
					newcli->StartProcessing(input);
					//cCmdProcessing proc = newcli.StartProcessing(input);
					break;
			}
		}
		else if (arg=="--complete-one") { // otcli "--complete-one" "ot msg sendfr"
			string v;  bool ok=1;  try { v=args.at(nr+1); } catch(...) { ok=0; } //
			if (ok) {
				nOT::nOTHint::cInteractiveShell shell;
				shell.runOnce(v);
			}
			else {
				_erro("Missing variables for command line argument '"<<arg<<"'");
				status = 1;
			}
		}
		++nr;
	}

	_note("Exiting application with status="<<status);
	return status;
}

bool cOTCli::LoadScript_Main(const std::string &thefile_name) {
	using std::string;
	std::string cmd="";
	std::ifstream thefile( thefile_name.c_str() );
	bool anything=false; // did we run any speciall test
	bool force_continue=false; // should we continue to main program forcefully
	bool read_anything=false;
	while (  (!thefile.eof()) && (thefile.good())  ) {
		getline(thefile, cmd);
		_dbg2("cmd="+cmd);
		if (!read_anything) { read_anything=true; _dbg1("Started reading data from "+thefile_name); }
		if (cmd=="quit") {
			_note("COMMAND: "<<cmd<<" - QUIT");
			return false;
		}
		else if (cmd=="tree") {
			_note("Will test new functions and exit");
			_note("TTTTTTTT");
			nOT::nOTHint::cHintManager hint;
			hint.TestNewFunction_Tree();
			_note("That is all, goodby");
		}
		else if ((cmd=="hello")) {
			_note("COMMAND: Hello world.");
		}
		else if ((cmd=="continue")||(cmd=="cont")) {
			_dbg1("Will continue");
			force_continue = true;
		}
	} // entire file
	bool will_continue = (!anything) || force_continue ;
	if (!will_continue) _note("Will exit then.");
	return will_continue;
} // LocalDeveloperCommands()

void cOTCli::LoadScript(const std::string &script_filename, const std::string &title) {
	_note("Script " + script_filename + " ("+title+")");
	try {
		LoadScript_Main(script_filename);
	}
	catch(const std::exception &e) {
		_erro("\n*** In SCRIPT "+script_filename+" got an exception: " << e.what());
	}
	catch(...) {
		_erro("\n*** In SCRIPT "+script_filename+" got an UNKNOWN exception!");
	}
}

}; // namespace nNewcli
}; // namespace OT

<|endoftext|>


<commit_before>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX24T グループ・ICUb 定義 @n
			Copyright 2016 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/io_utils.hpp"

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ICUA 定義基底クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	struct icu_t {

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  ベクター・インデックス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		enum class VECTOR {
			BUSERR = 16,  // BSC

			FRDYI  = 23,  // FCU

			SWINT  = 27,  // ICU

			CMI0   = 28,  // CMT0
			CMI1   = 29,  // CMT1
			CMW2   = 30,  // CMT2
			CMW3   = 31,  // CMT3

			FEPRF  = 32,  // CAC
			MENDF  = 33,  // CAC
			OVFF   = 34,  // CAC

			SPEI0  = 44,  // RSPI0
			SPRI0  = 45,  // RSPI0
			SPTI0  = 46,  // RSPI0
			SPII0  = 47,  // RSPI0

			DOPCF  = 57,  // DOC

			IRQ0   = 64,  // ICU
			IRQ1   = 65,
			IRQ2   = 66,
			IRQ3   = 67,
			IRQ4   = 68,
			IRQ5   = 69,
			IRQ6   = 70,
			IRQ7   = 71,

			LVD1   = 88,   // LVD
			LVD2   = 89,   // LVD

			ERI1   = 218,  // SCI1
			RXI1   = 219,  // SCI1
			TXI1   = 220,  // SCI1
			TEI1   = 221,  // SCI1
			ERI5   = 222,  // SCI5
			RXI5   = 223,  // SCI5
			TXI5   = 224,  // SCI5
			TEI5   = 225,  // SCI5
			ERI6   = 226,  // SCI6
			RXI6   = 227,  // SCI6
			TXI6   = 228,  // SCI6
			TEI6   = 229,  // SCI6

			EEI0   = 246,  // RIIC0
			RXI0   = 247,  // RIIC0
			TXI0   = 248,  // RIIC0
			TEI0   = 249,  // RIIC0
		};

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  IR レジスタ
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <uint32_t base>
		struct ir_t {
			rw8_t<base + 28> CMI0;
			rw8_t<base + 29> CMI1;
			rw8_t<base + 30> CMI2;
			rw8_t<base + 31> CMI3;

			rw8_t<base + 44> SPEI0;
			rw8_t<base + 45> SPRI0;
			rw8_t<base + 46> SPTI0;
			rw8_t<base + 47> SPII0;

			rw8_t<base + 218> ERI1;
			rw8_t<base + 219> RXI1;
			rw8_t<base + 220> TXI1;
			rw8_t<base + 221> TEI1;

			rw8_t<base + 222> ERI5;
			rw8_t<base + 223> RXI5;
			rw8_t<base + 224> TXI5;
			rw8_t<base + 225> TEI5;

			rw8_t<base + 226> ERI6;
			rw8_t<base + 227> RXI6;
			rw8_t<base + 228> TXI6;
			rw8_t<base + 229> TEI6;

			rw8_t<base + 246> ERI0;
			rw8_t<base + 247> RXI0;
			rw8_t<base + 248> TXI0;
			rw8_t<base + 249> TEI0;
		};
		static ir_t<0x00087010> IR;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  IER レジスタ
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <uint32_t base>
		struct ier_t {
			typedef rw8_t<base + 0x02> ier02;
			bit_rw_t<ier02, bitpos::B0>	BUSERR;
			bit_rw_t<ier02, bitpos::B7>	FRDYI;

			typedef rw8_t<base + 0x03> ier03;
			bit_rw_t<ier03, bitpos::B3>	SWINT;
			bit_rw_t<ier03, bitpos::B4>	CMI0;
			bit_rw_t<ier03, bitpos::B5>	CMI1;
			bit_rw_t<ier03, bitpos::B6>	CMI2;
			bit_rw_t<ier03, bitpos::B7>	CMI3;

			typedef rw8_t<base + 0x05> ier05;
			bit_rw_t<ier03, bitpos::B4>	SPEI0;
			bit_rw_t<ier03, bitpos::B5>	SPRI0;
			bit_rw_t<ier03, bitpos::B6>	SPTI0;
			bit_rw_t<ier03, bitpos::B7>	SPII0;

			typedef rw8_t<base + 0x08> ier08;
			bit_rw_t<ier08, bitpos::B0>	IRQ0;
			bit_rw_t<ier08, bitpos::B1>	IRQ1;
			bit_rw_t<ier08, bitpos::B2>	IRQ2;
			bit_rw_t<ier08, bitpos::B3>	IRQ3;
			bit_rw_t<ier08, bitpos::B4>	IRQ4;
			bit_rw_t<ier08, bitpos::B5>	IRQ5;
			bit_rw_t<ier08, bitpos::B6>	IRQ6;
			bit_rw_t<ier08, bitpos::B7>	IRQ7;

			typedef rw8_t<base + 0x1B> ier1b;
			bit_rw_t<ier1b, bitpos::B2>	ERI1;
			bit_rw_t<ier1b, bitpos::B3>	RXI1;
			bit_rw_t<ier1b, bitpos::B4>	TXI1;
			bit_rw_t<ier1b, bitpos::B5>	TEI1;
			bit_rw_t<ier1b, bitpos::B6>	ERI5;
			bit_rw_t<ier1b, bitpos::B7>	RXI5;
			typedef rw8_t<base + 0x1C> ier1c;
			bit_rw_t<ier1c, bitpos::B0>	TXI5;
			bit_rw_t<ier1c, bitpos::B1>	TEI5;
			bit_rw_t<ier1c, bitpos::B2>	ERI6;
			bit_rw_t<ier1c, bitpos::B3>	RXI6;
			bit_rw_t<ier1c, bitpos::B4>	TXI6;
			bit_rw_t<ier1c, bitpos::B5>	TEI6;

			typedef rw8_t<base + 0x1E> ier1e;
			bit_rw_t<ier1e, bitpos::B6>	EEI0;
			bit_rw_t<ier1e, bitpos::B7>	RXI0;
			typedef rw8_t<base + 0x1F> ier1f;
			bit_rw_t<ier1f, bitpos::B0>	TXI0;
			bit_rw_t<ier1f, bitpos::B1>	TEI0;
		};
		static ier_t<0x00087200> IER;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  IPR レジスタ @n
					全て、下位４ビットが有効
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <uint32_t base>
		struct ipr_t {

			rw8_t<base + 4> CMI0;
			rw8_t<base + 5> CMI1;
			rw8_t<base + 6> CMI2;
			rw8_t<base + 7> CMI3;

			rw8_t<base + 44> RSPI0;

			rw8_t<base + 218> SCI1;
			rw8_t<base + 222> SCI5;
			rw8_t<base + 226> SCI6;

			rw8_t<base + 246> EEI0;
			rw8_t<base + 247> RXI0;
			rw8_t<base + 248> TXI0;
			rw8_t<base + 249> TEI0;
		};
		static ipr_t<0x00087300> IPR;

	};
	typedef icu_t ICU;
}
<commit_msg>update CMI2, CMI3<commit_after>#pragma once
//=====================================================================//
/*!	@file
	@brief	RX24T グループ・ICUb 定義 @n
			Copyright 2016 Kunihito Hiramatsu
	@author	平松邦仁 (hira@rvf-rc45.net)
*/
//=====================================================================//
#include "common/io_utils.hpp"

namespace device {

	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	/*!
		@brief  ICUA 定義基底クラス
	*/
	//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
	struct icu_t {

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  ベクター・インデックス
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		enum class VECTOR {
			BUSERR = 16,  // BSC

			FRDYI  = 23,  // FCU

			SWINT  = 27,  // ICU

			CMI0   = 28,  // CMT0
			CMI1   = 29,  // CMT1
			CMI2   = 30,  // CMT2
			CMI3   = 31,  // CMT3

			FEPRF  = 32,  // CAC
			MENDF  = 33,  // CAC
			OVFF   = 34,  // CAC

			SPEI0  = 44,  // RSPI0
			SPRI0  = 45,  // RSPI0
			SPTI0  = 46,  // RSPI0
			SPII0  = 47,  // RSPI0

			DOPCF  = 57,  // DOC

			IRQ0   = 64,  // ICU
			IRQ1   = 65,
			IRQ2   = 66,
			IRQ3   = 67,
			IRQ4   = 68,
			IRQ5   = 69,
			IRQ6   = 70,
			IRQ7   = 71,

			LVD1   = 88,   // LVD
			LVD2   = 89,   // LVD

			ERI1   = 218,  // SCI1
			RXI1   = 219,  // SCI1
			TXI1   = 220,  // SCI1
			TEI1   = 221,  // SCI1
			ERI5   = 222,  // SCI5
			RXI5   = 223,  // SCI5
			TXI5   = 224,  // SCI5
			TEI5   = 225,  // SCI5
			ERI6   = 226,  // SCI6
			RXI6   = 227,  // SCI6
			TXI6   = 228,  // SCI6
			TEI6   = 229,  // SCI6

			EEI0   = 246,  // RIIC0
			RXI0   = 247,  // RIIC0
			TXI0   = 248,  // RIIC0
			TEI0   = 249,  // RIIC0
		};

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  IR レジスタ
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <uint32_t base>
		struct ir_t {
			rw8_t<base + 28> CMI0;
			rw8_t<base + 29> CMI1;
			rw8_t<base + 30> CMI2;
			rw8_t<base + 31> CMI3;

			rw8_t<base + 44> SPEI0;
			rw8_t<base + 45> SPRI0;
			rw8_t<base + 46> SPTI0;
			rw8_t<base + 47> SPII0;

			rw8_t<base + 218> ERI1;
			rw8_t<base + 219> RXI1;
			rw8_t<base + 220> TXI1;
			rw8_t<base + 221> TEI1;

			rw8_t<base + 222> ERI5;
			rw8_t<base + 223> RXI5;
			rw8_t<base + 224> TXI5;
			rw8_t<base + 225> TEI5;

			rw8_t<base + 226> ERI6;
			rw8_t<base + 227> RXI6;
			rw8_t<base + 228> TXI6;
			rw8_t<base + 229> TEI6;

			rw8_t<base + 246> ERI0;
			rw8_t<base + 247> RXI0;
			rw8_t<base + 248> TXI0;
			rw8_t<base + 249> TEI0;
		};
		static ir_t<0x00087010> IR;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  IER レジスタ
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <uint32_t base>
		struct ier_t {
			typedef rw8_t<base + 0x02> ier02;
			bit_rw_t<ier02, bitpos::B0>	BUSERR;
			bit_rw_t<ier02, bitpos::B7>	FRDYI;

			typedef rw8_t<base + 0x03> ier03;
			bit_rw_t<ier03, bitpos::B3>	SWINT;
			bit_rw_t<ier03, bitpos::B4>	CMI0;
			bit_rw_t<ier03, bitpos::B5>	CMI1;
			bit_rw_t<ier03, bitpos::B6>	CMI2;
			bit_rw_t<ier03, bitpos::B7>	CMI3;

			typedef rw8_t<base + 0x05> ier05;
			bit_rw_t<ier03, bitpos::B4>	SPEI0;
			bit_rw_t<ier03, bitpos::B5>	SPRI0;
			bit_rw_t<ier03, bitpos::B6>	SPTI0;
			bit_rw_t<ier03, bitpos::B7>	SPII0;

			typedef rw8_t<base + 0x08> ier08;
			bit_rw_t<ier08, bitpos::B0>	IRQ0;
			bit_rw_t<ier08, bitpos::B1>	IRQ1;
			bit_rw_t<ier08, bitpos::B2>	IRQ2;
			bit_rw_t<ier08, bitpos::B3>	IRQ3;
			bit_rw_t<ier08, bitpos::B4>	IRQ4;
			bit_rw_t<ier08, bitpos::B5>	IRQ5;
			bit_rw_t<ier08, bitpos::B6>	IRQ6;
			bit_rw_t<ier08, bitpos::B7>	IRQ7;

			typedef rw8_t<base + 0x1B> ier1b;
			bit_rw_t<ier1b, bitpos::B2>	ERI1;
			bit_rw_t<ier1b, bitpos::B3>	RXI1;
			bit_rw_t<ier1b, bitpos::B4>	TXI1;
			bit_rw_t<ier1b, bitpos::B5>	TEI1;
			bit_rw_t<ier1b, bitpos::B6>	ERI5;
			bit_rw_t<ier1b, bitpos::B7>	RXI5;
			typedef rw8_t<base + 0x1C> ier1c;
			bit_rw_t<ier1c, bitpos::B0>	TXI5;
			bit_rw_t<ier1c, bitpos::B1>	TEI5;
			bit_rw_t<ier1c, bitpos::B2>	ERI6;
			bit_rw_t<ier1c, bitpos::B3>	RXI6;
			bit_rw_t<ier1c, bitpos::B4>	TXI6;
			bit_rw_t<ier1c, bitpos::B5>	TEI6;

			typedef rw8_t<base + 0x1E> ier1e;
			bit_rw_t<ier1e, bitpos::B6>	EEI0;
			bit_rw_t<ier1e, bitpos::B7>	RXI0;
			typedef rw8_t<base + 0x1F> ier1f;
			bit_rw_t<ier1f, bitpos::B0>	TXI0;
			bit_rw_t<ier1f, bitpos::B1>	TEI0;
		};
		static ier_t<0x00087200> IER;

		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		/*!
			@brief  IPR レジスタ @n
					全て、下位４ビットが有効
		*/
		//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++//
		template <uint32_t base>
		struct ipr_t {

			rw8_t<base + 4> CMI0;
			rw8_t<base + 5> CMI1;
			rw8_t<base + 6> CMI2;
			rw8_t<base + 7> CMI3;

			rw8_t<base + 44> RSPI0;

			rw8_t<base + 218> SCI1;
			rw8_t<base + 222> SCI5;
			rw8_t<base + 226> SCI6;

			rw8_t<base + 246> EEI0;
			rw8_t<base + 247> RXI0;
			rw8_t<base + 248> TXI0;
			rw8_t<base + 249> TEI0;
		};
		static ipr_t<0x00087300> IPR;

	};
	typedef icu_t ICU;
}
<|endoftext|>


<commit_before>//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation.  All rights reserved.
// See LICENSE file in the project root for full license information.
//

#include <nanoHAL.h>
#include <target_platform.h>
#include <esp32_idf.h>

//
//  Allocate Memory for Managed heap
//
//  if spiRam is available then use all available ram - SPI_ALLOW_FREE
//
//  if no spiRam or spiRam malloc fails then malloc from normal ram
//
//  The CLR calls this multiple times. Once memory is allocated return the same memory for all
//  subsequent calls.

static const char *TAG = "Memory";

// Space to leave free in SPIRAM for allocation by IDF malloc
#define SPIRAM_MEMORY_LEAVE_FOR_ALLOCATION (256 * 1024)

// You can't go much bigger than this when allocating in internal memory to
// get memory in one continuous lump.
#if defined(HAL_USE_BLE)
#define INTERNAL_MEMORY_SIZE (54 * 1024) // Reduce Managed heap if using BLE without spiram
#else
#define INTERNAL_MEMORY_SIZE (84 * 1024)
#endif

// Saved memory allocation for when heap is reset so we can return same value.
unsigned char *pManagedHeap = NULL;
size_t managedHeapSize = 0;

extern "C"
{
    typedef portMUX_TYPE multi_heap_lock_t;
#include <heap_private.h>

    extern struct registered_heap_ll registered_heaps;
}

void print_heap_info(uint32_t caps)
{
    multi_heap_info_t info;

    debug_printf("Heap summary for capabilities 0x%08X:\n", caps);

    heap_t *heap;

    SLIST_FOREACH(heap, &registered_heaps, next)
    {
        if (heap_caps_match(heap, caps))
        {
            multi_heap_get_info(heap->heap, &info);

            debug_printf(
                "  At 0x%08x len %d free %d allocated %d min_free %d\n",
                heap->start,
                heap->end - heap->start,
                info.total_free_bytes,
                info.total_allocated_bytes,
                info.minimum_free_bytes);
            debug_printf(
                "    largest_free_block %d alloc_blocks %d free_blocks %d total_blocks %d\n",
                info.largest_free_block,
                info.allocated_blocks,
                info.free_blocks,
                info.total_blocks);
        }
    }

    debug_printf("  Totals:\n");
    heap_caps_get_info(&info, caps);

    debug_printf(
        "    free %d allocated %d min_free %d largest_free_block %d\n",
        info.total_free_bytes,
        info.total_allocated_bytes,
        info.minimum_free_bytes,
        info.largest_free_block);
}

//
//	Return the location and size of the managed heap
//  If called a 2nd time then always return same value
//
void HeapLocation(unsigned char *&baseAddress, unsigned int &sizeInBytes)
{
    NATIVE_PROFILE_PAL_HEAP();

    // Memory allocated yet ?
    if (pManagedHeap == NULL)
    {
        // Memory size to allocate in normal memory if PSRAM not available
        managedHeapSize = INTERNAL_MEMORY_SIZE;

        //////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////
        // uncomment, in case there is a need to check the heap info
        // print_heap_info(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
        //////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////

        // See if we have any SPIRAM
        size_t spiramMaxSize = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_32BIT | MALLOC_CAP_SPIRAM);

        // Sanity check - Make sure there is at least managedHeapSize available in SPIRAM
        if (spiramMaxSize)
        {
            // Allocate heap from SPIRAM
            managedHeapSize = spiramMaxSize - SPIRAM_MEMORY_LEAVE_FOR_ALLOCATION;

            pManagedHeap = (unsigned char *)heap_caps_malloc(
                managedHeapSize,
                MALLOC_CAP_8BIT | MALLOC_CAP_32BIT | MALLOC_CAP_SPIRAM);

            if (pManagedHeap)
            {
                // managed heap successfully allocated from SPIRAM
                ESP_LOGI(TAG, "Managed heap allocated from SPIRAM: %d (from max:%d)", managedHeapSize, spiramMaxSize);
            }
            else
            {
                // failed to allocation managed heap from SPIRAM
                ESP_LOGI(TAG, "Failed to allocate managed heap from SPIRAM");
            }
        }

        while (pManagedHeap == NULL)
        {
            // Allocate heap from Internal RAM
            pManagedHeap = (unsigned char *)heap_caps_malloc(managedHeapSize, MALLOC_CAP_8BIT | MALLOC_CAP_32BIT);

            if (pManagedHeap)
            {
                ESP_LOGI(TAG, "Managed heap allocated from internal RAM: %d", managedHeapSize);
            }
            else
            {
                // Subtract 1K and try again
                managedHeapSize -= 1024;

                if (managedHeapSize <= 0)
                {
                    ESP_LOGE(TAG, "Unable to allocate memory for managed heap");

                    ASSERT(false);

                    return;
                }
            }
        }
    }

    baseAddress = pManagedHeap;
    sizeInBytes = managedHeapSize;

    // Update System configuration with Heap location and size
    HalSystemConfig.RAM1.Size = managedHeapSize;
    HalSystemConfig.RAM1.Base = (unsigned int)pManagedHeap;
}
<commit_msg>Fix managed heap size for non BLE versions (#2168)<commit_after>//
// Copyright (c) .NET Foundation and Contributors
// Portions Copyright (c) Microsoft Corporation.  All rights reserved.
// See LICENSE file in the project root for full license information.
//

#include <nanoHAL.h>
#include <target_platform.h>
#include <esp32_idf.h>

//
//  Allocate Memory for Managed heap
//
//  if spiRam is available then use all available ram - SPI_ALLOW_FREE
//
//  if no spiRam or spiRam malloc fails then malloc from normal ram
//
//  The CLR calls this multiple times. Once memory is allocated return the same memory for all
//  subsequent calls.

static const char *TAG = "Memory";

// Space to leave free in SPIRAM for allocation by IDF malloc
#define SPIRAM_MEMORY_LEAVE_FOR_ALLOCATION (256 * 1024)

// You can't go much bigger than this when allocating in internal memory to
// get memory in one continuous lump.
#if (HAL_USE_BLE == TRUE)
#define INTERNAL_MEMORY_SIZE (54 * 1024) // Reduce Managed heap if using BLE without spiram
#else
#define INTERNAL_MEMORY_SIZE (84 * 1024)
#endif

// Saved memory allocation for when heap is reset so we can return same value.
unsigned char *pManagedHeap = NULL;
size_t managedHeapSize = 0;

extern "C"
{
    typedef portMUX_TYPE multi_heap_lock_t;
#include <heap_private.h>

    extern struct registered_heap_ll registered_heaps;
}

void print_heap_info(uint32_t caps)
{
    multi_heap_info_t info;

    debug_printf("Heap summary for capabilities 0x%08X:\n", caps);

    heap_t *heap;

    SLIST_FOREACH(heap, &registered_heaps, next)
    {
        if (heap_caps_match(heap, caps))
        {
            multi_heap_get_info(heap->heap, &info);

            debug_printf(
                "  At 0x%08x len %d free %d allocated %d min_free %d\n",
                heap->start,
                heap->end - heap->start,
                info.total_free_bytes,
                info.total_allocated_bytes,
                info.minimum_free_bytes);
            debug_printf(
                "    largest_free_block %d alloc_blocks %d free_blocks %d total_blocks %d\n",
                info.largest_free_block,
                info.allocated_blocks,
                info.free_blocks,
                info.total_blocks);
        }
    }

    debug_printf("  Totals:\n");
    heap_caps_get_info(&info, caps);

    debug_printf(
        "    free %d allocated %d min_free %d largest_free_block %d\n",
        info.total_free_bytes,
        info.total_allocated_bytes,
        info.minimum_free_bytes,
        info.largest_free_block);
}

//
//	Return the location and size of the managed heap
//  If called a 2nd time then always return same value
//
void HeapLocation(unsigned char *&baseAddress, unsigned int &sizeInBytes)
{
    NATIVE_PROFILE_PAL_HEAP();

    // Memory allocated yet ?
    if (pManagedHeap == NULL)
    {
        // Memory size to allocate in normal memory if PSRAM not available
        managedHeapSize = INTERNAL_MEMORY_SIZE;

        //////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////
        // uncomment, in case there is a need to check the heap info
        // print_heap_info(MALLOC_CAP_8BIT | MALLOC_CAP_SPIRAM);
        //////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////

        // See if we have any SPIRAM
        size_t spiramMaxSize = heap_caps_get_largest_free_block(MALLOC_CAP_8BIT | MALLOC_CAP_32BIT | MALLOC_CAP_SPIRAM);

        // Sanity check - Make sure there is at least managedHeapSize available in SPIRAM
        if (spiramMaxSize)
        {
            // Allocate heap from SPIRAM
            managedHeapSize = spiramMaxSize - SPIRAM_MEMORY_LEAVE_FOR_ALLOCATION;

            pManagedHeap = (unsigned char *)heap_caps_malloc(
                managedHeapSize,
                MALLOC_CAP_8BIT | MALLOC_CAP_32BIT | MALLOC_CAP_SPIRAM);

            if (pManagedHeap)
            {
                // managed heap successfully allocated from SPIRAM
                ESP_LOGI(TAG, "Managed heap allocated from SPIRAM: %d (from max:%d)", managedHeapSize, spiramMaxSize);
            }
            else
            {
                // failed to allocation managed heap from SPIRAM
                ESP_LOGI(TAG, "Failed to allocate managed heap from SPIRAM");
            }
        }

        while (pManagedHeap == NULL)
        {
            // Allocate heap from Internal RAM
            pManagedHeap = (unsigned char *)heap_caps_malloc(managedHeapSize, MALLOC_CAP_8BIT | MALLOC_CAP_32BIT);

            if (pManagedHeap)
            {
                ESP_LOGI(TAG, "Managed heap allocated from internal RAM: %d", managedHeapSize);
            }
            else
            {
                // Subtract 1K and try again
                managedHeapSize -= 1024;

                if (managedHeapSize <= 0)
                {
                    ESP_LOGE(TAG, "Unable to allocate memory for managed heap");

                    ASSERT(false);

                    return;
                }
            }
        }
    }

    baseAddress = pManagedHeap;
    sizeInBytes = managedHeapSize;

    // Update System configuration with Heap location and size
    HalSystemConfig.RAM1.Size = managedHeapSize;
    HalSystemConfig.RAM1.Base = (unsigned int)pManagedHeap;
}
<|endoftext|>


<commit_before>/*
 *  code.cpp
 *
 *  Created on: Oct 30, 2015
 *      Author: Naman, Srishti
 *
 * Play with parameters
 * preprocess - BG Subt -> threshold [OTSU] -> morph -> contour = shows circles in contours
 * Face detect -> remove with flood fill -> skin -> contour
 * Hand Detection with haar -> bounding box -> contouring within box = shows circles in contours
 */

#include <_mingw.h>
#include <core/cvdef.h>
#include <core/cvstd.hpp>
#include <core/mat.hpp>
#include <core/mat.inl.hpp>
#include <core/matx.hpp>
#include <core/ptr.inl.hpp>
#include <core/types.hpp>
#include <core.hpp>
#include <highgui.hpp>
#include <imgproc/types_c.h>
#include <imgproc.hpp>
#include <objdetect.hpp>
#include <video/background_segm.hpp>
#include <videoio.hpp>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <string>
#include <utility>
#include <vector>

using namespace cv;
using namespace std;

Mat frame;                                      //current frame
Mat fgMaskMOG2;                       //fg mask fg mask generated by MOG2 method
Mat back;                                       //stores the background frame
Ptr<BackgroundSubtractorMOG2> pMOG2;            //MOG2 Background subtractor
vector<pair<Point, double>> palm_centers;       //store last 10 palm centers
Mat draw;                                       //Mat for drawing
vector<Point> points;

//String face_cascade_name =
//    "../../../data/haarcascades/haarcascade_frontalface_alt.xml";

String face_cascade_name =
    "haarcascade_frontalface_alt.xml";

//String face_cascade_name = "../../../data/haarcascades/aGest.xml";
CascadeClassifier face_cascade;

//This function returns the square of the euclidean distance between 2 points.
double dist(Point x, Point y) {
  return (x.x - y.x) * (x.x - y.x) + (x.y - y.y) * (x.y - y.y);
}

Mat pre_processing(Mat frame) {

  GaussianBlur(frame, frame, Size(7, 7), 10, 10);
  Mat gray_scale;
  cvtColor(frame, gray_scale, COLOR_BGR2GRAY, 1);

  Mat element = (Mat_<uchar>(3, 3) << 0, 1, 0, 1, 1, 1, 0, 1, 0);
  morphologyEx(gray_scale, gray_scale, MORPH_OPEN, element);

  return gray_scale;
}

void bg_subtraction(VideoCapture cap, Mat frame) {

  //update the background model
  pMOG2->apply(frame, fgMaskMOG2);

  //Get background image to display it
  pMOG2->getBackgroundImage(back);
  pMOG2->setDetectShadows(0);
  pMOG2->setNMixtures(3);
}

//This function returns the radius and the center of the circle given 3 points
//If a circle cannot be formed , it returns a zero radius circle centered at (0,0)
pair<Point, double> circleFromPoints(Point p1, Point p2, Point p3) {
  double offset = pow(p2.x, 2) + pow(p2.y, 2);
  double bc = (pow(p1.x, 2) + pow(p1.y, 2) - offset) / 2.0;
  double cd = (offset - pow(p3.x, 2) - pow(p3.y, 2)) / 2.0;
  double det = (p1.x - p2.x) * (p2.y - p3.y) - (p2.x - p3.x) * (p1.y - p2.y);
  double TOL = 0.0000001;

  if (abs(det) < TOL) {
    cout << "POINTS TOO CLOSE" << endl;
    return make_pair(Point(0, 0), 0);
  }

  double idet = 1 / det;
  double centerx = (bc * (p2.y - p3.y) - cd * (p1.y - p2.y)) * idet;
  double centery = (cd * (p1.x - p2.x) - bc * (p2.x - p3.x)) * idet;
  double radius = sqrt(pow(p2.x - centerx, 2) + pow(p2.y - centery, 2));

  return make_pair(Point(centerx, centery), radius);
}

Mat contouring(Mat binarized, Mat pre_processed) {
  vector<vector<Point>> contours;
  findContours(binarized, contours, CV_RETR_EXTERNAL,
      CV_CHAIN_APPROX_TC89_KCOS);

  for (int i = 0; i < contours.size(); i++)

    //Ignore all small insignificant areas
    if (contourArea(contours[i]) >= 5000) {

      //Draw contour
      vector<vector<Point>> tcontours;
      tcontours.push_back(contours[i]);
      drawContours(pre_processed, tcontours, -1, Scalar(0, 0, 255), 2);

      //Detect Hull in current contour
      vector<vector<Point> > hulls(1);
      vector<vector<int> > hullsI(1);
      convexHull(Mat(tcontours[0]), hulls[0], false);
      convexHull(Mat(tcontours[0]), hullsI[0], false);
      drawContours(pre_processed, hulls, -1, Scalar(0, 255, 0), 2);

      //Find minimum area rectangle to enclose hand
      RotatedRect rect = minAreaRect(Mat(tcontours[0]));

      //Find Convex Defects
      vector<Vec4i> defects;
      if (hullsI[0].size() > 0) {
        Point2f rect_points[4];
        rect.points(rect_points);
        for (int j = 0; j < 4; j++)
          line(pre_processed, rect_points[j], rect_points[(j + 1) % 4],
              Scalar(255, 0, 0), 1, 8);
        Point rough_palm_center;
        convexityDefects(tcontours[0], hullsI[0], defects);
        if (defects.size() >= 3) {
          vector<Point> palm_points;
          for (int j = 0; j < defects.size(); j++) {
            int startidx = defects[j][0];
            Point ptStart(tcontours[0][startidx]);
            int endidx = defects[j][1];
            Point ptEnd(tcontours[0][endidx]);
            int faridx = defects[j][2];
            Point ptFar(tcontours[0][faridx]);

            //Sum up all the hull and defect points to compute average
            rough_palm_center += ptFar + ptStart + ptEnd;
            palm_points.push_back(ptFar);
            palm_points.push_back(ptStart);
            palm_points.push_back(ptEnd);
          }

          //Get palm center by 1st getting the average of all defect points, this is the rough palm center,
          //Then chose the closest 3 points ang get the circle radius and center formed from them which is the palm center.
          rough_palm_center.x /= defects.size() * 3;
          rough_palm_center.y /= defects.size() * 3;
          Point closest_pt = palm_points[0];
          vector<pair<double, int> > distvec;
          for (int i = 0; i < palm_points.size(); i++)
            distvec.push_back(
                make_pair(dist(rough_palm_center, palm_points[i]), i));
          sort(distvec.begin(), distvec.end());

          //Keep choosing 3 points till you find a circle with a valid radius
          //As there is a high chance that the closes points might be in a linear line or too close that it forms a very large circle
          pair<Point, double> soln_circle;
          for (int i = 0; i + 2 < distvec.size(); i++) {
            Point p1 = palm_points[distvec[i + 0].second];
            Point p2 = palm_points[distvec[i + 1].second];
            Point p3 = palm_points[distvec[i + 2].second];
            soln_circle = circleFromPoints(p1, p2, p3); //Final palm center,radius
            if (soln_circle.second != 0)
              break;
          }

          //Find avg palm centers for the last few frames to stabilize its centers, also find the avg radius
          palm_centers.push_back(soln_circle);
          if (palm_centers.size() > 10)
            palm_centers.erase(palm_centers.begin());

          Point palm_center;
          double radius = 0;

          //averaging all palm centres
          for (int i = 0; i < palm_centers.size(); i++) {
            palm_center += palm_centers[i].first;
            radius += palm_centers[i].second;
          }
          palm_center.x /= palm_centers.size();
          palm_center.y /= palm_centers.size();
          radius /= palm_centers.size();

          //Draw the palm center and the palm circle
          //The size of the palm gives the depth of the hand
          circle(pre_processed, palm_center, 5, Scalar(144, 144, 255), 3);
          circle(pre_processed, palm_center, radius, Scalar(144, 144, 255), 2);

          //Detect fingers by finding points that form an almost isosceles triangle with certain thesholds
          int no_of_fingers = 0;
          for (int j = 0; j < defects.size(); j++) {
            int startidx = defects[j][0];
            Point ptStart(tcontours[0][startidx]);
            int endidx = defects[j][1];
            Point ptEnd(tcontours[0][endidx]);
            int faridx = defects[j][2];
            Point ptFar(tcontours[0][faridx]);

            //X o--------------------------o Y

            double Xdist = sqrt(dist(palm_center, ptFar));
            double Ydist = sqrt(dist(palm_center, ptStart));
            double length = sqrt(dist(ptFar, ptStart));
            double retLength = sqrt(dist(ptEnd, ptFar));

            //Play with these thresholds to improve performance
            if (length <= 3 * radius && Ydist >= 0.4 * radius && length >= 10
                && retLength >= 10
                && max(length, retLength) / min(length, retLength) >= 0.8) {
              if (min(Xdist, Ydist) / max(Xdist, Ydist) <= 0.8) {
                if ((Xdist >= 0.1 * radius && Xdist <= 1.3 * radius
                    && Xdist < Ydist)
                    || (Ydist >= 0.1 * radius && Ydist <= 1.3 * radius
                        && Xdist > Ydist)) {
                  line(pre_processed, ptEnd, ptFar, Scalar(0, 255, 0), 1);
                  no_of_fingers++;
                }
              }
            }
          }

          no_of_fingers = min(5, no_of_fingers);
          cout << "NO OF FINGERS: " << no_of_fingers << endl;

          putText(pre_processed, "NO OF FINGERS: " + to_string(no_of_fingers),
              Point(30, 30), FONT_HERSHEY_COMPLEX_SMALL, 0.8,
              Scalar(200, 200, 250), 1, LINE_AA);

          if (no_of_fingers == 1) {
            //draw on draw matrix

            circle(draw, palm_center, 2, Scalar(0, 0, 255), 2);

            if(!points.empty())
              line(draw, palm_center, points.back() ,Scalar(14, 174, 255), 2);

            points.push_back(palm_center);

//            imshow("draw", draw);
          }else if(no_of_fingers == 5){
            putText(pre_processed, "PAN GESTURE",
                Point(90, 90), FONT_HERSHEY_COMPLEX_SMALL, 0.8,
                Scalar(200, 200, 250), 1, LINE_AA);

          }
        }
      }
    }
  return pre_processed;
}

void facedetect(Mat frame) {
  vector<Rect> faces;
  Mat frame_gray;

  if (frame.channels() > 1)
    cvtColor(frame, frame_gray, COLOR_BGR2GRAY);
  else
    frame_gray = frame;

  equalizeHist(frame_gray, frame_gray);

  //Detect faces
  face_cascade.detectMultiScale(frame_gray, faces, 1.1, 2,
      0 | CASCADE_SCALE_IMAGE, Size(30, 30));

  for (size_t i = 0; i < faces.size(); i++) {
    Point center(faces[i].x + faces[i].width / 2,
        faces[i].y + faces[i].height / 2);
    ellipse(frame, center, Size(faces[i].width / 2, faces[i].height / 2), 0, 0,
        360, Scalar(0, 0, 0), 200, 8, 0);

    Mat faceROI = frame_gray(faces[i]);
  }
}

Mat skin_detect(Mat frame) {

  //blur the image to make segmentation simpler
  blur(frame, frame, Size(10, 10));

  //convert the image from bgr to hsv mode
  Mat hsv;
  cvtColor(frame, hsv, CV_BGR2HSV);

  Mat detected;

  //lower bound - Scalar(0, 10, 60)  and upper bound - Scalar(20, 150, 255) for classifying skin
  //ranged is set to 255 (skin) if hsv is within the specified range and 0 otherwise.
  inRange(hsv, Scalar(0, 10, 60), Scalar(20, 150, 255), detected);

  return detected;
}

int process_video() {

  VideoCapture cap(0); // open the default camera
  if (!cap.isOpened())  // check if we succeeded
    return -1;

  //draw on blackboard
  Size s = Size(640, 480);
  draw = Mat::zeros(s, CV_8UC3);

  for (;;) {
    cap >> frame; // get a new frame from camera
    Mat orig = frame.clone();

    Mat foreground;

    Mat pre_processed = pre_processing(frame); //preprocess and convert to grayscale

    //returns the bg subtracted and stores
    bg_subtraction(cap, pre_processed);

    absdiff(pre_processed, back, foreground);

    Mat temp = foreground.clone();
//    facedetect(temp);

    Mat fg_binarized_mask;
    threshold(temp, fg_binarized_mask, 0, 255,
        THRESH_BINARY | THRESH_OTSU);
    GaussianBlur(fg_binarized_mask, fg_binarized_mask, Size(7, 7), 10, 10);

    //morphology to remove noise
    Mat element = (Mat_<uchar>(3, 3) << 0, 1, 0, 1, 1, 1, 0, 1, 0);
    morphologyEx(fg_binarized_mask, fg_binarized_mask, MORPH_OPEN, element);

    Mat bg_removed;
    orig.copyTo(bg_removed,fg_binarized_mask);

//    imshow("Binarised", fg_binarized_mask);

    //Detect Face here and remove it, input would be result of the above step

    /*
       //only hand is left detect skin
      Mat a = skin_detect(bg_removed);
      imshow("bg removed gray", a);
     */

    //finally contour
    Mat contour = contouring(fg_binarized_mask, bg_removed);

    imshow("Output", contour);
    imshow("Board", draw);
    if (waitKey(30) >= 0)
      break;
  }
  return 0;
}

int main(int, char**) {

  //create Background Subtractor objects
  pMOG2 = createBackgroundSubtractorMOG2(); //MOG2 approach
   // Load the cascades
   if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading face cascade\n"); return -1; };

  int res = process_video();
  return 0;
}
<commit_msg>tweaks and fixes<commit_after>/*
 *  code.cpp
 *
 *  Created on: Oct 30, 2015
 *      Author: Naman, Srishti
 *
 * Play with parameters
 * preprocess - BG Subt -> threshold [OTSU] -> morph -> contour = shows circles in contours
 * Face detect -> remove with flood fill -> skin -> contour
 * Hand Detection with haar -> bounding box -> contouring within box = shows circles in contours
 */

#include <core/cvstd.hpp>
#include <core/ptr.inl.hpp>
#include <objdetect.hpp>
#include <video/background_segm.hpp>
#include <cstdio>

#include "../helpers/helpers.cpp"

int main(int, char**) {

  //create Background Subtractor objects
  pMOG2 = createBackgroundSubtractorMOG2(); //MOG2 approach
   // Load the cascades
   if( !face_cascade.load( face_cascade_name ) ){ printf("--(!)Error loading face cascade\n"); return -1; };

  int res = process_video();
  return 0;
}
<|endoftext|>


<commit_before>#include "stdsneezy.h"
#include "obj_base_corpse.h"
#include "obj_tool.h"

int task_sacrifice(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *, TObj *obj)
{
  TThing *t, *t2;
  TMonster *guard;
  TTool *totem=NULL;
  int learning = ch->getSkillValue(SKILL_SACRIFICE);
  TBaseCorpse *corpse = dynamic_cast<TBaseCorpse *>(obj);
  int clev = ch->GetMaxLevel();
  int percent = ::number(1, 100);
  int factor = ::number(5, (((clev + learning) + percent) / 2));
  int factor2 = ::number(5, (((clev + learning) + percent) / 5));

  if (!ch || !ch->task) {
    vlogf(LOG_BUG, fmt("No %s in task_sacrifice!") % (ch ? "character" : "task"));
    return FALSE;
  }

  if (ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd)) {
    return FALSE;
  }

  if (!corpse) {
	  act("You can't find the object of the ritual! Wasn't there a corpse here?",
      FALSE, ch, 0, 0, TO_CHAR);
	  act("$n stops singing and looks confused.", TRUE, ch, 0, 0, TO_ROOM);
    ch->stopTask();
    vlogf(LOG_BUG,
        fmt("task_sacrifice.cc: sacrifice task entered by %s without a corpse!")
        % ch->getName());
    return TRUE;
  }

  if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom) ||
      (ch->getPosition() < POSITION_RESTING)) {
    act("You cease the ritual sacrifice of $p.", FALSE, ch, corpse, 0, TO_CHAR);
    act("$n stops trying to sacrifice $p.", TRUE, ch, corpse, 0, TO_ROOM);
    ch->stopTask();
    if (corpse->isCorpseFlag(CORPSE_SACRIFICE))
      corpse->remCorpseFlag(CORPSE_SACRIFICE);
    return TRUE;
  }

  if (!(t = get_thing_char_using(ch, "totem", 0, FALSE, FALSE)) ||
      !(totem=dynamic_cast<TTool *>(t))) {
    ch->sendTo("You need to own a totem to perform the ritual.\n\r");
    ch->stopTask();
    if (corpse->isCorpseFlag(CORPSE_SACRIFICE))
      corpse->remCorpseFlag(CORPSE_SACRIFICE);
    return TRUE;
  }

  for (t = ch->roomp->getStuff(); t; t = t2) {
    t2 = t->nextThing;
    guard = dynamic_cast<TMonster *>(t);
    if (!guard)
      continue;
    if (!guard->isPolice() || !guard->canSee(ch) || !guard->awake())
      continue;
    int saything = (::number(0,3));
    switch (saything) {
      case 0:
	      guard->doSay("Hey! Get the hell out of here! Damn Voodoo Witch!");
	      break;
      case 1:
	      guard->doSay("Hey! Don't you have any respect for the dead?!? Get the hell out of here!");
	      break;
      case 2:
	      guard->doSay("Damn Shaman! Take your voodoo crap and PISS OFF!!!");
	      break;
      case 3:
	    guard->doSay("Hey witch!! Are you some sort of whacked out necrophiliac? Bugger off!!");
	    break;
    }
    act("You cease the ritual sacrifice of $p.",
        FALSE, ch, corpse, 0, TO_CHAR);
    act("$n stops chanting over the corpse of $p.",
        TRUE, ch, corpse, 0, TO_ROOM);
    ch->stopTask();
    if (corpse->isCorpseFlag(CORPSE_SACRIFICE))
      corpse->remCorpseFlag(CORPSE_SACRIFICE);
    return TRUE;
  }

  if (ch->task->timeLeft < 0){
    act("You have completed the sacrifice of $p.",
        FALSE, ch, corpse, 0, TO_CHAR);
    act("$n has completed $s ritual sacrifice of $p.",
        TRUE, ch, corpse, 0, TO_ROOM);
    act("Some <r>blood<z> from $p has been left behind.",
        FALSE, ch, corpse, 0, TO_ROOM);
    act("Some <r>blood<z> from $p has been left behind for the dogs!",
        TRUE, ch, corpse, 0, TO_CHAR);
    ch->dropPool(1, LIQ_BLOOD);
    ch->stopTask();
    delete corpse;
    corpse = NULL;
    return TRUE;
  }

  switch (cmd) {
    case CMD_TASK_CONTINUE:
      if (percent < ch->getSkillValue(SKILL_SACRIFICE)) {
        act("Your sacrifice is being accepted by the loa.",
            FALSE, ch, 0, 0, TO_CHAR);
        ch->addToLifeforce(factor);
        ch->updatePos();
      } else {
        ch->addToLifeforce(-factor2);
        if (0 >= ch->getLifeforce()) {
          ch->setLifeforce(0);
          act("The loa demands that you cease this vain sacrifice, and you comply.",
              FALSE, ch, 0, 0, TO_CHAR);
          ch->addToHit(-2);
          ch->updatePos();
          ch->task->timeLeft = -1;
        }
      }

      ch->task->calcNextUpdate(pulse, 2 * PULSE_MOBACT);
      totem->addToToolUses(-1);
      if (totem->getToolUses() <= 0) {
        act("Your $o has been confiscated by the loa! It must have been too weak.",
            FALSE, ch, totem, 0, TO_CHAR);
        act("$n looks pale as $s $o shatters.", TRUE, ch, totem, 0, TO_ROOM);
        ch->stopTask();
        delete totem;
        totem = NULL;
        if (corpse->isCorpseFlag(CORPSE_SACRIFICE))
          corpse->remCorpseFlag(CORPSE_SACRIFICE);
        return TRUE;
      }
      if (10 >= corpse->obj_flags.decay_time)
        corpse->obj_flags.decay_time = 10;

      switch (ch->task->timeLeft) {
        case 2:
          act("You continue the rada song to the loa in hopes they will accept your sacrifice.",
              FALSE, ch, 0, 0, TO_CHAR);
          act("$n sings in an unfamiliar tongue over $p.",
              TRUE, ch, corpse, 0, TO_ROOM);
	        if (ch->bSuccess(learning, SKILL_SACRIFICE))
	          ch->task->timeLeft--;
	        break;
        case 1:
          act("Your $o's eyes glow <r>blood red<1>.",
              FALSE, ch, totem, 0, TO_CHAR);
          act("The eyes on $n's $o begin to glow a <r>blood red<1>.",
              TRUE, ch, totem, 0, TO_ROOM);
	        if (ch->bSuccess(learning, SKILL_SACRIFICE))
	          ch->task->timeLeft--;
	        break;
        case 0:
	        act("You continue to sing the rada song over $p.",
              FALSE, ch, corpse, 0, TO_CHAR);
	        act("$n's ritual sacrifice causes $p's face to glow <G>pale green<1>.",
              TRUE, ch, corpse, 0, TO_ROOM);
          if (ch->bSuccess(learning, SKILL_SACRIFICE))
            ch->task->timeLeft--;
          break;
        case -1:
          act("You feel the loa ignoring your vain attempt and feel completed to stop.",
              false, ch, 0, 0, TO_CHAR);
          act("$n has stopped $s ritual sacrifice of $p.",
              TRUE, ch, corpse, 0, TO_ROOM);
          ch->stopTask();
          if (corpse->isCorpseFlag(CORPSE_SACRIFICE))
            corpse->remCorpseFlag(CORPSE_SACRIFICE);
          break;
        default:
          // BUG - somehow you land here if you run your life force down
          // when sacrificing and the loa forces you to stop
          act("Bug Maror if you get this message.", false, ch, 0, 0, TO_CHAR);
          vlogf(LOG_BUG, fmt("no appropriate option in switch in sacrifice.cc, timeleft value was %d")
              % ch->task->timeLeft);
          ch->stopTask();
          if (corpse->isCorpseFlag(CORPSE_SACRIFICE))
            corpse->remCorpseFlag(CORPSE_SACRIFICE);
          break;
      }
      break;
    case CMD_TASK_FIGHTING:
      ch->sendTo("You can't sacrifice a corpse while under attack.\n\r");
      // don't put a break in here
    case CMD_ABORT:
    case CMD_STOP:
      act("You stop your sacrifice of $p.",
          FALSE, ch, corpse, 0, TO_CHAR);
      act("$n has stopped $s ritual sacrifice of $p.",
          TRUE, ch, corpse, 0, TO_ROOM);
      act("Some <r>blood<z> from $p has been left behind.",
          FALSE, ch, corpse, 0, TO_ROOM);
      act("Some <r>blood<z> from $p has been left behind for the dogs!",
          TRUE, ch, corpse, 0, TO_CHAR);
      ch->dropPool(1, LIQ_BLOOD);
      ch->stopTask();
      delete corpse;
      corpse = NULL;
      break;
    default:
      if (cmd < MAX_CMD_LIST) {
        ch->addToLifeforce(-factor * 2);
        ch->sendTo("The loa are upset with your flagrant disregard for the houngan ways and punish you!\n\r");
      }

      warn_busy(ch);
      break;
  }
  return TRUE;
}
<commit_msg>Added a failure message to sacrifice by player request.<commit_after>#include "stdsneezy.h"
#include "obj_base_corpse.h"
#include "obj_tool.h"

int task_sacrifice(TBeing *ch, cmdTypeT cmd, const char *, int pulse, TRoom *, TObj *obj)
{
  TThing *t, *t2;
  TMonster *guard;
  TTool *totem=NULL;
  int learning = ch->getSkillValue(SKILL_SACRIFICE);
  TBaseCorpse *corpse = dynamic_cast<TBaseCorpse *>(obj);
  int clev = ch->GetMaxLevel();
  int percent = ::number(1, 100);
  int factor = ::number(5, (((clev + learning) + percent) / 2));
  int factor2 = ::number(5, (((clev + learning) + percent) / 5));

  if (!ch || !ch->task) {
    vlogf(LOG_BUG, fmt("No %s in task_sacrifice!") % (ch ? "character" : "task"));
    return FALSE;
  }

  if (ch->utilityTaskCommand(cmd) || ch->nobrainerTaskCommand(cmd)) {
    return FALSE;
  }

  if (!corpse) {
	  act("You can't find the object of the ritual! Wasn't there a corpse here?",
      FALSE, ch, 0, 0, TO_CHAR);
	  act("$n stops singing and looks confused.", TRUE, ch, 0, 0, TO_ROOM);
    ch->stopTask();
    vlogf(LOG_BUG,
        fmt("task_sacrifice.cc: sacrifice task entered by %s without a corpse!")
        % ch->getName());
    return TRUE;
  }

  if (ch->isLinkdead() || (ch->in_room != ch->task->wasInRoom) ||
      (ch->getPosition() < POSITION_RESTING)) {
    act("You cease the ritual sacrifice of $p.", FALSE, ch, corpse, 0, TO_CHAR);
    act("$n stops trying to sacrifice $p.", TRUE, ch, corpse, 0, TO_ROOM);
    ch->stopTask();
    if (corpse->isCorpseFlag(CORPSE_SACRIFICE))
      corpse->remCorpseFlag(CORPSE_SACRIFICE);
    return TRUE;
  }

  if (!(t = get_thing_char_using(ch, "totem", 0, FALSE, FALSE)) ||
      !(totem=dynamic_cast<TTool *>(t))) {
    ch->sendTo("You need to own a totem to perform the ritual.\n\r");
    ch->stopTask();
    if (corpse->isCorpseFlag(CORPSE_SACRIFICE))
      corpse->remCorpseFlag(CORPSE_SACRIFICE);
    return TRUE;
  }

  for (t = ch->roomp->getStuff(); t; t = t2) {
    t2 = t->nextThing;
    guard = dynamic_cast<TMonster *>(t);
    if (!guard)
      continue;
    if (!guard->isPolice() || !guard->canSee(ch) || !guard->awake())
      continue;
    int saything = (::number(0,3));
    switch (saything) {
      case 0:
	      guard->doSay("Hey! Get the hell out of here! Damn Voodoo Witch!");
	      break;
      case 1:
	      guard->doSay("Hey! Don't you have any respect for the dead?!? Get the hell out of here!");
	      break;
      case 2:
	      guard->doSay("Damn Shaman! Take your voodoo crap and PISS OFF!!!");
	      break;
      case 3:
	    guard->doSay("Hey witch!! Are you some sort of whacked out necrophiliac? Bugger off!!");
	    break;
    }
    act("You cease the ritual sacrifice of $p.",
        FALSE, ch, corpse, 0, TO_CHAR);
    act("$n stops chanting over the corpse of $p.",
        TRUE, ch, corpse, 0, TO_ROOM);
    ch->stopTask();
    if (corpse->isCorpseFlag(CORPSE_SACRIFICE))
      corpse->remCorpseFlag(CORPSE_SACRIFICE);
    return TRUE;
  }

  if (ch->task->timeLeft < 0){
    act("You have completed the sacrifice of $p.",
        FALSE, ch, corpse, 0, TO_CHAR);
    act("$n has completed $s ritual sacrifice of $p.",
        TRUE, ch, corpse, 0, TO_ROOM);
    act("Some <r>blood<z> from $p has been left behind.",
        FALSE, ch, corpse, 0, TO_ROOM);
    act("Some <r>blood<z> from $p has been left behind for the dogs!",
        TRUE, ch, corpse, 0, TO_CHAR);
    ch->dropPool(1, LIQ_BLOOD);
    ch->stopTask();
    delete corpse;
    corpse = NULL;
    return TRUE;
  }

  switch (cmd) {
    case CMD_TASK_CONTINUE:
      if (percent < ch->getSkillValue(SKILL_SACRIFICE)) {
        act("Your sacrifice is being accepted by the loa.",
            FALSE, ch, 0, 0, TO_CHAR);
        ch->addToLifeforce(factor);
        ch->updatePos();
      } else {
        ch->addToLifeforce(-factor2);
        act("Your sacrificial attempts aren't pleasing the loa.",
            FALSE, ch, 0, 0, TO_CHAR);
        if (0 >= ch->getLifeforce()) {
          ch->setLifeforce(0);
          act("The loa demands that you cease this vain sacrifice, and you comply.",
              FALSE, ch, 0, 0, TO_CHAR);
          ch->addToHit(-2);
          ch->updatePos();
          ch->task->timeLeft = -1;
        }
      }

      ch->task->calcNextUpdate(pulse, 2 * PULSE_MOBACT);
      totem->addToToolUses(-1);
      if (totem->getToolUses() <= 0) {
        act("Your $o has been confiscated by the loa! It must have been too weak.",
            FALSE, ch, totem, 0, TO_CHAR);
        act("$n looks pale as $s $o shatters.", TRUE, ch, totem, 0, TO_ROOM);
        ch->stopTask();
        delete totem;
        totem = NULL;
        if (corpse->isCorpseFlag(CORPSE_SACRIFICE))
          corpse->remCorpseFlag(CORPSE_SACRIFICE);
        return TRUE;
      }
      if (10 >= corpse->obj_flags.decay_time)
        corpse->obj_flags.decay_time = 10;

      switch (ch->task->timeLeft) {
        case 2:
          act("You continue the rada song to the loa in hopes they will accept your sacrifice.",
              FALSE, ch, 0, 0, TO_CHAR);
          act("$n sings in an unfamiliar tongue over $p.",
              TRUE, ch, corpse, 0, TO_ROOM);
	        if (ch->bSuccess(learning, SKILL_SACRIFICE))
	          ch->task->timeLeft--;
	        break;
        case 1:
          act("Your $o's eyes glow <r>blood red<1>.",
              FALSE, ch, totem, 0, TO_CHAR);
          act("The eyes on $n's $o begin to glow a <r>blood red<1>.",
              TRUE, ch, totem, 0, TO_ROOM);
	        if (ch->bSuccess(learning, SKILL_SACRIFICE))
	          ch->task->timeLeft--;
	        break;
        case 0:
	        act("You continue to sing the rada song over $p.",
              FALSE, ch, corpse, 0, TO_CHAR);
	        act("$n's ritual sacrifice causes $p's face to glow <G>pale green<1>.",
              TRUE, ch, corpse, 0, TO_ROOM);
          if (ch->bSuccess(learning, SKILL_SACRIFICE))
            ch->task->timeLeft--;
          break;
        case -1:
          act("You feel the loa ignoring your vain attempt and feel completed to stop.",
              false, ch, 0, 0, TO_CHAR);
          act("$n has stopped $s ritual sacrifice of $p.",
              TRUE, ch, corpse, 0, TO_ROOM);
          ch->stopTask();
          if (corpse->isCorpseFlag(CORPSE_SACRIFICE))
            corpse->remCorpseFlag(CORPSE_SACRIFICE);
          break;
        default:
          // BUG - somehow you land here if you run your life force down
          // when sacrificing and the loa forces you to stop
          act("Bug Maror if you get this message.", false, ch, 0, 0, TO_CHAR);
          vlogf(LOG_BUG, fmt("no appropriate option in switch in sacrifice.cc, timeleft value was %d")
              % ch->task->timeLeft);
          ch->stopTask();
          if (corpse->isCorpseFlag(CORPSE_SACRIFICE))
            corpse->remCorpseFlag(CORPSE_SACRIFICE);
          break;
      }
      break;
    case CMD_TASK_FIGHTING:
      ch->sendTo("You can't sacrifice a corpse while under attack.\n\r");
      // don't put a break in here
    case CMD_ABORT:
    case CMD_STOP:
      act("You stop your sacrifice of $p.",
          FALSE, ch, corpse, 0, TO_CHAR);
      act("$n has stopped $s ritual sacrifice of $p.",
          TRUE, ch, corpse, 0, TO_ROOM);
      act("Some <r>blood<z> from $p has been left behind.",
          FALSE, ch, corpse, 0, TO_ROOM);
      act("Some <r>blood<z> from $p has been left behind for the dogs!",
          TRUE, ch, corpse, 0, TO_CHAR);
      ch->dropPool(1, LIQ_BLOOD);
      ch->stopTask();
      delete corpse;
      corpse = NULL;
      break;
    default:
      if (cmd < MAX_CMD_LIST) {
        ch->addToLifeforce(-factor * 2);
        ch->sendTo("The loa are upset with your flagrant disregard for the houngan ways and punish you!\n\r");
      }

      warn_busy(ch);
      break;
  }
  return TRUE;
}
<|endoftext|>


<commit_before>vector<int> e[10000];int visit[10000], low[10000];bool instack[10000];int belong[10000];stack<int> s;
int t;;int num; //number of SCC
void DFS(int u)
{
    visit[u] = low[u] = ++t; //進行標號
    s.push(u); instack[u] = true;
    for (int i = 0; i < e[i].size(); i++) {
        int v = e[u][i];
        if (!visit[v]) {
            DFS(v); low[u] = min(low[u], low[v]); // 找 u 的最上層祖先
        }
        if (instack[v]) low[u] = min(low[u], visit[v]); //還在stack中 用 visit的值
    }
    if (visit[u] == low[u]){//SCC
        num++; int v = s.top();s.pop();
        instack[v] = false;belong[v] = num;
        while (v != u) {
            v = s.top();  s.pop();
            belong[v] = num; instack[v] = false;
        }
    }
}
int Tarjan(int n) //n:number of vertex 0-based
{
    t = 0, num = 0;
    memset(visit, 0, sizeof(visit));
    for (int i = 0; i < n; i++) e[i].clear();
    for (int i = 0; i < n; i++)
        if (!visit[i]) DFS(i);
    return num;
}
<commit_msg>debug SCC<commit_after>vector<int> e[10000];int visit[10000], low[10000];bool instack[10000];int belong[10000];stack<int> s;
int t;;int num; //number of SCC
void DFS(int u)
{
    visit[u] = low[u] = ++t; //進行標號
    s.push(u); instack[u] = true;
    for (int i = 0; i < e[u].size(); i++) {
        int v = e[u][i];
        if (!visit[v]) {
            DFS(v); low[u] = min(low[u], low[v]); // 找 u 的最上層祖先
        }
        if (instack[v]) low[u] = min(low[u], visit[v]); //還在stack中 用 visit的值
    }
    if (visit[u] == low[u]){//SCC
        num++; int v = s.top();s.pop();
        instack[v] = false;belong[v] = num;
        while (v != u) {
            v = s.top();  s.pop();
            belong[v] = num; instack[v] = false;
        }
    }
}
int Tarjan(int n) //n:number of vertex 0-based
{
    t = 0, num = 0;
    memset(visit, 0, sizeof(visit));
    for (int i = 0; i < n; i++) e[i].clear();
    for (int i = 0; i < n; i++)
        if (!visit[i]) DFS(i);
    return num;
}
<|endoftext|>