<commit_before>/*
 * Copyright (c) 2014-2015, Georgia Tech Research Corporation
 * All rights reserved.
 *
 * Author(s): Jeongseok Lee <jslee02@gmail.com>
 *
 * Georgia Tech Graphics Lab and Humanoid Robotics Lab
 *
 * Directed by Prof. C. Karen Liu and Prof. Mike Stilman
 * <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu>
 *
 * This file is provided under the following "BSD-style" License:
 *   Redistribution and use in source and binary forms, with or
 *   without modification, are permitted provided that the following
 *   conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *   CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 *   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 *   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *   AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *   POSSIBILITY OF SUCH DAMAGE.
 */

#include "dart/utils/sdf/SoftSdfParser.h"

#include <map>
#include <iostream>
#include <fstream>

#include "dart/common/Console.h"
#include "dart/collision/dart/DARTCollisionDetector.h"
#include "dart/collision/fcl/FCLCollisionDetector.h"
// #include "dart/collision/fcl_mesh/FCLMeshCollisionDetector.h"
#include "dart/dynamics/Shape.h"
#include "dart/dynamics/BoxShape.h"
#include "dart/dynamics/CylinderShape.h"
#include "dart/dynamics/EllipsoidShape.h"
#include "dart/dynamics/WeldJoint.h"
#include "dart/dynamics/RevoluteJoint.h"
#include "dart/dynamics/PrismaticJoint.h"
#include "dart/dynamics/TranslationalJoint.h"
#include "dart/dynamics/BallJoint.h"
#include "dart/dynamics/FreeJoint.h"
#include "dart/dynamics/ScrewJoint.h"
#include "dart/dynamics/UniversalJoint.h"
#include "dart/simulation/World.h"
#include "dart/utils/SkelParser.h"

#include "dart/collision/fcl_mesh/FCLMeshCollisionDetector.h"
#include "dart/dynamics/SoftMeshShape.h"
#include "dart/dynamics/SoftBodyNode.h"
#include "dart/dynamics/Skeleton.h"
#include "dart/simulation/World.h"

namespace dart {
namespace utils {

//==============================================================================
simulation::WorldPtr SoftSdfParser::readSoftSdfFile(
  const common::Uri& _filUri, const common::ResourceRetrieverPtr& _retriever)
{
  return SdfParser::readSdfFile(_filUri, getResourceRetriever(_retriever),
    static_cast<simulation::WorldPtr (*)(
      tinyxml2::XMLElement*, const std::string&,
      const common::ResourceRetrieverPtr&)>(&SoftSdfParser::readWorld));
}

//==============================================================================
dynamics::SkeletonPtr SoftSdfParser::readSkeleton(
    const common::Uri& _fileUri, const common::ResourceRetrieverPtr& _retriever)
{
  return SdfParser::readSkeleton(_fileUri, getResourceRetriever(_retriever),
    static_cast<dynamics::SkeletonPtr (*)(
      tinyxml2::XMLElement*, const std::string&,
      const common::ResourceRetrieverPtr&)>(&SoftSdfParser::readSkeleton));
}

bool SoftSdfParser::createSoftPair(
    dynamics::SkeletonPtr skeleton,
    dynamics::BodyNode* parent,
    const SDFJoint& newJoint,
    const SDFBodyNode& newBody)
{
  std::pair<dynamics::Joint*, dynamics::BodyNode*> pair;
  if(newBody.type.empty())
    pair = createJointAndNodePair<dynamics::BodyNode>(
          skeleton, parent, newJoint, newBody);
  else if(std::string("soft") == newBody.type)
    pair = createJointAndNodePair<dynamics::SoftBodyNode>(
          skeleton, parent, newJoint, newBody);
  else
  {
    dterr << "[SoftSdfParser::createSoftPair] Unsupported Link type: "
          << newBody.type << "\n";
    return false;
  }

  if(!pair.first || !pair.second)
    return false;

  return true;
}

simulation::WorldPtr SoftSdfParser::readWorld(
    tinyxml2::XMLElement* _worldElement,
    const std::string& _skelPath,
    const common::ResourceRetrieverPtr& _retriever)
{
  return SdfParser::readWorld(_worldElement, _skelPath, _retriever,
    static_cast<dynamics::SkeletonPtr (*)(
      tinyxml2::XMLElement*, const std::string&,
      const common::ResourceRetrieverPtr&)>(&SoftSdfParser::readSkeleton));
}

dynamics::SkeletonPtr SoftSdfParser::readSkeleton(
    tinyxml2::XMLElement* _skeletonElement,
    const std::string& _skelPath,
    const common::ResourceRetrieverPtr& _retriever)
{
  return SdfParser::readSkeleton(_skeletonElement, _skelPath, _retriever,
                                 &readSoftBodyNode, &createSoftPair);
}

SdfParser::SDFBodyNode SoftSdfParser::readSoftBodyNode(
    tinyxml2::XMLElement* _softBodyNodeElement,
    const Eigen::Isometry3d& _skeletonFrame,
    const std::string& _skelPath,
    const common::ResourceRetrieverPtr& _retriever)
{
  //---------------------------------- Note ------------------------------------
  // SoftBodyNode is created if _softBodyNodeElement has <soft_shape>.
  // Otherwise, BodyNode is created.

  //----------------------------------------------------------------------------
  assert(_softBodyNodeElement != nullptr);

  // If _softBodyNodeElement has no <soft_shape>, return rigid body node
  if (!hasElement(_softBodyNodeElement, "soft_shape"))
  {
    return SdfParser::readBodyNode(
          _softBodyNodeElement, _skeletonFrame, _skelPath, _retriever);
  }

  SDFBodyNode standardSDF =
      SdfParser::readBodyNode(_softBodyNodeElement, _skeletonFrame, _skelPath, _retriever);

  BodyPropPtr standardProperties = standardSDF.properties;

  dynamics::SoftBodyNode::UniqueProperties softProperties;

  //----------------------------------------------------------------------------
  // Soft properties
  if (hasElement(_softBodyNodeElement, "soft_shape"))
  {
    tinyxml2::XMLElement* softShapeEle
        = getElement(_softBodyNodeElement, "soft_shape");

    // mass
    double totalMass = getValueDouble(softShapeEle, "total_mass");

    // pose
    Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
    if (hasElement(softShapeEle, "pose"))
      T = getValueIsometry3dWithExtrinsicRotation(softShapeEle, "pose");

    // geometry
    tinyxml2::XMLElement* geometryEle = getElement(softShapeEle, "geometry");
    if (hasElement(geometryEle, "box"))
    {
      tinyxml2::XMLElement* boxEle = getElement(geometryEle, "box");
      Eigen::Vector3d size  = getValueVector3d(boxEle, "size");
      Eigen::Vector3i frags = getValueVector3i(boxEle, "frags");
      softProperties = dynamics::SoftBodyNodeHelper::makeBoxProperties(
            size, T, frags, totalMass);
    }
    else if (hasElement(geometryEle, "ellipsoid"))
    {
      tinyxml2::XMLElement* ellipsoidEle = getElement(geometryEle, "ellipsoid");
      Eigen::Vector3d size = getValueVector3d(ellipsoidEle, "size");
      double nSlices       = getValueDouble(ellipsoidEle, "num_slices");
      double nStacks       = getValueDouble(ellipsoidEle, "num_stacks");
      softProperties = dynamics::SoftBodyNodeHelper::makeEllipsoidProperties(
            size, nSlices, nStacks, totalMass);
    }
    else if (hasElement(geometryEle, "cylinder"))
    {
      tinyxml2::XMLElement* ellipsoidEle = getElement(geometryEle, "cylinder");
      double radius  = getValueDouble(ellipsoidEle, "radius");
      double height  = getValueDouble(ellipsoidEle, "height");
      double nSlices = getValueDouble(ellipsoidEle, "num_slices");
      double nStacks = getValueDouble(ellipsoidEle, "num_stacks");
      double nRings = getValueDouble(ellipsoidEle, "num_rings");
      softProperties = dynamics::SoftBodyNodeHelper::makeCylinderProperties(
            radius, height, nSlices, nStacks, nRings, totalMass);
    }
    else
    {
      dterr << "Unknown soft shape.\n";
    }

    // kv
    if (hasElement(softShapeEle, "kv"))
    {
      softProperties.mKv = getValueDouble(softShapeEle, "kv");
    }

    // ke
    if (hasElement(softShapeEle, "ke"))
    {
      softProperties.mKe = getValueDouble(softShapeEle, "ke");
    }

    // damp
    if (hasElement(softShapeEle, "damp"))
    {
      softProperties.mDampCoeff = getValueDouble(softShapeEle, "damp");
    }
  }

  SDFBodyNode sdfBodyNode;
  sdfBodyNode.properties =
      Eigen::make_aligned_shared<dynamics::SoftBodyNode::Properties>(
        *standardProperties, softProperties);
  sdfBodyNode.initTransform = standardSDF.initTransform;
  sdfBodyNode.type = "soft";

  return sdfBodyNode;
}

common::ResourceRetrieverPtr getResourceRetriever(
    const common::ResourceRetrieverPtr& _retriever);

}  // namespace utils
}  // namespace dart
<commit_msg>Fix typo: filUri --> fileUri<commit_after>/*
 * Copyright (c) 2014-2015, Georgia Tech Research Corporation
 * All rights reserved.
 *
 * Author(s): Jeongseok Lee <jslee02@gmail.com>
 *
 * Georgia Tech Graphics Lab and Humanoid Robotics Lab
 *
 * Directed by Prof. C. Karen Liu and Prof. Mike Stilman
 * <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu>
 *
 * This file is provided under the following "BSD-style" License:
 *   Redistribution and use in source and binary forms, with or
 *   without modification, are permitted provided that the following
 *   conditions are met:
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * Redistributions in binary form must reproduce the above
 *     copyright notice, this list of conditions and the following
 *     disclaimer in the documentation and/or other materials provided
 *     with the distribution.
 *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
 *   CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
 *   INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 *   MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR
 *   CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 *   USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
 *   AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 *   LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
 *   ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 *   POSSIBILITY OF SUCH DAMAGE.
 */

#include "dart/utils/sdf/SoftSdfParser.h"

#include <map>
#include <iostream>
#include <fstream>

#include "dart/common/Console.h"
#include "dart/collision/dart/DARTCollisionDetector.h"
#include "dart/collision/fcl/FCLCollisionDetector.h"
// #include "dart/collision/fcl_mesh/FCLMeshCollisionDetector.h"
#include "dart/dynamics/Shape.h"
#include "dart/dynamics/BoxShape.h"
#include "dart/dynamics/CylinderShape.h"
#include "dart/dynamics/EllipsoidShape.h"
#include "dart/dynamics/WeldJoint.h"
#include "dart/dynamics/RevoluteJoint.h"
#include "dart/dynamics/PrismaticJoint.h"
#include "dart/dynamics/TranslationalJoint.h"
#include "dart/dynamics/BallJoint.h"
#include "dart/dynamics/FreeJoint.h"
#include "dart/dynamics/ScrewJoint.h"
#include "dart/dynamics/UniversalJoint.h"
#include "dart/simulation/World.h"
#include "dart/utils/SkelParser.h"

#include "dart/collision/fcl_mesh/FCLMeshCollisionDetector.h"
#include "dart/dynamics/SoftMeshShape.h"
#include "dart/dynamics/SoftBodyNode.h"
#include "dart/dynamics/Skeleton.h"
#include "dart/simulation/World.h"

namespace dart {
namespace utils {

//==============================================================================
simulation::WorldPtr SoftSdfParser::readSoftSdfFile(
  const common::Uri& _fileUri, const common::ResourceRetrieverPtr& _retriever)
{
  return SdfParser::readSdfFile(_fileUri, getResourceRetriever(_retriever),
    static_cast<simulation::WorldPtr (*)(
      tinyxml2::XMLElement*, const std::string&,
      const common::ResourceRetrieverPtr&)>(&SoftSdfParser::readWorld));
}

//==============================================================================
dynamics::SkeletonPtr SoftSdfParser::readSkeleton(
    const common::Uri& _fileUri, const common::ResourceRetrieverPtr& _retriever)
{
  return SdfParser::readSkeleton(_fileUri, getResourceRetriever(_retriever),
    static_cast<dynamics::SkeletonPtr (*)(
      tinyxml2::XMLElement*, const std::string&,
      const common::ResourceRetrieverPtr&)>(&SoftSdfParser::readSkeleton));
}

bool SoftSdfParser::createSoftPair(
    dynamics::SkeletonPtr skeleton,
    dynamics::BodyNode* parent,
    const SDFJoint& newJoint,
    const SDFBodyNode& newBody)
{
  std::pair<dynamics::Joint*, dynamics::BodyNode*> pair;
  if(newBody.type.empty())
    pair = createJointAndNodePair<dynamics::BodyNode>(
          skeleton, parent, newJoint, newBody);
  else if(std::string("soft") == newBody.type)
    pair = createJointAndNodePair<dynamics::SoftBodyNode>(
          skeleton, parent, newJoint, newBody);
  else
  {
    dterr << "[SoftSdfParser::createSoftPair] Unsupported Link type: "
          << newBody.type << "\n";
    return false;
  }

  if(!pair.first || !pair.second)
    return false;

  return true;
}

simulation::WorldPtr SoftSdfParser::readWorld(
    tinyxml2::XMLElement* _worldElement,
    const std::string& _skelPath,
    const common::ResourceRetrieverPtr& _retriever)
{
  return SdfParser::readWorld(_worldElement, _skelPath, _retriever,
    static_cast<dynamics::SkeletonPtr (*)(
      tinyxml2::XMLElement*, const std::string&,
      const common::ResourceRetrieverPtr&)>(&SoftSdfParser::readSkeleton));
}

dynamics::SkeletonPtr SoftSdfParser::readSkeleton(
    tinyxml2::XMLElement* _skeletonElement,
    const std::string& _skelPath,
    const common::ResourceRetrieverPtr& _retriever)
{
  return SdfParser::readSkeleton(_skeletonElement, _skelPath, _retriever,
                                 &readSoftBodyNode, &createSoftPair);
}

SdfParser::SDFBodyNode SoftSdfParser::readSoftBodyNode(
    tinyxml2::XMLElement* _softBodyNodeElement,
    const Eigen::Isometry3d& _skeletonFrame,
    const std::string& _skelPath,
    const common::ResourceRetrieverPtr& _retriever)
{
  //---------------------------------- Note ------------------------------------
  // SoftBodyNode is created if _softBodyNodeElement has <soft_shape>.
  // Otherwise, BodyNode is created.

  //----------------------------------------------------------------------------
  assert(_softBodyNodeElement != nullptr);

  // If _softBodyNodeElement has no <soft_shape>, return rigid body node
  if (!hasElement(_softBodyNodeElement, "soft_shape"))
  {
    return SdfParser::readBodyNode(
          _softBodyNodeElement, _skeletonFrame, _skelPath, _retriever);
  }

  SDFBodyNode standardSDF =
      SdfParser::readBodyNode(_softBodyNodeElement, _skeletonFrame, _skelPath, _retriever);

  BodyPropPtr standardProperties = standardSDF.properties;

  dynamics::SoftBodyNode::UniqueProperties softProperties;

  //----------------------------------------------------------------------------
  // Soft properties
  if (hasElement(_softBodyNodeElement, "soft_shape"))
  {
    tinyxml2::XMLElement* softShapeEle
        = getElement(_softBodyNodeElement, "soft_shape");

    // mass
    double totalMass = getValueDouble(softShapeEle, "total_mass");

    // pose
    Eigen::Isometry3d T = Eigen::Isometry3d::Identity();
    if (hasElement(softShapeEle, "pose"))
      T = getValueIsometry3dWithExtrinsicRotation(softShapeEle, "pose");

    // geometry
    tinyxml2::XMLElement* geometryEle = getElement(softShapeEle, "geometry");
    if (hasElement(geometryEle, "box"))
    {
      tinyxml2::XMLElement* boxEle = getElement(geometryEle, "box");
      Eigen::Vector3d size  = getValueVector3d(boxEle, "size");
      Eigen::Vector3i frags = getValueVector3i(boxEle, "frags");
      softProperties = dynamics::SoftBodyNodeHelper::makeBoxProperties(
            size, T, frags, totalMass);
    }
    else if (hasElement(geometryEle, "ellipsoid"))
    {
      tinyxml2::XMLElement* ellipsoidEle = getElement(geometryEle, "ellipsoid");
      Eigen::Vector3d size = getValueVector3d(ellipsoidEle, "size");
      double nSlices       = getValueDouble(ellipsoidEle, "num_slices");
      double nStacks       = getValueDouble(ellipsoidEle, "num_stacks");
      softProperties = dynamics::SoftBodyNodeHelper::makeEllipsoidProperties(
            size, nSlices, nStacks, totalMass);
    }
    else if (hasElement(geometryEle, "cylinder"))
    {
      tinyxml2::XMLElement* ellipsoidEle = getElement(geometryEle, "cylinder");
      double radius  = getValueDouble(ellipsoidEle, "radius");
      double height  = getValueDouble(ellipsoidEle, "height");
      double nSlices = getValueDouble(ellipsoidEle, "num_slices");
      double nStacks = getValueDouble(ellipsoidEle, "num_stacks");
      double nRings = getValueDouble(ellipsoidEle, "num_rings");
      softProperties = dynamics::SoftBodyNodeHelper::makeCylinderProperties(
            radius, height, nSlices, nStacks, nRings, totalMass);
    }
    else
    {
      dterr << "Unknown soft shape.\n";
    }

    // kv
    if (hasElement(softShapeEle, "kv"))
    {
      softProperties.mKv = getValueDouble(softShapeEle, "kv");
    }

    // ke
    if (hasElement(softShapeEle, "ke"))
    {
      softProperties.mKe = getValueDouble(softShapeEle, "ke");
    }

    // damp
    if (hasElement(softShapeEle, "damp"))
    {
      softProperties.mDampCoeff = getValueDouble(softShapeEle, "damp");
    }
  }

  SDFBodyNode sdfBodyNode;
  sdfBodyNode.properties =
      Eigen::make_aligned_shared<dynamics::SoftBodyNode::Properties>(
        *standardProperties, softProperties);
  sdfBodyNode.initTransform = standardSDF.initTransform;
  sdfBodyNode.type = "soft";

  return sdfBodyNode;
}

common::ResourceRetrieverPtr getResourceRetriever(
    const common::ResourceRetrieverPtr& _retriever);

}  // namespace utils
}  // namespace dart
<|endoftext|>


<commit_before>/*
* Copyright (C) 2008-2010 J-P Nurmi jpnurmi@gmail.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* $Id$
*/

#include "messageview.h"
#include "session.h"
#include "settings.h"
#include "completer.h"
#include "application.h"
#include <QShortcut>
#include <QKeyEvent>
#include <QDebug>
#include <irccommand.h>
#include <ircprefix.h>
#include <ircutil.h>
#include <irc.h>
#include "commandparser.h"

MessageView::MessageView(IrcSession* session, QWidget* parent) :
    QWidget(parent)
{
    d.setupUi(this);

    setFocusProxy(d.editFrame->lineEdit());
    d.textBrowser->installEventFilter(this);
    d.textBrowser->viewport()->installEventFilter(this);

    d.session = session;
    d.formatter.setHightlights(QStringList(session->nickName()));

    // TODO: d.editFrame->completer()->setModel(d.model);
    connect(d.editFrame, SIGNAL(send(QString)), this, SLOT(onSend(QString)));
    connect(d.editFrame, SIGNAL(typed(QString)), this, SLOT(showHelp(QString)));

    d.helpLabel->hide();
    d.findFrame->setTextEdit(d.textBrowser);

    QShortcut* shortcut = new QShortcut(Qt::Key_Escape, this);
    connect(shortcut, SIGNAL(activated()), this, SLOT(onEscPressed()));

    connect(qApp, SIGNAL(settingsChanged(Settings)), this, SLOT(applySettings(Settings)));
    applySettings(Application::settings());
}

MessageView::~MessageView()
{
}

QString MessageView::receiver() const
{
    return d.receiver;
}

void MessageView::setReceiver(const QString& receiver)
{
    d.receiver = receiver;
}

void MessageView::showHelp(const QString& text, bool error)
{
    /* TODO:
    QString syntax;
    if (text == "/")
    {
        QStringList commands = IrcMessage::availableCommands();
        commands.sort();
        syntax = commands.join(" ");
    }
    else if (text.startsWith('/'))
    {
        QString command = text.mid(1).split(' ', QString::SkipEmptyParts).value(0).toUpper();
        IrcMessage* message = IrcMessage::create(command, this);
        if (message)
            syntax = message->syntax();
        delete message;
    }
    d.helpLabel->setVisible(!syntax.isEmpty());
    QPalette pal;
    if (error)
        pal.setColor(QPalette::WindowText, Qt::red);
    d.helpLabel->setPalette(pal);
    d.helpLabel->setText(syntax);*/
}

void MessageView::appendMessage(const QString& message)
{
    // workaround the link activation merge char format bug
//    if (message.endsWith(""))
//        message += " ";

    if (!message.isEmpty())
        d.textBrowser->append(message);
}

bool MessageView::eventFilter(QObject* receiver, QEvent* event)
{
    Q_UNUSED(receiver);
    if (event->type() == QEvent::KeyPress)
    {
        QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
        // for example:
        // - Ctrl+C goes to the browser
        // - Ctrl+V goes to the line edit
        // - Shift+7 ("/") goes to the line edit
        switch (keyEvent->key())
        {
            case Qt::Key_Shift:
            case Qt::Key_Control:
            case Qt::Key_Meta:
            case Qt::Key_Alt:
            case Qt::Key_AltGr:
                break;
            default:
                if (!keyEvent->matches(QKeySequence::Copy))
                {
                    QApplication::sendEvent(d.editFrame->lineEdit(), keyEvent);
                    d.editFrame->lineEdit()->setFocus();
                    return true;
                }
                break;
        }
    }
    return false;
}

void MessageView::onEscPressed()
{
    d.helpLabel->hide();
    d.findFrame->hide();
    setFocus(Qt::OtherFocusReason);
}

void MessageView::onSend(const QString& text)
{
    // TODO: query, help, check empty txt...
    IrcCommand* cmd = CommandParser::parseCommand(d.receiver, text);
    if (cmd)
    {
        d.session->sendCommand(cmd);

        if (cmd->type() == IrcCommand::Message)
        {
            IrcPrivateMessage msg;
            msg.initFrom(d.session->nickName(), cmd->parameters());
            receiveMessage(&msg);
        }
    }
}

void MessageView::applySettings(const Settings& settings)
{
    d.formatter.setTimeStamp(settings.timeStamp);
    d.textBrowser->setFont(settings.font);
    d.textBrowser->document()->setMaximumBlockCount(settings.maxBlockCount);

    QString backgroundColor = settings.colors.value(Settings::Background);
    d.textBrowser->setStyleSheet(QString("QTextBrowser { background-color: %1 }").arg(backgroundColor));

    d.textBrowser->document()->setDefaultStyleSheet(
        QString(
            ".highlight { color: %1 }"
            ".message   { color: %2 }"
            ".notice    { color: %3 }"
            ".action    { color: %4 }"
            ".event     { color: %5 }"
        ).arg(settings.colors.value((Settings::Highlight)))
         .arg(settings.colors.value((Settings::Message)))
         .arg(settings.colors.value((Settings::Notice)))
         .arg(settings.colors.value((Settings::Action)))
         .arg(settings.colors.value((Settings::Event))));
}

void MessageView::receiveMessage(IrcMessage* message)
{
    bool append = true;
    bool hilite = false;
    bool matches = false;

    switch (message->type())
    {
    case IrcMessage::Join:
        append = Application::settings().messages.value(Settings::Joins);
        hilite = Application::settings().highlights.value(Settings::Joins);
        break;
    case IrcMessage::Kick:
        append = Application::settings().messages.value(Settings::Kicks);
        hilite = Application::settings().highlights.value(Settings::Kicks);
        break;
    case IrcMessage::Mode:
        append = Application::settings().messages.value(Settings::Modes);
        hilite = Application::settings().highlights.value(Settings::Modes);
        break;
    case IrcMessage::Nick:
        append = Application::settings().messages.value(Settings::Nicks);
        hilite = Application::settings().highlights.value(Settings::Nicks);
        break;
    case IrcMessage::Notice:
        matches = static_cast<IrcNoticeMessage*>(message)->message().contains(d.session->nickName());
        hilite = true;
        break;
    case IrcMessage::Part:
        append = Application::settings().messages.value(Settings::Parts);
        hilite = Application::settings().highlights.value(Settings::Parts);
        break;
    case IrcMessage::Private:
        matches = !isChannelView() || static_cast<IrcPrivateMessage*>(message)->message().contains(d.session->nickName());
        hilite = true;
        break;
    case IrcMessage::Quit:
        append = Application::settings().messages.value(Settings::Quits);
        hilite = Application::settings().highlights.value(Settings::Quits);
        break;
    case IrcMessage::Topic:
        append = Application::settings().messages.value(Settings::Topics);
        hilite = Application::settings().highlights.value(Settings::Topics);
        break;
    case IrcMessage::Unknown:
        qWarning() << "unknown:" << message->prefix() << message->parameters();
        append = false;
        break;
    case IrcMessage::Invite:
    case IrcMessage::Numeric:
    case IrcMessage::Ping:
    case IrcMessage::Pong:
    case IrcMessage::Error:
        break;
    }

    if (matches)
        emit alert(this, true);
    else if (hilite)
        emit highlight(this, true);
    if (append)
        appendMessage(d.formatter.formatMessage(message));
}

bool MessageView::isChannelView() const
{
    if (d.receiver.isEmpty())
        return false;

    switch (d.receiver.at(0).unicode())
    {
        case '#':
        case '&':
        case '!':
        case '+':
            return true;
        default:
            return false;
    }
}
<commit_msg>example: interactive help is back<commit_after>/*
* Copyright (C) 2008-2010 J-P Nurmi jpnurmi@gmail.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* $Id$
*/

#include "messageview.h"
#include "session.h"
#include "settings.h"
#include "completer.h"
#include "application.h"
#include <QShortcut>
#include <QKeyEvent>
#include <QDebug>
#include <irccommand.h>
#include <ircprefix.h>
#include <ircutil.h>
#include <irc.h>
#include "commandparser.h"

MessageView::MessageView(IrcSession* session, QWidget* parent) :
    QWidget(parent)
{
    d.setupUi(this);

    setFocusProxy(d.editFrame->lineEdit());
    d.textBrowser->installEventFilter(this);
    d.textBrowser->viewport()->installEventFilter(this);

    d.session = session;
    d.formatter.setHightlights(QStringList(session->nickName()));

    // TODO: d.editFrame->completer()->setModel(d.model);
    connect(d.editFrame, SIGNAL(send(QString)), this, SLOT(onSend(QString)));
    connect(d.editFrame, SIGNAL(typed(QString)), this, SLOT(showHelp(QString)));

    d.helpLabel->hide();
    d.findFrame->setTextEdit(d.textBrowser);

    QShortcut* shortcut = new QShortcut(Qt::Key_Escape, this);
    connect(shortcut, SIGNAL(activated()), this, SLOT(onEscPressed()));

    connect(qApp, SIGNAL(settingsChanged(Settings)), this, SLOT(applySettings(Settings)));
    applySettings(Application::settings());
}

MessageView::~MessageView()
{
}

QString MessageView::receiver() const
{
    return d.receiver;
}

void MessageView::setReceiver(const QString& receiver)
{
    d.receiver = receiver;
}

void MessageView::showHelp(const QString& text, bool error)
{
    QString syntax;
    if (text == "/")
    {
        QStringList commands = CommandParser::availableCommands();
        syntax = commands.join(" ");
    }
    else if (text.startsWith('/'))
    {
        QString command = text.mid(1).split(' ', QString::SkipEmptyParts).value(0);
        if (!error)
            command = CommandParser::suggestedCommand(command);
        syntax = CommandParser::syntax(command);
        if (syntax.isEmpty() && error)
            syntax = tr("Unknown command '%1'").arg(command.toUpper());
    }

    d.helpLabel->setVisible(!syntax.isEmpty());
    QPalette pal;
    if (error)
        pal.setColor(QPalette::WindowText, Qt::red);
    d.helpLabel->setPalette(pal);
    d.helpLabel->setText(syntax);
}

void MessageView::appendMessage(const QString& message)
{
    // workaround the link activation merge char format bug
//    if (message.endsWith(""))
//        message += " ";

    if (!message.isEmpty())
        d.textBrowser->append(message);
}

bool MessageView::eventFilter(QObject* receiver, QEvent* event)
{
    Q_UNUSED(receiver);
    if (event->type() == QEvent::KeyPress)
    {
        QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
        // for example:
        // - Ctrl+C goes to the browser
        // - Ctrl+V goes to the line edit
        // - Shift+7 ("/") goes to the line edit
        switch (keyEvent->key())
        {
            case Qt::Key_Shift:
            case Qt::Key_Control:
            case Qt::Key_Meta:
            case Qt::Key_Alt:
            case Qt::Key_AltGr:
                break;
            default:
                if (!keyEvent->matches(QKeySequence::Copy))
                {
                    QApplication::sendEvent(d.editFrame->lineEdit(), keyEvent);
                    d.editFrame->lineEdit()->setFocus();
                    return true;
                }
                break;
        }
    }
    return false;
}

void MessageView::onEscPressed()
{
    d.helpLabel->hide();
    d.findFrame->hide();
    setFocus(Qt::OtherFocusReason);
}

void MessageView::onSend(const QString& text)
{
    // TODO: query, help, check empty txt...
    IrcCommand* cmd = CommandParser::parseCommand(d.receiver, text);
    if (cmd)
    {
        d.session->sendCommand(cmd);

        if (cmd->type() == IrcCommand::Message)
        {
            IrcPrivateMessage msg;
            msg.initFrom(d.session->nickName(), cmd->parameters());
            receiveMessage(&msg);
        }
    }
    else
    {
        showHelp(text, true);
    }
}

void MessageView::applySettings(const Settings& settings)
{
    d.formatter.setTimeStamp(settings.timeStamp);
    d.textBrowser->setFont(settings.font);
    d.textBrowser->document()->setMaximumBlockCount(settings.maxBlockCount);

    QString backgroundColor = settings.colors.value(Settings::Background);
    d.textBrowser->setStyleSheet(QString("QTextBrowser { background-color: %1 }").arg(backgroundColor));

    d.textBrowser->document()->setDefaultStyleSheet(
        QString(
            ".highlight { color: %1 }"
            ".message   { color: %2 }"
            ".notice    { color: %3 }"
            ".action    { color: %4 }"
            ".event     { color: %5 }"
        ).arg(settings.colors.value((Settings::Highlight)))
         .arg(settings.colors.value((Settings::Message)))
         .arg(settings.colors.value((Settings::Notice)))
         .arg(settings.colors.value((Settings::Action)))
         .arg(settings.colors.value((Settings::Event))));
}

void MessageView::receiveMessage(IrcMessage* message)
{
    bool append = true;
    bool hilite = false;
    bool matches = false;

    switch (message->type())
    {
    case IrcMessage::Join:
        append = Application::settings().messages.value(Settings::Joins);
        hilite = Application::settings().highlights.value(Settings::Joins);
        break;
    case IrcMessage::Kick:
        append = Application::settings().messages.value(Settings::Kicks);
        hilite = Application::settings().highlights.value(Settings::Kicks);
        break;
    case IrcMessage::Mode:
        append = Application::settings().messages.value(Settings::Modes);
        hilite = Application::settings().highlights.value(Settings::Modes);
        break;
    case IrcMessage::Nick:
        append = Application::settings().messages.value(Settings::Nicks);
        hilite = Application::settings().highlights.value(Settings::Nicks);
        break;
    case IrcMessage::Notice:
        matches = static_cast<IrcNoticeMessage*>(message)->message().contains(d.session->nickName());
        hilite = true;
        break;
    case IrcMessage::Part:
        append = Application::settings().messages.value(Settings::Parts);
        hilite = Application::settings().highlights.value(Settings::Parts);
        break;
    case IrcMessage::Private:
        matches = !isChannelView() || static_cast<IrcPrivateMessage*>(message)->message().contains(d.session->nickName());
        hilite = true;
        break;
    case IrcMessage::Quit:
        append = Application::settings().messages.value(Settings::Quits);
        hilite = Application::settings().highlights.value(Settings::Quits);
        break;
    case IrcMessage::Topic:
        append = Application::settings().messages.value(Settings::Topics);
        hilite = Application::settings().highlights.value(Settings::Topics);
        break;
    case IrcMessage::Unknown:
        qWarning() << "unknown:" << message->prefix() << message->parameters();
        append = false;
        break;
    case IrcMessage::Invite:
    case IrcMessage::Numeric:
    case IrcMessage::Ping:
    case IrcMessage::Pong:
    case IrcMessage::Error:
        break;
    }

    if (matches)
        emit alert(this, true);
    else if (hilite)
        emit highlight(this, true);
    if (append)
        appendMessage(d.formatter.formatMessage(message));
}

bool MessageView::isChannelView() const
{
    if (d.receiver.isEmpty())
        return false;

    switch (d.receiver.at(0).unicode())
    {
        case '#':
        case '&':
        case '!':
        case '+':
            return true;
        default:
            return false;
    }
}
<|endoftext|>


<commit_before>/* perl-conduit.cc			KPilot
**
** Copyright (C) 2004 by Adriaan de Groot
**
** This file is part of the Perl conduit, a conduit for KPilot that
** is intended to showcase how to use perl code inside a conduit.
*/

/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation; either version 2.1 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

#ifdef DEBUG
#undef DEBUG
#define DEBUG (1)
#else
#define DEBUG (1)
#endif

#include "options.h"

#include "perl-conduit.h"  // The Conduit action
#include "perlconduit.h"   // The settings class

#include <qthread.h>
#include <qapplication.h>

#include <EXTERN.h>
#include <perl.h>

extern "C"
{
long version_conduit_perl = KPILOT_PLUGIN_API;
const char *id_conduit_perl =
	"$Id$";
}

/* From the cvs log mailing list:
Am Dienstag, 13. April 2004 22:26 schrieb Adriaan de Groot:
> On Tuesday 13 April 2004 20:53, Reinhold Kainhofer wrote:
> > rename fPerl to my_perl to make it compile again...
>
> Note that the renaming is needed because perl 5.8 is a brain-dead abortion,
> and the code works fine with perl 5.6.
*/
class PerlThread : public QThread
{
public:
	PerlThread(QObject *parent) : fParent(parent) { } ;
	virtual void run();

	QString result() const { return fResult; } ;

protected:
	QObject *fParent;
	PerlInterpreter *my_perl;

	QString fResult;
} ;

PerlConduit::PerlConduit(KPilotDeviceLink *d,
	const char *n,
	const QStringList &l) :
	ConduitAction(d,n,l)
{
	FUNCTIONSETUP;
#ifdef DEBUG
	DEBUGCONDUIT << id_conduit_perl << endl;
#endif
	fConduitName=i18n("Perl");

	(void) id_conduit_perl;
}

PerlConduit::~PerlConduit()
{
	FUNCTIONSETUP;
}

/* virtual */ bool PerlConduit::exec()
{
	FUNCTIONSETUP;

#ifdef DEBUG
	DEBUGCONDUIT << fname << ": In exec() @" << (unsigned long) this << endl;
#endif

	fThread = new PerlThread(this) ;
	fThread->start();
	startTickle();
	return true;
}

/* virtual */ bool PerlConduit::event(QEvent *e)
{
	FUNCTIONSETUP;

	if (e->type() == QEvent::User)
	{
#ifdef DEBUG
		DEBUGCONDUIT << fname << ": Perl thread done." << endl;
#endif
		QString r;
		addSyncLogEntry(i18n("Perl returned %1.").arg(fThread->result()));
		stopTickle();
		delayDone();
		return true;
	}
	else return ConduitAction::event(e);
}

static const char *perl_args[] = { "", "-e", "0" } ;

void PerlThread::run()
{
	FUNCTIONSETUP;

#ifdef DEBUG
	DEBUGCONDUIT << fname << ": Thread starting." << endl;
#endif

	my_perl = perl_alloc();
	perl_construct(my_perl);
	perl_parse(my_perl, NULL, 3, const_cast<char **>(perl_args), NULL);
	perl_run(my_perl);

	eval_pv(PerlConduitSettings::expression().latin1(),TRUE);

#ifdef DEBUG
	DEBUGCONDUIT << fname << ": Thread woken with " << SvIV(get_sv("a",FALSE)) << endl;
#endif

	fResult.setNum(SvIV(get_sv("a",FALSE)));

	perl_destruct(my_perl);
	perl_free(my_perl);

	QApplication::postEvent(fParent,new QEvent(QEvent::User));
}

<commit_msg>Avoid crashes when perl-script doesn't set $a<commit_after>/* perl-conduit.cc			KPilot
**
** Copyright (C) 2004 by Adriaan de Groot
**
** This file is part of the Perl conduit, a conduit for KPilot that
** is intended to showcase how to use perl code inside a conduit.
*/

/*
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU Lesser General Public License as published by
** the Free Software Foundation; either version 2.1 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU Lesser General Public License for more details.
**
** You should have received a copy of the GNU Lesser General Public License
** along with this program in a file called COPYING; if not, write to
** the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
** MA 02111-1307, USA.
*/

/*
** Bug reports and questions can be sent to kde-pim@kde.org
*/

/*
** This file is based on the perlembed examples, from
** http://search.cpan.org/dist/perl/pod/perlembed.pod
*/

#ifdef DEBUG
#undef DEBUG
#define DEBUG (1)
#else
#define DEBUG (1)
#endif

#include "options.h"

#include "perl-conduit.h"  // The Conduit action
#include "perlconduit.h"   // The settings class

#include <qthread.h>
#include <qapplication.h>

#include <EXTERN.h>
#include <perl.h>

extern "C"
{
long version_conduit_perl = KPILOT_PLUGIN_API;
const char *id_conduit_perl =
	"$Id$";
}

/* From the cvs log mailing list:
Am Dienstag, 13. April 2004 22:26 schrieb Adriaan de Groot:
> On Tuesday 13 April 2004 20:53, Reinhold Kainhofer wrote:
> > rename fPerl to my_perl to make it compile again...
>
> Note that the renaming is needed because perl 5.8 is a brain-dead abortion,
> and the code works fine with perl 5.6.
*/
class PerlThread : public QThread
{
public:
	PerlThread(QObject *parent) : fParent(parent) { } ;
	virtual void run();

	QString result() const { return fResult; } ;

protected:
	QObject *fParent;
	PerlInterpreter *my_perl;

	QString fResult;
} ;

PerlConduit::PerlConduit(KPilotDeviceLink *d,
	const char *n,
	const QStringList &l) :
	ConduitAction(d,n,l)
{
	FUNCTIONSETUP;
#ifdef DEBUG
	DEBUGCONDUIT << id_conduit_perl << endl;
#endif
	fConduitName=i18n("Perl");

	(void) id_conduit_perl;
}

PerlConduit::~PerlConduit()
{
	FUNCTIONSETUP;
}

/* virtual */ bool PerlConduit::exec()
{
	FUNCTIONSETUP;

#ifdef DEBUG
	DEBUGCONDUIT << fname << ": In exec() @" << (unsigned long) this << endl;
#endif

	fThread = new PerlThread(this) ;
	fThread->start();
	startTickle();
	return true;
}

/* virtual */ bool PerlConduit::event(QEvent *e)
{
	FUNCTIONSETUP;

	if (e->type() == QEvent::User)
	{
#ifdef DEBUG
		DEBUGCONDUIT << fname << ": Perl thread done." << endl;
#endif
		QString r;
		addSyncLogEntry(i18n("Perl returned %1.").arg(fThread->result()));
		stopTickle();
		delayDone();
		return true;
	}
	else return ConduitAction::event(e);
}

static const char *perl_args[] = { "", "-e", "0" } ;

void PerlThread::run()
{
	FUNCTIONSETUP;

#ifdef DEBUG
	DEBUGCONDUIT << fname << ": Thread starting." << endl;
#endif

	my_perl = perl_alloc();
	perl_construct(my_perl);
	perl_parse(my_perl, NULL, 3, const_cast<char **>(perl_args), NULL);
	perl_run(my_perl);

	eval_pv(PerlConduitSettings::expression().latin1(),TRUE);

	SV *retval = get_sv("a",FALSE);
	if (retval)
	{
		fResult.setNum(SvIV(retval));
	}
	else
	{
		fResult = i18n("No value");
	}

#ifdef DEBUG
	DEBUGCONDUIT << fname << ": Thread woken with " << fResult << endl;
#endif

	perl_destruct(my_perl);
	perl_free(my_perl);

	QApplication::postEvent(fParent,new QEvent(QEvent::User));
}

<|endoftext|>


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

#include "stdio.h"
#include "Physics_util.h"
#include "Constants.h"
#include "VmFunc.h"

extern void LOGI(const char* msg);
extern void LOGW(const char* msg);
extern void LOGE(const char* msg);

/*
 * Get b2Vec2 from emo.Vec2
 */
void getVec2Instance(HSQUIRRELVM v, int idx, b2Vec2* vec2) {
	getInstanceMemberAsFloat(v, idx, "x", &vec2->x);
	getInstanceMemberAsFloat(v, idx, "y", &vec2->y);
}

/*
 * Get b2Vec2 from emo.Vec2 of instance member
 */
void getVec2InstanceFromMember(HSQUIRRELVM v, int idx, const char* member, b2Vec2* vec2) {
	getInstanceMemberAsTable(v, idx, member, "x", &vec2->x);
	getInstanceMemberAsTable(v, idx, member, "y", &vec2->y);
}

/*
 * Push b2Vec2 as an array
 */
void pushVec2(HSQUIRRELVM v, b2Vec2 vec2) {
	sq_newarray(v, 0);

	sq_pushfloat(v, vec2.x);
	sq_arrayappend(v, -2);

	sq_pushfloat(v, vec2.y);
	sq_arrayappend(v, -2);
}

/*
 * get b2BodyDef from emo.BodyDef instance
 */
void getBodyDefInstance(HSQUIRRELVM v, int idx, b2BodyDef* def) {
	SQInteger btype;
	getInstanceMemberAsInteger(v, idx, "type", &btype);
	switch(btype) {
		case PHYSICS_BODY_STATIC:
			def->type = b2_staticBody;
			break;
		case PHYSICS_BODY_KINEMATIC:
			def->type = b2_kinematicBody;
			break;
		case PHYSICS_BODY_DYNAMIC:
			def->type = b2_dynamicBody;
			break;
	}
	getVec2InstanceFromMember(v, idx, "position", &def->position);
	getInstanceMemberAsFloat(v,  idx, "angle",    &def->angle);
	getVec2InstanceFromMember(v, idx, "linearVelocity",  &def->linearVelocity);
	getInstanceMemberAsFloat(v,  idx, "angularVelocity", &def->angularVelocity);
	getInstanceMemberAsFloat(v,  idx, "linearDamping",   &def->linearDamping);
	getInstanceMemberAsFloat(v,  idx, "angularDamping",  &def->angularDamping);
	getInstanceMemberAsBool(v,   idx, "allowSleep",      &def->allowSleep);
	getInstanceMemberAsBool(v,   idx, "awake",           &def->awake);
	getInstanceMemberAsBool(v,   idx, "fixedRotation",   &def->fixedRotation);
	getInstanceMemberAsBool(v,   idx, "bullet",          &def->bullet);
	getInstanceMemberAsBool(v,   idx, "active",          &def->active);
	getInstanceMemberAsFloat(v,  idx, "inertiaScale",    &def->inertiaScale);
}

/*
 * Get b2FixtureDef from emo.FixtureDef instance
 */
void getFixtureDefInstance(HSQUIRRELVM v, int idx, b2FixtureDef* def) {
	getInstanceMemberAsFloat(v,  idx, "friction",    &def->friction);
	getInstanceMemberAsFloat(v,  idx, "restitution", &def->restitution);
	getInstanceMemberAsFloat(v,  idx, "density",     &def->density);
	getInstanceMemberAsBool(v,   idx, "isSensor",    &def->isSensor);

	SQUserPointer ptr_shape;
	if (getInstanceMemberAsInstance(v, idx, "shape", "id", &ptr_shape)) {
		def->shape = reinterpret_cast<b2Shape*>(ptr_shape);
	}
}

/*
 * Get b2DistanceJointDef from emo.DistanceJointDef instance
 */
void getDistanceJointDef(HSQUIRRELVM v, int idx, b2DistanceJointDef* def) {
	getInstanceMemberAsFloat(v, idx, "frequencyHz", &def->frequencyHz);
	getInstanceMemberAsFloat(v, idx, "dampingRatio", &def->dampingRatio);
}

/*
 * Get b2FrictionJointDef from emo.FrictionJointDef instance
 */
void getFrictionJointDef(HSQUIRRELVM v, int idx, b2FrictionJointDef* def) {
	getInstanceMemberAsFloat(v, idx, "maxForce", &def->maxForce);
	getInstanceMemberAsFloat(v, idx, "maxTorque", &def->maxTorque);
}

/*
 * Get b2GearJointDef from emo.GearJointDef instance
 */
void getGearJointDef(HSQUIRRELVM v, int idx, b2GearJointDef* def) {
	getInstanceMemberAsFloat(v, idx, "ratio", &def->ratio);

	SQUserPointer ptr_joint1;
	if (getInstanceMemberAsUserPointer(v, idx, "joint1", "id", &ptr_joint1)) {
		def->joint1 = reinterpret_cast<b2Joint*>(ptr_joint1);
	}

	SQUserPointer ptr_joint2;
	if (getInstanceMemberAsUserPointer(v, idx, "joint2", "id", &ptr_joint2)) {
		def->joint2 = reinterpret_cast<b2Joint*>(ptr_joint2);
	}

	SQUserPointer ptr_bodyA;
	if (getInstanceMemberAsUserPointer(v, idx, "bodyA", "id", &ptr_bodyA)) {
		def->bodyA = reinterpret_cast<b2Body*>(ptr_bodyA);
	}

	SQUserPointer ptr_bodyB;
	if (getInstanceMemberAsUserPointer(v, idx, "bodyB", "id", &ptr_bodyB)) {
		def->bodyB = reinterpret_cast<b2Body*>(ptr_bodyB);
	}
}

/*
 * Get b2LineJointDef from emo.LineJointDef instance
 */
void getLineJointDef(HSQUIRRELVM v, int idx, b2LineJointDef* def) {
	getInstanceMemberAsBool(v, idx, "enableLimit", &def->enableLimit);
	getInstanceMemberAsFloat(v, idx, "lowerTranslation", &def->lowerTranslation);
	getInstanceMemberAsFloat(v, idx, "upperTranslation", &def->upperTranslation);
	getInstanceMemberAsBool(v, idx, "enableMotor", &def->enableMotor);
	getInstanceMemberAsFloat(v, idx, "maxMotorForce", &def->maxMotorForce);
	getInstanceMemberAsFloat(v, idx, "motorSpeed", &def->motorSpeed);
}

/*
 * Get b2PrismaticJointDef from emo.PrismaticJointDef instance
 */
void getPrismaticJointDef(HSQUIRRELVM v, int idx, b2PrismaticJointDef* def) {
	getInstanceMemberAsBool(v, idx, "enableLimit", &def->enableLimit);
	getInstanceMemberAsFloat(v, idx, "lowerTranslation", &def->lowerTranslation);
	getInstanceMemberAsFloat(v, idx, "upperTranslation", &def->upperTranslation);
	getInstanceMemberAsBool(v, idx, "enableMotor", &def->enableMotor);
	getInstanceMemberAsFloat(v, idx, "maxMotorForce", &def->maxMotorForce);
	getInstanceMemberAsFloat(v, idx, "motorSpeed", &def->motorSpeed);
}

/*
 * Get b2PulleyJointDef from emo.PulleyJointDef instance
 */
void getPulleyJointDef(HSQUIRRELVM v, int idx, b2PulleyJointDef* def) {
	// no item to convert
}

/*
 * Get b2RevoluteJointDef from emo.RevoluteJointDe instance
 */
void getRevoluteJointDef(HSQUIRRELVM v, int idx, b2RevoluteJointDef* def) {
	getInstanceMemberAsBool(v, idx, "enableLimit", &def->enableLimit);
	getInstanceMemberAsFloat(v, idx, "lowerAngle", &def->lowerAngle);
	getInstanceMemberAsFloat(v, idx, "upperAngle", &def->upperAngle);
	getInstanceMemberAsBool(v, idx, "enableMotor", &def->enableMotor);
	getInstanceMemberAsFloat(v, idx, "maxMotorTorque", &def->maxMotorTorque);
	getInstanceMemberAsFloat(v, idx, "motorSpeed", &def->motorSpeed);
}

/*
 * Get b2WeldJointDef from emo.WeldJointDef instance
 */
void getWeldJointDef(HSQUIRRELVM v, int idx, b2WeldJointDef* def) {
	// no item to convert
}

/*
 * Get b2MouseJointDef from emo.MouseJointDef instance
 */
void getMouseJointDef(HSQUIRRELVM v, int idx, b2MouseJointDef* def) {
	getInstanceMemberAsFloat(v, idx, "maxForce",     &def->maxForce);
	getInstanceMemberAsFloat(v, idx, "frequencyHz",  &def->frequencyHz);
	getInstanceMemberAsFloat(v, idx, "dampingRatio", &def->dampingRatio);
	getInstanceMemberAsBool(v, idx,  "collideConnected", &def->collideConnected);

	getVec2InstanceFromMember(v, idx, "target",  &def->target);

	SQUserPointer ptr_bodyA;
	if (getInstanceMemberAsUserPointer(v, idx, "bodyA", "id", &ptr_bodyA)) {
		def->bodyA = reinterpret_cast<b2Body*>(ptr_bodyA);
	}

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

#include "stdio.h"
#include "Physics_util.h"
#include "Constants.h"
#include "VmFunc.h"

extern void LOGI(const char* msg);
extern void LOGW(const char* msg);
extern void LOGE(const char* msg);

/*
 * Get b2Vec2 from emo.Vec2
 */
void getVec2Instance(HSQUIRRELVM v, int idx, b2Vec2* vec2) {
	getInstanceMemberAsFloat(v, idx, "x", &vec2->x);
	getInstanceMemberAsFloat(v, idx, "y", &vec2->y);
}

/*
 * Get b2Vec2 from emo.Vec2 of instance member
 */
void getVec2InstanceFromMember(HSQUIRRELVM v, int idx, const char* member, b2Vec2* vec2) {
	getInstanceMemberAsTable(v, idx, member, "x", &vec2->x);
	getInstanceMemberAsTable(v, idx, member, "y", &vec2->y);
}

/*
 * Push b2Vec2 as an array
 */
void pushVec2(HSQUIRRELVM v, b2Vec2 vec2) {
	sq_newarray(v, 0);

	sq_pushfloat(v, vec2.x);
	sq_arrayappend(v, -2);

	sq_pushfloat(v, vec2.y);
	sq_arrayappend(v, -2);
}

/*
 * get b2BodyDef from emo.BodyDef instance
 */
void getBodyDefInstance(HSQUIRRELVM v, int idx, b2BodyDef* def) {
	SQInteger btype;
	getInstanceMemberAsInteger(v, idx, "type", &btype);
	switch(btype) {
		case PHYSICS_BODY_STATIC:
			def->type = b2_staticBody;
			break;
		case PHYSICS_BODY_KINEMATIC:
			def->type = b2_kinematicBody;
			break;
		case PHYSICS_BODY_DYNAMIC:
			def->type = b2_dynamicBody;
			break;
	}
	getVec2InstanceFromMember(v, idx, "position", &def->position);
	getInstanceMemberAsFloat(v,  idx, "angle",    &def->angle);
	getVec2InstanceFromMember(v, idx, "linearVelocity",  &def->linearVelocity);
	getInstanceMemberAsFloat(v,  idx, "angularVelocity", &def->angularVelocity);
	getInstanceMemberAsFloat(v,  idx, "linearDamping",   &def->linearDamping);
	getInstanceMemberAsFloat(v,  idx, "angularDamping",  &def->angularDamping);
	getInstanceMemberAsBool(v,   idx, "allowSleep",      &def->allowSleep);
	getInstanceMemberAsBool(v,   idx, "awake",           &def->awake);
	getInstanceMemberAsBool(v,   idx, "fixedRotation",   &def->fixedRotation);
	getInstanceMemberAsBool(v,   idx, "bullet",          &def->bullet);
	getInstanceMemberAsBool(v,   idx, "active",          &def->active);
	getInstanceMemberAsFloat(v,  idx, "inertiaScale",    &def->inertiaScale);
}

/*
 * Get b2FixtureDef from emo.FixtureDef instance
 */
void getFixtureDefInstance(HSQUIRRELVM v, int idx, b2FixtureDef* def) {
	getInstanceMemberAsFloat(v,  idx, "friction",    &def->friction);
	getInstanceMemberAsFloat(v,  idx, "restitution", &def->restitution);
	getInstanceMemberAsFloat(v,  idx, "density",     &def->density);
	getInstanceMemberAsBool(v,   idx, "isSensor",    &def->isSensor);

	SQUserPointer ptr_shape;
	if (getInstanceMemberAsInstance(v, idx, "shape", "id", &ptr_shape)) {
		def->shape = reinterpret_cast<b2Shape*>(ptr_shape);
	}
}

/*
 * Get b2DistanceJointDef from emo.DistanceJointDef instance
 */
void getDistanceJointDef(HSQUIRRELVM v, int idx, b2DistanceJointDef* def) {
	getInstanceMemberAsFloat(v, idx, "frequencyHz", &def->frequencyHz);
	getInstanceMemberAsFloat(v, idx, "dampingRatio", &def->dampingRatio);
}

/*
 * Get b2FrictionJointDef from emo.FrictionJointDef instance
 */
void getFrictionJointDef(HSQUIRRELVM v, int idx, b2FrictionJointDef* def) {
	getInstanceMemberAsFloat(v, idx, "maxForce", &def->maxForce);
	getInstanceMemberAsFloat(v, idx, "maxTorque", &def->maxTorque);
}

/*
 * Get b2GearJointDef from emo.GearJointDef instance
 */
void getGearJointDef(HSQUIRRELVM v, int idx, b2GearJointDef* def) {
	getInstanceMemberAsFloat(v, idx, "ratio", &def->ratio);

	SQUserPointer ptr_joint1;
	if (getInstanceMemberAsUserPointer(v, idx, "joint1", "id", &ptr_joint1)) {
		def->joint1 = reinterpret_cast<b2Joint*>(ptr_joint1);
	}

	SQUserPointer ptr_joint2;
	if (getInstanceMemberAsUserPointer(v, idx, "joint2", "id", &ptr_joint2)) {
		def->joint2 = reinterpret_cast<b2Joint*>(ptr_joint2);
	}

	SQUserPointer ptr_bodyA;
	if (getInstanceMemberAsUserPointer(v, idx, "bodyA", "id", &ptr_bodyA)) {
		def->bodyA = reinterpret_cast<b2Body*>(ptr_bodyA);
	}

	SQUserPointer ptr_bodyB;
	if (getInstanceMemberAsUserPointer(v, idx, "bodyB", "id", &ptr_bodyB)) {
		def->bodyB = reinterpret_cast<b2Body*>(ptr_bodyB);
	}
}

/*
 * Get b2LineJointDef from emo.LineJointDef instance
 */
void getLineJointDef(HSQUIRRELVM v, int idx, b2LineJointDef* def) {
	getInstanceMemberAsBool(v, idx, "enableLimit", &def->enableLimit);
	getInstanceMemberAsFloat(v, idx, "lowerTranslation", &def->lowerTranslation);
	getInstanceMemberAsFloat(v, idx, "upperTranslation", &def->upperTranslation);
	getInstanceMemberAsBool(v, idx, "enableMotor", &def->enableMotor);
	getInstanceMemberAsFloat(v, idx, "maxMotorForce", &def->maxMotorForce);
	getInstanceMemberAsFloat(v, idx, "motorSpeed", &def->motorSpeed);
}

/*
 * Get b2PrismaticJointDef from emo.PrismaticJointDef instance
 */
void getPrismaticJointDef(HSQUIRRELVM v, int idx, b2PrismaticJointDef* def) {
	getInstanceMemberAsBool(v, idx, "enableLimit", &def->enableLimit);
	getInstanceMemberAsFloat(v, idx, "lowerTranslation", &def->lowerTranslation);
	getInstanceMemberAsFloat(v, idx, "upperTranslation", &def->upperTranslation);
	getInstanceMemberAsBool(v, idx, "enableMotor", &def->enableMotor);
	getInstanceMemberAsFloat(v, idx, "maxMotorForce", &def->maxMotorForce);
	getInstanceMemberAsFloat(v, idx, "motorSpeed", &def->motorSpeed);
}

/*
 * Get b2PulleyJointDef from emo.PulleyJointDef instance
 */
void getPulleyJointDef(HSQUIRRELVM v, int idx, b2PulleyJointDef* def) {
	// no item to convert
}

/*
 * Get b2RevoluteJointDef from emo.RevoluteJointDe instance
 */
void getRevoluteJointDef(HSQUIRRELVM v, int idx, b2RevoluteJointDef* def) {
	getInstanceMemberAsBool(v, idx, "enableLimit", &def->enableLimit);
	getInstanceMemberAsFloat(v, idx, "lowerAngle", &def->lowerAngle);
	getInstanceMemberAsFloat(v, idx, "upperAngle", &def->upperAngle);
	getInstanceMemberAsBool(v, idx, "enableMotor", &def->enableMotor);
	getInstanceMemberAsFloat(v, idx, "maxMotorTorque", &def->maxMotorTorque);
	getInstanceMemberAsFloat(v, idx, "motorSpeed", &def->motorSpeed);
}

/*
 * Get b2WeldJointDef from emo.WeldJointDef instance
 */
void getWeldJointDef(HSQUIRRELVM v, int idx, b2WeldJointDef* def) {
	// no item to convert
}

/*
 * Get b2MouseJointDef from emo.MouseJointDef instance
 */
void getMouseJointDef(HSQUIRRELVM v, int idx, b2MouseJointDef* def) {
	getInstanceMemberAsFloat(v, idx, "maxForce",     &def->maxForce);
	getInstanceMemberAsFloat(v, idx, "frequencyHz",  &def->frequencyHz);
	getInstanceMemberAsFloat(v, idx, "dampingRatio", &def->dampingRatio);
	getInstanceMemberAsBool(v, idx,  "collideConnected", &def->collideConnected);

	getVec2InstanceFromMember(v, idx, "target",  &def->target);

	SQUserPointer ptr_bodyA;
	if (getInstanceMemberAsUserPointer(v, idx, "bodyA", "id", &ptr_bodyA)) {
		def->bodyA = reinterpret_cast<b2Body*>(ptr_bodyA);
	}

	SQUserPointer ptr_bodyB;
	if (getInstanceMemberAsUserPointer(v, idx, "bodyB", "id", &ptr_bodyB)) {
		def->bodyB = reinterpret_cast<b2Body*>(ptr_bodyB);
	}
}
<|endoftext|>


<commit_before>#include "SceneManager.h"
#include "Scene.h"

namespace Scheduler
{
	SceneManager::SceneManager() :
			routing_service(nullptr)
	{
	}

	Scene* SceneManager::createScene()
	{
		Scene *scene = scenes_factory.createObject();

		scene->setOperationsfactory(&operations_factory);
		scene->setOrdersFactory(&orders_factory);
		scene->setPerformersFactory(&performers_factory);
		scene->setSchedulesFactory(&schedules_factory);
		scene->setVehiclesFactory(&vehicles_factory);
		scene->setRunsFactory(&runs_factory);
		scene->setStopsFactory(&stops_factory);

		scene->setRoutingService(routing_service);
		scene->setScheduleActualizationAlgorithmsFactory(&schedule_actualization_algorithms_factory);

		scenes.insert(scene);
		return scene;
	}

	void SceneManager::destroyScene(Scene *scene)
	{
		scenes.erase(scene);
		scenes_factory.destroyObject(scene);
	}

	const Attribute* SceneManager::createAttribute(const char *name)
	{
		auto iter = attributes.find(name);
		if (iter != attributes.end()) return iter->second;

		Attribute* attribute = attributes_factory.createObject(name);
		attributes.emplace(name, attribute);

		return attribute;
	}

	SceneManager::~SceneManager()
	{
		for (Scene *scene: scenes) {
			destroyScene(scene);
		}
	}

	void SceneManager::setRoutingService(RoutingService *routing_service)
	{
		this->routing_service = routing_service;
	}

}<commit_msg>[bug] Fixed dumb deinitialization error<commit_after>#include "SceneManager.h"
#include "Scene.h"

namespace Scheduler
{
	SceneManager::SceneManager() :
			routing_service(nullptr)
	{
	}

	Scene* SceneManager::createScene()
	{
		Scene *scene = scenes_factory.createObject();

		scene->setOperationsfactory(&operations_factory);
		scene->setOrdersFactory(&orders_factory);
		scene->setPerformersFactory(&performers_factory);
		scene->setSchedulesFactory(&schedules_factory);
		scene->setVehiclesFactory(&vehicles_factory);
		scene->setRunsFactory(&runs_factory);
		scene->setStopsFactory(&stops_factory);

		scene->setRoutingService(routing_service);
		scene->setScheduleActualizationAlgorithmsFactory(&schedule_actualization_algorithms_factory);

		scenes.insert(scene);
		return scene;
	}

	void SceneManager::destroyScene(Scene *scene)
	{
		scenes.erase(scene);
		scenes_factory.destroyObject(scene);
	}

	const Attribute* SceneManager::createAttribute(const char *name)
	{
		auto iter = attributes.find(name);
		if (iter != attributes.end()) return iter->second;

		Attribute* attribute = attributes_factory.createObject(name);
		attributes.emplace(name, attribute);

		return attribute;
	}

	SceneManager::~SceneManager()
	{
		for (Scene *scene: scenes) {
			scenes_factory.destroyObject(scene);
		}
	}

	void SceneManager::setRoutingService(RoutingService *routing_service)
	{
		this->routing_service = routing_service;
	}

}<|endoftext|>


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

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

//! [includes]
#include "QmitkRegisterClasses.h"
#include "QmitkRenderWindow.h"

#include <mitkDataNodeFactory.h>
#include <mitkPointSet.h>
#include <mitkStandaloneDataStorage.h>

#include <itksys/SystemTools.hxx>
#include <QApplication>
#include <mitkOverlay2DLayouter.h>
#include <mitkOverlayManager.h>
#include <mitkTextOverlay2D.h>
#include <mitkTextOverlay3D.h>
//! [includes]

//##Documentation
//## @brief Load image (nrrd format) and display it in a 2D view
int main(int argc, char* argv[])
{
  QApplication qtapplication( argc, argv );

  if (argc < 2)
  {
    fprintf( stderr, "Usage:   %s [filename] \n\n", itksys::SystemTools::GetFilenameName(argv[0]).c_str() );
    return 1;
  }

  // Register Qmitk-dependent global instances
  QmitkRegisterClasses();

  //*************************************************************************
  // Part I: Basic initialization
  //*************************************************************************

  // Create a DataStorage
  // The DataStorage manages all data objects. It is used by the
  // rendering mechanism to render all data objects
  // We use the standard implementation mitk::StandaloneDataStorage.
  mitk::StandaloneDataStorage::Pointer dataStorage = mitk::StandaloneDataStorage::New();

  //*************************************************************************
  // Part II: Create some data by reading a file
  //*************************************************************************

  // Create a DataNodeFactory to read a data format supported
  // by the DataNodeFactory (many image formats, surface formats, etc.)
  mitk::DataNodeFactory::Pointer reader=mitk::DataNodeFactory::New();
  const char * filename = argv[1];
  try
  {
    reader->SetFileName(filename);
    reader->Update();
    //*************************************************************************
    // Part III: Put the data into the datastorage
    //*************************************************************************

    // Add the node to the DataStorage
    dataStorage->Add(reader->GetOutput());
  }
  catch(...)
  {
    fprintf( stderr, "Could not open file %s \n\n", filename );
    exit(2);
  }

  //*************************************************************************
  // Part IV: Create window and pass the datastorage to it
  //*************************************************************************

  // Create a RenderWindow
  QmitkRenderWindow renderWindow;

  // Tell the RenderWindow which (part of) the datastorage to render
  renderWindow.GetRenderer()->SetDataStorage(dataStorage);

  // Initialize the RenderWindow
  mitk::TimeGeometry::Pointer geo = dataStorage->ComputeBoundingGeometry(dataStorage->GetAll());
  mitk::RenderingManager::GetInstance()->InitializeViews( geo );
  //mitk::RenderingManager::GetInstance()->InitializeViews();

  // Select a slice
  mitk::SliceNavigationController::Pointer sliceNaviController = renderWindow.GetSliceNavigationController();
  if (sliceNaviController)
    sliceNaviController->GetSlice()->SetPos( 0 );

  //*************************************************************************
  // Part V: Qt-specific initialization
  //*************************************************************************

  //! [CreateOverlayManager]
  mitk::OverlayManager::Pointer OverlayManagerInstance = mitk::OverlayManager::New();
  mitk::BaseRenderer* renderer = mitk::BaseRenderer::GetInstance(renderWindow.GetVtkRenderWindow());
  renderer->SetOverlayManager(OverlayManagerInstance);
  //! [CreateOverlayManager]

  //! [GetOverlayManagerInstance]
  //The id that is passed identifies the correct mitk::OverlayManager and is '0' by default.
  mitk::BaseRenderer* renderer2D = mitk::BaseRenderer::GetInstance(renderWindow.GetVtkRenderWindow());
  mitk::OverlayManager::Pointer overlayManager = renderer2D->GetOverlayManager();
  //! [GetOverlayManagerInstance]

  //! [AddLayouter]
  //This creates a 2DLayouter that is only active for the recently fetched axialRenderer and positione
  mitk::Overlay2DLayouter::Pointer topleftLayouter = mitk::Overlay2DLayouter::CreateLayouter(mitk::Overlay2DLayouter::STANDARD_2D_TOPLEFT(), renderer2D);

  //Now, the created Layouter is added to the OverlayManager and can be referred to by its identification string.
  overlayManager->AddLayouter(topleftLayouter.GetPointer());

  //Several other Layouters can be added to the overlayManager
  mitk::Overlay2DLayouter::Pointer bottomLayouter = mitk::Overlay2DLayouter::CreateLayouter(mitk::Overlay2DLayouter::STANDARD_2D_BOTTOM(), renderer2D);
  overlayManager->AddLayouter(bottomLayouter.GetPointer());
  //! [AddLayouter]

  //! [TextOverlay2D]
  //Create a textOverlay2D
  mitk::TextOverlay2D::Pointer textOverlay = mitk::TextOverlay2D::New();

  textOverlay->SetText("Test!"); //set UTF-8 encoded text to render
  textOverlay->SetFontSize(40);
  textOverlay->SetColor(1,0,0); //Set text color to red
  textOverlay->SetOpacity(1);

  //The position of the Overlay can be set to a fixed coordinate on the display.
  mitk::Point2D pos;
  pos[0] = 10,pos[1] = 20;
  textOverlay->SetPosition2D(pos);

  //Add the overlay to the overlayManager. It is added to all registered renderers automaticly
  overlayManager->AddOverlay(textOverlay.GetPointer());

  //Alternatively, a layouter can be used to manage the position of the overlay. If a layouter is set, the absolute position of the overlay is not used anymore
  //The Standard TopLeft Layouter has to be registered to the OverlayManager first
  overlayManager->AddLayouter(mitk::Overlay2DLayouter::CreateLayouter(mitk::Overlay2DLayouter::STANDARD_2D_TOPLEFT(), renderer2D).GetPointer());
  //! [TextOverlay2D]

  //! [SetLayouterToOverlay]
  //Because a Layouter is specified by the identification string AND the Renderer, both have to be passed to the call.
  overlayManager->SetLayouter(textOverlay.GetPointer(),mitk::Overlay2DLayouter::STANDARD_2D_TOPLEFT(),renderer2D);
  //! [SetLayouterToOverlay]

  //! [TextOverlay3D]
  mitk::PointSet::Pointer pointset = mitk::PointSet::New();

  // This vector is used to define an offset for the annotations, in order to show them with a margin to the actual coordinate.
  mitk::Point3D offset;
  offset[0] = .5;
  offset[1] = .5;
  offset[2] = .5;

  //Just a loop to create some points
  for(int i=0 ; i < 10 ; i++){
    //To each point, a TextOverlay3D is created
    mitk::TextOverlay3D::Pointer textOverlay3D = mitk::TextOverlay3D::New();
    mitk::Point3D point;
    point[0] = i*20;
    point[1] = i*30;
    point[2] = -i*50;
    pointset->InsertPoint(i, point);
    textOverlay3D->SetText("A Point");

    // The Position is set to the point coordinate to create an annotation to the point in the PointSet.
    textOverlay3D->SetPosition3D(point);

    // move the annotation away from the actual point
    textOverlay3D->SetOffsetVector(offset);

    overlayManager->AddOverlay(textOverlay3D.GetPointer());
  }

  // also show the created pointset
  mitk::DataNode::Pointer datanode = mitk::DataNode::New();
  datanode->SetData(pointset);
  datanode->SetName("pointSet");
  dataStorage->Add(datanode);
  //! [TextOverlay3D]
  renderWindow.show();
  renderWindow.resize( 256, 256 );

  return qtapplication.exec();

  // cleanup: Remove References to DataStorage. This will delete the object
  dataStorage = NULL;
}
/**
\example Step1.cpp
*/
<commit_msg>COMP: Fixed wrong call in Examples<commit_after>/*===================================================================

The Medical Imaging Interaction Toolkit (MITK)

Copyright (c) German Cancer Research Center,
Division of Medical and Biological Informatics.
All rights reserved.

This software is distributed WITHOUT ANY WARRANTY; without
even the implied warranty of MERCHANTABILITY or FITNESS FOR
A PARTICULAR PURPOSE.

See LICENSE.txt or http://www.mitk.org for details.

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

//! [includes]
#include "QmitkRegisterClasses.h"
#include "QmitkRenderWindow.h"

#include <mitkDataNodeFactory.h>
#include <mitkPointSet.h>
#include <mitkStandaloneDataStorage.h>

#include <itksys/SystemTools.hxx>
#include <QApplication>
#include <mitkOverlay2DLayouter.h>
#include <mitkOverlayManager.h>
#include <mitkTextOverlay2D.h>
#include <mitkTextOverlay3D.h>
//! [includes]

//##Documentation
//## @brief Load image (nrrd format) and display it in a 2D view
int main(int argc, char* argv[])
{
  QApplication qtapplication( argc, argv );

  if (argc < 2)
  {
    fprintf( stderr, "Usage:   %s [filename] \n\n", itksys::SystemTools::GetFilenameName(argv[0]).c_str() );
    return 1;
  }

  // Register Qmitk-dependent global instances
  QmitkRegisterClasses();

  //*************************************************************************
  // Part I: Basic initialization
  //*************************************************************************

  // Create a DataStorage
  // The DataStorage manages all data objects. It is used by the
  // rendering mechanism to render all data objects
  // We use the standard implementation mitk::StandaloneDataStorage.
  mitk::StandaloneDataStorage::Pointer dataStorage = mitk::StandaloneDataStorage::New();

  //*************************************************************************
  // Part II: Create some data by reading a file
  //*************************************************************************

  // Create a DataNodeFactory to read a data format supported
  // by the DataNodeFactory (many image formats, surface formats, etc.)
  mitk::DataNodeFactory::Pointer reader=mitk::DataNodeFactory::New();
  const char * filename = argv[1];
  try
  {
    reader->SetFileName(filename);
    reader->Update();
    //*************************************************************************
    // Part III: Put the data into the datastorage
    //*************************************************************************

    // Add the node to the DataStorage
    dataStorage->Add(reader->GetOutput());
  }
  catch(...)
  {
    fprintf( stderr, "Could not open file %s \n\n", filename );
    exit(2);
  }

  //*************************************************************************
  // Part IV: Create window and pass the datastorage to it
  //*************************************************************************

  // Create a RenderWindow
  QmitkRenderWindow renderWindow;

  // Tell the RenderWindow which (part of) the datastorage to render
  renderWindow.GetRenderer()->SetDataStorage(dataStorage);

  // Initialize the RenderWindow
  mitk::TimeGeometry::Pointer geo = dataStorage->ComputeBoundingGeometry3D(dataStorage->GetAll());
  mitk::RenderingManager::GetInstance()->InitializeViews( geo );
  //mitk::RenderingManager::GetInstance()->InitializeViews();

  // Select a slice
  mitk::SliceNavigationController::Pointer sliceNaviController = renderWindow.GetSliceNavigationController();
  if (sliceNaviController)
    sliceNaviController->GetSlice()->SetPos( 0 );

  //*************************************************************************
  // Part V: Qt-specific initialization
  //*************************************************************************

  //! [CreateOverlayManager]
  mitk::OverlayManager::Pointer OverlayManagerInstance = mitk::OverlayManager::New();
  mitk::BaseRenderer* renderer = mitk::BaseRenderer::GetInstance(renderWindow.GetVtkRenderWindow());
  renderer->SetOverlayManager(OverlayManagerInstance);
  //! [CreateOverlayManager]

  //! [GetOverlayManagerInstance]
  //The id that is passed identifies the correct mitk::OverlayManager and is '0' by default.
  mitk::BaseRenderer* renderer2D = mitk::BaseRenderer::GetInstance(renderWindow.GetVtkRenderWindow());
  mitk::OverlayManager::Pointer overlayManager = renderer2D->GetOverlayManager();
  //! [GetOverlayManagerInstance]

  //! [AddLayouter]
  //This creates a 2DLayouter that is only active for the recently fetched axialRenderer and positione
  mitk::Overlay2DLayouter::Pointer topleftLayouter = mitk::Overlay2DLayouter::CreateLayouter(mitk::Overlay2DLayouter::STANDARD_2D_TOPLEFT(), renderer2D);

  //Now, the created Layouter is added to the OverlayManager and can be referred to by its identification string.
  overlayManager->AddLayouter(topleftLayouter.GetPointer());

  //Several other Layouters can be added to the overlayManager
  mitk::Overlay2DLayouter::Pointer bottomLayouter = mitk::Overlay2DLayouter::CreateLayouter(mitk::Overlay2DLayouter::STANDARD_2D_BOTTOM(), renderer2D);
  overlayManager->AddLayouter(bottomLayouter.GetPointer());
  //! [AddLayouter]

  //! [TextOverlay2D]
  //Create a textOverlay2D
  mitk::TextOverlay2D::Pointer textOverlay = mitk::TextOverlay2D::New();

  textOverlay->SetText("Test!"); //set UTF-8 encoded text to render
  textOverlay->SetFontSize(40);
  textOverlay->SetColor(1,0,0); //Set text color to red
  textOverlay->SetOpacity(1);

  //The position of the Overlay can be set to a fixed coordinate on the display.
  mitk::Point2D pos;
  pos[0] = 10,pos[1] = 20;
  textOverlay->SetPosition2D(pos);

  //Add the overlay to the overlayManager. It is added to all registered renderers automaticly
  overlayManager->AddOverlay(textOverlay.GetPointer());

  //Alternatively, a layouter can be used to manage the position of the overlay. If a layouter is set, the absolute position of the overlay is not used anymore
  //The Standard TopLeft Layouter has to be registered to the OverlayManager first
  overlayManager->AddLayouter(mitk::Overlay2DLayouter::CreateLayouter(mitk::Overlay2DLayouter::STANDARD_2D_TOPLEFT(), renderer2D).GetPointer());
  //! [TextOverlay2D]

  //! [SetLayouterToOverlay]
  //Because a Layouter is specified by the identification string AND the Renderer, both have to be passed to the call.
  overlayManager->SetLayouter(textOverlay.GetPointer(),mitk::Overlay2DLayouter::STANDARD_2D_TOPLEFT(),renderer2D);
  //! [SetLayouterToOverlay]

  //! [TextOverlay3D]
  mitk::PointSet::Pointer pointset = mitk::PointSet::New();

  // This vector is used to define an offset for the annotations, in order to show them with a margin to the actual coordinate.
  mitk::Point3D offset;
  offset[0] = .5;
  offset[1] = .5;
  offset[2] = .5;

  //Just a loop to create some points
  for(int i=0 ; i < 10 ; i++){
    //To each point, a TextOverlay3D is created
    mitk::TextOverlay3D::Pointer textOverlay3D = mitk::TextOverlay3D::New();
    mitk::Point3D point;
    point[0] = i*20;
    point[1] = i*30;
    point[2] = -i*50;
    pointset->InsertPoint(i, point);
    textOverlay3D->SetText("A Point");

    // The Position is set to the point coordinate to create an annotation to the point in the PointSet.
    textOverlay3D->SetPosition3D(point);

    // move the annotation away from the actual point
    textOverlay3D->SetOffsetVector(offset);

    overlayManager->AddOverlay(textOverlay3D.GetPointer());
  }

  // also show the created pointset
  mitk::DataNode::Pointer datanode = mitk::DataNode::New();
  datanode->SetData(pointset);
  datanode->SetName("pointSet");
  dataStorage->Add(datanode);
  //! [TextOverlay3D]
  renderWindow.show();
  renderWindow.resize( 256, 256 );

  return qtapplication.exec();

  // cleanup: Remove References to DataStorage. This will delete the object
  dataStorage = NULL;
}
/**
\example Step1.cpp
*/<|endoftext|>


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

#include "brw_fs.h"
#include "brw_fs_live_variables.h"
#include "brw_cfg.h"

/** @file brw_fs_saturate_propagation.cpp
 */

static bool
opt_saturate_propagation_local(fs_visitor *v, bblock_t *block)
{
   bool progress = false;
   int ip = block->start_ip - 1;

   for (fs_inst *inst = (fs_inst *)block->start;
        inst != block->end->next;
        inst = (fs_inst *) inst->next) {
      ip++;

      if (inst->opcode != BRW_OPCODE_MOV ||
          inst->dst.file != GRF ||
          inst->src[0].file != GRF ||
          !inst->saturate)
         continue;

      int src_var = v->live_intervals->var_from_reg(&inst->src[0]);
      int src_end_ip = v->live_intervals->end[src_var];
      if (src_end_ip > ip && !inst->dst.equals(inst->src[0]))
         continue;

      int scan_ip = ip;
      bool interfered = false;
      for (fs_inst *scan_inst = (fs_inst *) inst->prev;
           scan_inst != block->start->prev;
           scan_inst = (fs_inst *) scan_inst->prev) {
         scan_ip--;

         if (scan_inst->dst.file == GRF &&
             scan_inst->dst.reg == inst->src[0].reg &&
             scan_inst->dst.reg_offset == inst->src[0].reg_offset &&
             !scan_inst->is_partial_write()) {
            if (scan_inst->can_do_saturate()) {
               scan_inst->saturate = true;
               inst->saturate = false;
               progress = true;
            }
            break;
         }
         for (int i = 0; i < 3; i++) {
            if (scan_inst->src[i].file == GRF &&
                scan_inst->src[i].reg == inst->src[0].reg &&
                scan_inst->src[i].reg_offset == inst->src[0].reg_offset) {
               interfered = true;
               break;
            }
         }

         if (interfered)
            break;
      }
   }

   return progress;
}

bool
fs_visitor::opt_saturate_propagation()
{
   bool progress = false;

   calculate_live_intervals();

   cfg_t cfg(&instructions);

   for (int b = 0; b < cfg.num_blocks; b++) {
      progress = opt_saturate_propagation_local(this, cfg.blocks[b])
                 || progress;
   }

   if (progress)
      invalidate_live_intervals();

   return progress;
}
<commit_msg>i965/fs: Don't propagate saturation modifiers if there are source modifiers.<commit_after>/*
 * Copyright © 2013 Intel Corporation
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

#include "brw_fs.h"
#include "brw_fs_live_variables.h"
#include "brw_cfg.h"

/** @file brw_fs_saturate_propagation.cpp
 */

static bool
opt_saturate_propagation_local(fs_visitor *v, bblock_t *block)
{
   bool progress = false;
   int ip = block->start_ip - 1;

   for (fs_inst *inst = (fs_inst *)block->start;
        inst != block->end->next;
        inst = (fs_inst *) inst->next) {
      ip++;

      if (inst->opcode != BRW_OPCODE_MOV ||
          inst->dst.file != GRF ||
          inst->src[0].file != GRF ||
          inst->src[0].abs ||
          inst->src[0].negate ||
          !inst->saturate)
         continue;

      int src_var = v->live_intervals->var_from_reg(&inst->src[0]);
      int src_end_ip = v->live_intervals->end[src_var];
      if (src_end_ip > ip && !inst->dst.equals(inst->src[0]))
         continue;

      int scan_ip = ip;
      bool interfered = false;
      for (fs_inst *scan_inst = (fs_inst *) inst->prev;
           scan_inst != block->start->prev;
           scan_inst = (fs_inst *) scan_inst->prev) {
         scan_ip--;

         if (scan_inst->dst.file == GRF &&
             scan_inst->dst.reg == inst->src[0].reg &&
             scan_inst->dst.reg_offset == inst->src[0].reg_offset &&
             !scan_inst->is_partial_write()) {
            if (scan_inst->can_do_saturate()) {
               scan_inst->saturate = true;
               inst->saturate = false;
               progress = true;
            }
            break;
         }
         for (int i = 0; i < 3; i++) {
            if (scan_inst->src[i].file == GRF &&
                scan_inst->src[i].reg == inst->src[0].reg &&
                scan_inst->src[i].reg_offset == inst->src[0].reg_offset) {
               interfered = true;
               break;
            }
         }

         if (interfered)
            break;
      }
   }

   return progress;
}

bool
fs_visitor::opt_saturate_propagation()
{
   bool progress = false;

   calculate_live_intervals();

   cfg_t cfg(&instructions);

   for (int b = 0; b < cfg.num_blocks; b++) {
      progress = opt_saturate_propagation_local(this, cfg.blocks[b])
                 || progress;
   }

   if (progress)
      invalidate_live_intervals();

   return progress;
}
<|endoftext|>


<commit_before>#include<chrono>
#include<iostream>
#include<random>
#include"func.cpp"
int main()
{
        str s("RAMAN"),s1;
        str q(s1);
        str r,a;
        r=q+s1;
        r.countocc();
        r.disp();
	a.randomizer();
	a.countocc();
	a.disp();
        return 0;

}

<commit_msg>updated<commit_after>#include<chrono>
#include<iostream>
#include<random>
#include"functions.cpp"
int main()
{
        str a("RAMAN"); // Invokes the constructor
	str b;
        a.countocc(); //Counts the occurunces
        a.disp(); // To display the data
	a.randomizer(); // Generates new random string
	a.countocc(); // Counts the occurunces
	a.disp(); // To display
	b.getdata(); // Get new data
	b.cal(); //Calculates the strlen
	b.anagram(); // To generate anagrams
        return 0;

}

<|endoftext|>


<commit_before>#include <hop_bits/optimisationAlgorithm/roleBasedImitationAlgorithm.hpp>

// HOP
#include <hop_bits/helper/random.hpp>

namespace hop {
  RoleBasedImitationAlgorithm::RoleBasedImitationAlgorithm(const std::shared_ptr<OptimisationProblem> optimisationProblem, const unsigned int& populationSize)
    : OptimisationAlgorithm(optimisationProblem),
      populationSize_(populationSize),
      objectiveValues_(populationSize_) {
    neighbourhoodSize_ = 0;
    maximalNeighourhoodConvergence_ = 0;

  }

  void RoleBasedImitationAlgorithm::optimiseImplementation() {
    arma::Mat<double> agents = arma::randu<arma::Mat<double>>(optimisationProblem_->getNumberOfDimensions(), populationSize_);
    agents.each_col() %= optimisationProblem_->getUpperBounds() - optimisationProblem_->getLowerBounds();
    agents.each_col() += optimisationProblem_->getLowerBounds();

    for(std::size_t n = 0; n < populationSize_; ++n) {
      ++numberOfIterations_;

      arma::Col<double> solution = agents.col(n);
      double objectiveValue = optimisationProblem_->getObjectiveValue(solution) + optimisationProblem_->getSoftConstraintsValue(solution);
      objectiveValues_.at(n) = objectiveValue;

      if(objectiveValue < bestObjectiveValue_) {
        bestSolution_ = solution;
        bestObjectiveValue_ = objectiveValue;
      }

      if(isFinished() || isTerminated()) {
        break;
      }
    }

    while(!isFinished() && !isTerminated()) {
      arma::Col<arma::uword> permutation = Random::getRandomPermutation(populationSize_);
      for(std::size_t n = 0; n < populationSize_; ++n) {
        ++numberOfIterations_;

        std::size_t nn = permutation.at(n);
        arma::Col<double> currentSolution = agents.col(nn);
        double currentObjectiveValue = objectiveValues_.at(nn);

        arma::Col<arma::uword> neighbours = Random::getRandomPermutation(populationSize_ - 1, neighbourhoodSize_);
        neighbours.elem(arma::find(neighbours >= nn)) += 1;

        arma::Col<arma::uword> parametersToMutate = Random::getRandomPermutation(optimisationProblem_->getNumberOfDimensions(), std::uniform_int_distribution<unsigned int>(0, optimisationProblem_->getNumberOfDimensions())(Random::Rng));

        arma::Col<double> neighourhoodMeanObjectiveValues = arma::mean(static_cast<arma::Mat<double>>(agents.cols(neighbours)).rows(parametersToMutate));

        arma::Col<arma::uword> betterNeighbours = arma::find(objectiveValues_.elem(neighbours) < currentObjectiveValue);

        if(betterNeighbours.n_elem > 0) {
          arma::Col<double> neighbourhoodStddevObjectiveValues = arma::stddev(static_cast<arma::Mat<double>>(agents.cols(neighbours)).rows(parametersToMutate));
          arma::Col<arma::uword> convergedNeighbours = arma::find(neighbourhoodStddevObjectiveValues < maximalNeighourhoodConvergence_.elem(parametersToMutate));

          if(convergedNeighbours.n_elem > 0) {

          }
        } else {

        }
        //                if convergedSize > 0

        //                    convergedParameter = parametersToMutate(converged);

        //                    % notNeighbours = setdiff(agents, [neighbours(:); agent]);
        //                    notNeighbours = agents(~ismembc(agents, sort([neighbours(:); agent])));

        //                    factor = ones(1, convergedSize);
        //                    factor(randperm(convergedSize, randi(convergedSize))) = -1;

        //                    p = rand(1, convergedSize);

        //                    other_k = parameters(sub2ind(size(parameters), notNeighbours(randi(size(notNeighbours, 2), 1, convergedSize)), convergedParameter));
        //                    other_j = parameters(sub2ind(size(parameters), notNeighbours(randi(size(notNeighbours, 2), 1, convergedSize)), convergedParameter));
        //                    x = other_k .* (1 - p) + other_j .* p;

        //                    parametersCandidate = x + factor .* abs(x - factor .* max(factor .* other_k, factor .* other_j)) .* rand(1, convergedSize) * 2;
        //                    withinBoundary = parametersCandidate >= lowerBounds(convergedParameter) & parametersCandidate <= upperBounds(convergedParameter);
        //                    parameters(agent, convergedParameter(withinBoundary)) = parametersCandidate(withinBoundary);
        //                else
        //                    static = true;
        //                end
      }
    }
  }

  void RoleBasedImitationAlgorithm::setNeighbourhoodSize(const unsigned int& neighbourhoodSize) {
    neighbourhoodSize_ = neighbourhoodSize;
  }

  void RoleBasedImitationAlgorithm::setMaximalNeighourhoodConvergence(const arma::Col<double>& maximalNeighourhoodConvergence) {
    maximalNeighourhoodConvergence_ = maximalNeighourhoodConvergence;
  }

  std::string RoleBasedImitationAlgorithm::to_string() const {
    return "RoleBasedImitationAlgorithm";
  }
}
<commit_msg>fix: Type error<commit_after>#include <hop_bits/optimisationAlgorithm/roleBasedImitationAlgorithm.hpp>

// HOP
#include <hop_bits/helper/random.hpp>

namespace hop {
  RoleBasedImitationAlgorithm::RoleBasedImitationAlgorithm(const std::shared_ptr<OptimisationProblem> optimisationProblem, const unsigned int& populationSize)
    : OptimisationAlgorithm(optimisationProblem),
      populationSize_(populationSize),
      objectiveValues_(populationSize_),
      maximalNeighourhoodConvergence_(populationSize_) {
    neighbourhoodSize_ = 0;

  }

  void RoleBasedImitationAlgorithm::optimiseImplementation() {
    arma::Mat<double> agents = arma::randu<arma::Mat<double>>(optimisationProblem_->getNumberOfDimensions(), populationSize_);
    agents.each_col() %= optimisationProblem_->getUpperBounds() - optimisationProblem_->getLowerBounds();
    agents.each_col() += optimisationProblem_->getLowerBounds();

    for(std::size_t n = 0; n < populationSize_; ++n) {
      ++numberOfIterations_;

      arma::Col<double> solution = agents.col(n);
      double objectiveValue = optimisationProblem_->getObjectiveValue(solution) + optimisationProblem_->getSoftConstraintsValue(solution);
      objectiveValues_.at(n) = objectiveValue;

      if(objectiveValue < bestObjectiveValue_) {
        bestSolution_ = solution;
        bestObjectiveValue_ = objectiveValue;
      }

      if(isFinished() || isTerminated()) {
        break;
      }
    }

    while(!isFinished() && !isTerminated()) {
      arma::Col<arma::uword> permutation = Random::getRandomPermutation(populationSize_);
      for(std::size_t n = 0; n < populationSize_; ++n) {
        ++numberOfIterations_;

        std::size_t nn = permutation.at(n);
        arma::Col<double> currentSolution = agents.col(nn);
        double currentObjectiveValue = objectiveValues_.at(nn);

        arma::Col<arma::uword> neighbours = Random::getRandomPermutation(populationSize_ - 1, neighbourhoodSize_);
        neighbours.elem(arma::find(neighbours >= nn)) += 1;

        arma::Col<arma::uword> parametersToMutate = Random::getRandomPermutation(optimisationProblem_->getNumberOfDimensions(), std::uniform_int_distribution<unsigned int>(0, optimisationProblem_->getNumberOfDimensions())(Random::Rng));

        arma::Col<double> neighourhoodMeanObjectiveValues = arma::mean(static_cast<arma::Mat<double>>(agents.cols(neighbours)).rows(parametersToMutate));

        arma::Col<arma::uword> betterNeighbours = arma::find(objectiveValues_.elem(neighbours) < currentObjectiveValue);

        if(betterNeighbours.n_elem > 0) {
          arma::Col<double> neighbourhoodStddevObjectiveValues = arma::stddev(static_cast<arma::Mat<double>>(agents.cols(neighbours)).rows(parametersToMutate));
          arma::Col<arma::uword> convergedNeighbours = arma::find(neighbourhoodStddevObjectiveValues < maximalNeighourhoodConvergence_.elem(parametersToMutate));

          if(convergedNeighbours.n_elem > 0) {

          }
        } else {

        }
        //                if convergedSize > 0

        //                    convergedParameter = parametersToMutate(converged);

        //                    % notNeighbours = setdiff(agents, [neighbours(:); agent]);
        //                    notNeighbours = agents(~ismembc(agents, sort([neighbours(:); agent])));

        //                    factor = ones(1, convergedSize);
        //                    factor(randperm(convergedSize, randi(convergedSize))) = -1;

        //                    p = rand(1, convergedSize);

        //                    other_k = parameters(sub2ind(size(parameters), notNeighbours(randi(size(notNeighbours, 2), 1, convergedSize)), convergedParameter));
        //                    other_j = parameters(sub2ind(size(parameters), notNeighbours(randi(size(notNeighbours, 2), 1, convergedSize)), convergedParameter));
        //                    x = other_k .* (1 - p) + other_j .* p;

        //                    parametersCandidate = x + factor .* abs(x - factor .* max(factor .* other_k, factor .* other_j)) .* rand(1, convergedSize) * 2;
        //                    withinBoundary = parametersCandidate >= lowerBounds(convergedParameter) & parametersCandidate <= upperBounds(convergedParameter);
        //                    parameters(agent, convergedParameter(withinBoundary)) = parametersCandidate(withinBoundary);
        //                else
        //                    static = true;
        //                end
      }
    }
  }

  void RoleBasedImitationAlgorithm::setNeighbourhoodSize(const unsigned int& neighbourhoodSize) {
    neighbourhoodSize_ = neighbourhoodSize;
  }

  void RoleBasedImitationAlgorithm::setMaximalNeighourhoodConvergence(const arma::Col<double>& maximalNeighourhoodConvergence) {
    maximalNeighourhoodConvergence_ = maximalNeighourhoodConvergence;
  }

  std::string RoleBasedImitationAlgorithm::to_string() const {
    return "RoleBasedImitationAlgorithm";
  }
}
<|endoftext|>