<commit_before>#ifndef DISSENT_CRYPTO_INTEGER_H_GUARD
#define DISSENT_CRYPTO_INTEGER_H_GUARD

#include <QByteArray>
#include <QString>

#include "CryptoFactory.hpp"
#include "IntegerData.hpp"

namespace Dissent {
namespace Crypto {
  /**
   * "Big" Integer wrapper
   */
  class Integer {
    public:
      /**
       * Construct from IntegerData
       */
      explicit Integer(IntegerData *data) : _data(data)
      {
        if(data == 0) {
          _data = CryptoFactory::GetInstance().GetLibrary()->GetIntegerData(0);
        }
      }

      Integer(int value = 0) :
        _data(CryptoFactory::GetInstance().GetLibrary()->GetIntegerData(value))
      {
      }

      explicit Integer(const QByteArray &value) :
        _data(CryptoFactory::GetInstance().GetLibrary()->GetIntegerData(
              value.isEmpty() ? QByteArray(1, 0) : value))
      {
      }

      explicit Integer(const QString &value) :
        _data(CryptoFactory::GetInstance().GetLibrary()->GetIntegerData(value))
      {
      }

      Integer(const Integer &other) :
        _data(CryptoFactory::GetInstance().GetLibrary()->GetIntegerData(0))
      {
        _data->Set(other._data.constData());
      }

      /**
       * returns a random integer data
       * @param bit_count the amount of bits in the integer
       * @param mod the modulus of the integer
       * @param prime if the integer should be prime
       */
      static Integer GetRandomInteger(int bit_count,
          const Integer &mod = Integer(), bool prime = false)
      {
        IntegerData *data = CryptoFactory::GetInstance().
          GetLibrary()->GetRandomInteger(bit_count, mod.GetData(), prime);
        return Integer(data);
      }

      /**
       * Returns the byte array representation of the number
       */
      inline const QByteArray &GetByteArray() const
      {
        return _data->GetByteArray();
      }

      /**
       * Returns the string representation
       */
      inline const QString &ToString() const
      {
        return _data->ToString();
      }

      /**
       * Add operator, produces a new Integer
       * @param other the Integer to add
       */
      inline Integer Add(const Integer &term) const
      {
        return Integer(_data->Add(term._data.constData()));
      }

      /**
       * Subtraction operator, produces a new Integer
       * @param other the Integer to subtract (subtrahend)
       */
      inline Integer Subtract(const Integer &subtrahend) const
      {
        return Integer(_data->Subtract(subtrahend._data.constData()));
      }

      /**
       * Subtraction operator, produces a new Integer
       * @param multiplicand the Integer to multiply this
       */
      inline Integer Multiply(const Integer &multiplicand) const
      {
        return Integer(_data->Multiply(multiplicand._data.constData()));
      }

      /**
       * Division operator, produces a new Integer
       * @param divisor the Integer to divide into this
       */
      inline Integer Divide(const Integer &divisor) const
      {
        return Integer(_data->Divide(divisor._data.constData()));
      }

      /**
       * Exponentiating operator
       * @param pow raise this to other
       * @param mod modulus for the exponentiation
       */
      Integer Pow(const Integer &pow, const Integer &mod) const
      {
        return Integer(_data->Pow(pow._data.constData(), mod._data.constData()));
      }

      /**
       * Assignment operator
       * @param other the other Integer
       */
      inline Integer &operator=(const Integer &other)
      {
        _data->Set(other._data.constData());
        return *this;
      }

      /**
       * Add operator, adds to current
       * @param other the Integer to add
       */
      inline Integer &operator+=(const Integer &other)
      {
        _data->operator+=(other._data.constData());
        return *this;
      }

      /**
       * Subtraction operator, subtracts from current
       * @param other the Integer to subtract
       */
      Integer &operator-=(const Integer &other)
      {
        _data->operator-=(other._data.constData());
        return *this;
      }

      /**
       * Equality operator
       * @param other the Integer to compare
       */
      bool operator==(const Integer &other) const
      {
        return _data->operator==(other._data.constData());
      }

      /**
       * Not qquality operator
       * @param other the Integer to compare
       */
      bool operator!=(const Integer &other) const
      {
        return _data->operator!=(other._data.constData());
      }

      /**
       * Greater than
       * @param other the Integer to compare
       */
      bool operator>(const Integer &other) const
      {
        return _data->operator>(other._data.constData());
      }

      /**
       * Greater than or equal
       * @param other the Integer to compare
       */
      bool operator>=(const Integer &other) const
      {
        return _data->operator>=(other._data.constData());
      }

      /**
       * Less than
       * @param other the Integer to compare
       */
      bool operator<(const Integer &other) const
      {
        return _data->operator<(other._data.constData());
      }

      /**
       * Less than or equal
       * @param other the Integer to compare
       */
      bool operator<=(const Integer &other) const
      {
        return _data->operator<=(other._data.constData());
      }

      /**
       * Returns the integer's count in bits
       */
      inline int GetBitCount() const
      {
        return _data->GetBitCount();
      }

      /**
       * Returns the integer's count in bytes
       */
      inline int GetByteCount() const
      {
        return _data->GetByteCount();
      }

      /**
       * returns the internal integer data, not particularly safe
       */
      const IntegerData *GetData() const { return _data.constData(); }

    private:
      QExplicitlySharedDataPointer<IntegerData> _data;
  };

  /**
   * Add operator, produces a new Integer
   * @param lhs first term
   * @param rhs second term
   */
  inline Integer operator+(const Integer &lhs, const Integer &rhs)
  {
    return Integer(lhs.Add(rhs));
  }

  /**
   * Subtraction operator, produces a new Integer
   * @param lhs minuend
   * @param rhs subtrahend
   */
  inline Integer operator-(const Integer &lhs, const Integer &rhs)
  {
    return Integer(lhs.Subtract(rhs));
  }

  /**
   * Multiplication operator, produces a new Integer
   * @param lhs left multiplicand
   * @param rhs right multiplicand
   */
  inline Integer operator*(const Integer &lhs, const Integer &rhs)
  {
    return Integer(lhs.Multiply(rhs));
  }

  /**
   * Division operator, produces a new Integer (quotient)
   * @param lhs dividend
   * @param rhs divisor
   */
  inline Integer operator/(const Integer &lhs, const Integer &rhs)
  {
    return Integer(lhs.Divide(rhs));
  }
}
}

#endif
<commit_msg>[Crypto] Added support for serializing / deserializing Integer<commit_after>#ifndef DISSENT_CRYPTO_INTEGER_H_GUARD
#define DISSENT_CRYPTO_INTEGER_H_GUARD

#include <QByteArray>
#include <QString>

#include "CryptoFactory.hpp"
#include "IntegerData.hpp"

namespace Dissent {
namespace Crypto {
  /**
   * "Big" Integer wrapper
   */
  class Integer {
    public:
      /**
       * Construct from IntegerData
       */
      explicit Integer(IntegerData *data) : _data(data)
      {
        if(data == 0) {
          _data = CryptoFactory::GetInstance().GetLibrary()->GetIntegerData(0);
        }
      }

      Integer(int value = 0) :
        _data(CryptoFactory::GetInstance().GetLibrary()->GetIntegerData(value))
      {
      }

      explicit Integer(const QByteArray &value) :
        _data(CryptoFactory::GetInstance().GetLibrary()->GetIntegerData(
              value.isEmpty() ? QByteArray(1, 0) : value))
      {
      }

      explicit Integer(const QString &value) :
        _data(CryptoFactory::GetInstance().GetLibrary()->GetIntegerData(value))
      {
      }

      Integer(const Integer &other) :
        _data(CryptoFactory::GetInstance().GetLibrary()->GetIntegerData(0))
      {
        _data->Set(other._data.constData());
      }

      /**
       * returns a random integer data
       * @param bit_count the amount of bits in the integer
       * @param mod the modulus of the integer
       * @param prime if the integer should be prime
       */
      static Integer GetRandomInteger(int bit_count,
          const Integer &mod = Integer(), bool prime = false)
      {
        IntegerData *data = CryptoFactory::GetInstance().
          GetLibrary()->GetRandomInteger(bit_count, mod.GetData(), prime);
        return Integer(data);
      }

      /**
       * Returns the byte array representation of the number
       */
      inline const QByteArray &GetByteArray() const
      {
        return _data->GetByteArray();
      }

      /**
       * Returns the string representation
       */
      inline const QString &ToString() const
      {
        return _data->ToString();
      }

      /**
       * Add operator, produces a new Integer
       * @param other the Integer to add
       */
      inline Integer Add(const Integer &term) const
      {
        return Integer(_data->Add(term._data.constData()));
      }

      /**
       * Subtraction operator, produces a new Integer
       * @param other the Integer to subtract (subtrahend)
       */
      inline Integer Subtract(const Integer &subtrahend) const
      {
        return Integer(_data->Subtract(subtrahend._data.constData()));
      }

      /**
       * Subtraction operator, produces a new Integer
       * @param multiplicand the Integer to multiply this
       */
      inline Integer Multiply(const Integer &multiplicand) const
      {
        return Integer(_data->Multiply(multiplicand._data.constData()));
      }

      /**
       * Division operator, produces a new Integer
       * @param divisor the Integer to divide into this
       */
      inline Integer Divide(const Integer &divisor) const
      {
        return Integer(_data->Divide(divisor._data.constData()));
      }

      /**
       * Exponentiating operator
       * @param pow raise this to other
       * @param mod modulus for the exponentiation
       */
      Integer Pow(const Integer &pow, const Integer &mod) const
      {
        return Integer(_data->Pow(pow._data.constData(), mod._data.constData()));
      }

      /**
       * Assignment operator
       * @param other the other Integer
       */
      inline Integer &operator=(const Integer &other)
      {
        _data->Set(other._data.constData());
        return *this;
      }

      /**
       * Add operator, adds to current
       * @param other the Integer to add
       */
      inline Integer &operator+=(const Integer &other)
      {
        _data->operator+=(other._data.constData());
        return *this;
      }

      /**
       * Subtraction operator, subtracts from current
       * @param other the Integer to subtract
       */
      Integer &operator-=(const Integer &other)
      {
        _data->operator-=(other._data.constData());
        return *this;
      }

      /**
       * Equality operator
       * @param other the Integer to compare
       */
      bool operator==(const Integer &other) const
      {
        return _data->operator==(other._data.constData());
      }

      /**
       * Not qquality operator
       * @param other the Integer to compare
       */
      bool operator!=(const Integer &other) const
      {
        return _data->operator!=(other._data.constData());
      }

      /**
       * Greater than
       * @param other the Integer to compare
       */
      bool operator>(const Integer &other) const
      {
        return _data->operator>(other._data.constData());
      }

      /**
       * Greater than or equal
       * @param other the Integer to compare
       */
      bool operator>=(const Integer &other) const
      {
        return _data->operator>=(other._data.constData());
      }

      /**
       * Less than
       * @param other the Integer to compare
       */
      bool operator<(const Integer &other) const
      {
        return _data->operator<(other._data.constData());
      }

      /**
       * Less than or equal
       * @param other the Integer to compare
       */
      bool operator<=(const Integer &other) const
      {
        return _data->operator<=(other._data.constData());
      }

      /**
       * Returns the integer's count in bits
       */
      inline int GetBitCount() const
      {
        return _data->GetBitCount();
      }

      /**
       * Returns the integer's count in bytes
       */
      inline int GetByteCount() const
      {
        return _data->GetByteCount();
      }

      /**
       * returns the internal integer data, not particularly safe
       */
      const IntegerData *GetData() const { return _data.constData(); }

    private:
      QExplicitlySharedDataPointer<IntegerData> _data;
  };

  /**
   * Add operator, produces a new Integer
   * @param lhs first term
   * @param rhs second term
   */
  inline Integer operator+(const Integer &lhs, const Integer &rhs)
  {
    return Integer(lhs.Add(rhs));
  }

  /**
   * Subtraction operator, produces a new Integer
   * @param lhs minuend
   * @param rhs subtrahend
   */
  inline Integer operator-(const Integer &lhs, const Integer &rhs)
  {
    return Integer(lhs.Subtract(rhs));
  }

  /**
   * Multiplication operator, produces a new Integer
   * @param lhs left multiplicand
   * @param rhs right multiplicand
   */
  inline Integer operator*(const Integer &lhs, const Integer &rhs)
  {
    return Integer(lhs.Multiply(rhs));
  }

  /**
   * Division operator, produces a new Integer (quotient)
   * @param lhs dividend
   * @param rhs divisor
   */
  inline Integer operator/(const Integer &lhs, const Integer &rhs)
  {
    return Integer(lhs.Divide(rhs));
  }

  /**
   * Serialize an Integer
   * @param stream where to store the serialized integer
   * @param value the integer to serialize
   */
  inline QDataStream &operator<<(QDataStream &stream, const Integer &value)
  {
    return stream << value.GetByteArray();
  }

  /**
   * Deserialize an integer
   * @param stream where to read data from
   * @param value where to store the deserialized integer
   */
  inline QDataStream &operator>>(QDataStream &stream, Integer &value)
  {
    QByteArray tvalue;
    stream >> tvalue;
    value = Integer(tvalue);
    return stream;
  }
}
}

#endif
<|endoftext|>


<commit_before>#include "TestIODevice.hpp"

#include <iostream>

void TestIODevice::fakeWrite(const QByteArray& data)
{
    readStore.append(data);
    emit readyRead();
}

qint64 TestIODevice::readData(char* data, qint64 maxSize)
{
    auto readData = readStore.left(maxSize);
    //std::cerr << "Read " << readData.size() << " byte(s) from mock IO device, requested " << maxSize << std::endl;
    qstrcpy(data, readData.constData());
    if (readStore.size() == readData.size()) {
        readStore.clear();
    } else {
        readStore = readStore.right(readStore.size() - readData.size());
    }
    return readData.size();
}

qint64 TestIODevice::writeData(const char* data, qint64 maxSize)
{
    writeStore.append(data, maxSize);
    return maxSize;
}
<commit_msg>Use memcpy, not qstrcpy, when copying data in the test device<commit_after>#include "TestIODevice.hpp"

#include <iostream>
#include <cstring>

void TestIODevice::fakeWrite(const QByteArray& data)
{
    readStore.append(data);
    emit readyRead();
}

qint64 TestIODevice::readData(char* data, qint64 maxSize)
{
    auto readData = readStore.left(maxSize);
    //std::cerr << "Read " << readData.size() << " byte(s) from mock IO device, requested " << maxSize << std::endl;
    memcpy(data, readData.constData(), readData.size());
    if (readStore.size() == readData.size()) {
        readStore.clear();
    } else {
        readStore = readStore.right(readStore.size() - readData.size());
    }
    return readData.size();
}

qint64 TestIODevice::writeData(const char* data, qint64 maxSize)
{
    writeStore.append(data, maxSize);
    return maxSize;
}
<|endoftext|>


<commit_before>/**
 * Copyright (C) 2012 by INdT
 *
 * 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
 * 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 Lesser 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.
 *
 * @author Rodrigo Goncalves de Oliveira <rodrigo.goncalves@openbossa.org>
 * @author Roger Felipe Zanoni da Silva <roger.zanoni@openbossa.org>
 */

#include "game.h"
#include "scene.h"
#include "viewport.h"

#include <QtQuick/QQuickWindow>
#include <QtGui/QCursor>

/*!
  \qmltype Game
  \inqmlmodule Bacon2D
  \inherits Item
  \brief The root element containing one or more Scene.

  The Game component is the root game component which
  contains one or more Scene components.  Only one
  Scene will be set as currentScene.

  Example usage:
  \qml
   import QtQuick 2.0
   import Bacon2D 1.0

   Game {
       id: game
       width: 800
       height: 600

       Scene {
           id: scene
           width: 300
           height: 300
       }
   }
   \endqml
*/
Game::Game(QQuickItem *parent)
    : QQuickItem(parent)
    , m_currentScene(0)
    , m_ups(30)
    , m_timerId(0)
{
    m_gameTime.start();
    m_timerId = startTimer(1000 / m_ups);
}

/*!
  \qmlproperty string Game::gameName
  \brief Name of the game, required if using Settings
*/
QString Game::gameName()
{
    return QCoreApplication::applicationName();
}

void Game::setGameName(const QString& gameName)
{
    // applicationName is needed for QSettings to create path to file
    QCoreApplication::setApplicationName(gameName);
    // Set the organizationName to match the applicationName, it's redundant
    // but creates path that plays well accross platforms
    QCoreApplication::setOrganizationName(gameName);
    Q_EMIT gameNameChanged();
}

/*!
  \qmlproperty Scene Game::currentScene
  \brief The current Scene
*/
Scene *Game::currentScene() const
{
    return m_currentScene;
}

void Game::setCurrentScene(Scene *currentScene)
{
    if (m_currentScene == currentScene)
        return;

    if (m_currentScene) {
        if (m_viewport) {
            m_viewport->setVisible(false);
            m_viewport = 0;
        }

        m_currentScene->setRunning(false);
        m_currentScene->setVisible(false);
    }

    m_currentScene = currentScene;

    if (m_currentScene) {
        m_currentScene->setGame(this);

        if ((m_viewport = m_currentScene->viewport())) {
            m_viewport->setParent(this);
            m_viewport->setParentItem(this);
            m_viewport->setScene(m_currentScene);
            m_viewport->setWidth(width());
            m_viewport->setHeight(height());
            m_viewport->setContentWidth(m_currentScene->width());
            m_viewport->setContentHeight(m_currentScene->height());
            m_viewport->updateMaxOffsets();
            m_viewport->setVisible(true);

            m_currentScene->setParentItem(m_viewport);
        } else {
            m_currentScene->setParent(this);
            m_currentScene->setParentItem(this);
        }

        m_currentScene->setRunning(true);
        m_currentScene->setVisible(true);
    }

    emit currentSceneChanged();
}

/*!
  \qmlproperty int Game::ups
  \brief This property holds the number of times update is called per second.

    Updates per second can be used to control the speed of the game
    loop.  The default is 30.
 */
int Game::ups() const
{
    return m_ups;
}

void Game::setUps(const int &ups)
{
    if (m_ups == ups)
        return;

    m_ups = ups;

    killTimer(m_timerId);
    m_gameTime.restart();
    m_timerId = startTimer(1000 / m_ups);

    emit upsChanged();
}

void Game::timerEvent(QTimerEvent *event)
{
    Q_UNUSED(event)

    update();
}

void Game::update()
{
    long elapsedTime = m_gameTime.restart();
    if (m_currentScene)
        m_currentScene->update(elapsedTime);
    if (m_viewport)
        m_viewport->update(elapsedTime);
}

/*!
  \qmlproperty QPointF Game::mouse
  \brief The point in the plane of the mouse pointer
*/
QPointF Game::mouse()
{
    return window()->mapFromGlobal(QCursor::pos());
}

void Game::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
    if (newGeometry.isEmpty() || !isComponentComplete() || (newGeometry == oldGeometry))
        return;

    if (m_viewport && m_currentScene) {
        m_viewport->setWidth(width());
        m_viewport->setHeight(height());
        m_viewport->setContentWidth(m_currentScene->width());
        m_viewport->setContentHeight(m_currentScene->height());
        m_viewport->updateMaxOffsets();
    }

    QQuickItem::geometryChanged(newGeometry, oldGeometry);
}
<commit_msg>Set currentScene's parent item before calculating contentHeight and contentWidth.<commit_after>/**
 * Copyright (C) 2012 by INdT
 *
 * 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
 * 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 Lesser 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.
 *
 * @author Rodrigo Goncalves de Oliveira <rodrigo.goncalves@openbossa.org>
 * @author Roger Felipe Zanoni da Silva <roger.zanoni@openbossa.org>
 */

#include "game.h"
#include "scene.h"
#include "viewport.h"

#include <QtQuick/QQuickWindow>
#include <QtGui/QCursor>

/*!
  \qmltype Game
  \inqmlmodule Bacon2D
  \inherits Item
  \brief The root element containing one or more Scene.

  The Game component is the root game component which
  contains one or more Scene components.  Only one
  Scene will be set as currentScene.

  Example usage:
  \qml
   import QtQuick 2.0
   import Bacon2D 1.0

   Game {
       id: game
       width: 800
       height: 600

       Scene {
           id: scene
           width: 300
           height: 300
       }
   }
   \endqml
*/
Game::Game(QQuickItem *parent)
    : QQuickItem(parent)
    , m_currentScene(0)
    , m_ups(30)
    , m_timerId(0)
{
    m_gameTime.start();
    m_timerId = startTimer(1000 / m_ups);
}

/*!
  \qmlproperty string Game::gameName
  \brief Name of the game, required if using Settings
*/
QString Game::gameName()
{
    return QCoreApplication::applicationName();
}

void Game::setGameName(const QString& gameName)
{
    // applicationName is needed for QSettings to create path to file
    QCoreApplication::setApplicationName(gameName);
    // Set the organizationName to match the applicationName, it's redundant
    // but creates path that plays well accross platforms
    QCoreApplication::setOrganizationName(gameName);
    Q_EMIT gameNameChanged();
}

/*!
  \qmlproperty Scene Game::currentScene
  \brief The current Scene
*/
Scene *Game::currentScene() const
{
    return m_currentScene;
}

void Game::setCurrentScene(Scene *currentScene)
{
    if (m_currentScene == currentScene)
        return;

    if (m_currentScene) {
        if (m_viewport) {
            m_viewport->setVisible(false);
            m_viewport = 0;
        }

        m_currentScene->setRunning(false);
        m_currentScene->setVisible(false);
    }

    m_currentScene = currentScene;

    if (m_currentScene) {
        m_currentScene->setGame(this);

        if (m_viewport = m_currentScene->viewport()) {
            m_viewport->setParent(this);
            m_viewport->setParentItem(this);
            m_viewport->setScene(m_currentScene);
            m_currentScene->setParentItem(m_viewport);
            m_viewport->setWidth(width());
            m_viewport->setHeight(height());
            m_viewport->setContentWidth(m_currentScene->width());
            m_viewport->setContentHeight(m_currentScene->height());
            m_viewport->updateMaxOffsets();
            m_viewport->setVisible(true);
        } else {
            m_currentScene->setParentItem(this);
        }

        m_currentScene->setRunning(true);
        m_currentScene->setVisible(true);
    }

    emit currentSceneChanged();
}

/*!
  \qmlproperty int Game::ups
  \brief This property holds the number of times update is called per second.

    Updates per second can be used to control the speed of the game
    loop.  The default is 30.
 */
int Game::ups() const
{
    return m_ups;
}

void Game::setUps(const int &ups)
{
    if (m_ups == ups)
        return;

    m_ups = ups;

    killTimer(m_timerId);
    m_gameTime.restart();
    m_timerId = startTimer(1000 / m_ups);

    emit upsChanged();
}

void Game::timerEvent(QTimerEvent *event)
{
    Q_UNUSED(event)

    update();
}

void Game::update()
{
    long elapsedTime = m_gameTime.restart();
    if (m_currentScene)
        m_currentScene->update(elapsedTime);
    if (m_viewport)
        m_viewport->update(elapsedTime);
}

/*!
  \qmlproperty QPointF Game::mouse
  \brief The point in the plane of the mouse pointer
*/
QPointF Game::mouse()
{
    return window()->mapFromGlobal(QCursor::pos());
}

void Game::geometryChanged(const QRectF &newGeometry, const QRectF &oldGeometry)
{
    if (newGeometry.isEmpty() || !isComponentComplete() || (newGeometry == oldGeometry))
        return;

    if (m_viewport && m_currentScene) {
        m_viewport->setWidth(width());
        m_viewport->setHeight(height());
        m_viewport->setContentWidth(m_currentScene->width());
        m_viewport->setContentHeight(m_currentScene->height());
        m_viewport->updateMaxOffsets();
    }

    QQuickItem::geometryChanged(newGeometry, oldGeometry);
}
<|endoftext|>


<commit_before>#include <ncurses.h>

#include <string>
#include <random>

#include "game.h"
#include "InfoPanel.h"

using namespace std;

void menuShow(WINDOW *wnd, string title);
void startGame();

WINDOW *wmenu, *wmain;

InfoPanel *infoPanel = new InfoPanel();

struct {
    vec2i pos;
    rect bounds;
    char disp_char;
} player;

rect game_area;

int init() {

    initscr();

    /*
     * init main window
     */

    wmain = newwin(40, 80, 1, 1);
    box(wmain, 0, 0);

    /*
     * init menu window
     */

    wmenu = newwin(10, 12, 10, 10);
    wborder(wmenu,
            ACS_BULLET, ACS_BULLET, ACS_BULLET, ACS_BULLET,     /* ls, rs, ts, bs */
            '+', '+', '+', '+');                                /* tl, tr, bl, br */

    noecho();
    keypad(wmenu, true);
    curs_set(0);

    return 0;
}

void run() {
    char menuItems[2][10] = {
        "start",
        "quit"
    };
    char menuItem[7];
    int ch, i = 0, width = 7;

    /*
     * init title, menu
     */

    for (i = 0; i < 2; i++) {
        if (i == 0) wattron(wmenu, A_STANDOUT);
        else wattroff(wmenu, A_STANDOUT);

        sprintf(menuItem, "%-7s", menuItems[i]);
        mvwprintw(wmenu, i + 1, 2, "%s", menuItem);
    }

    wrefresh(wmain);
    wrefresh(wmenu);
    infoPanel->update();
    menuShow(wmain, "TERMINAL QUEST");
    i = 0;

    string infoPos, infoKey, infoMsg;
    bool exitRequested = false, gameRequested = false;
    while (( ch = wgetch(wmenu)) != 'q') {
        infoMsg = "";
        infoPos = to_string(ch);
        infoKey = to_string(i);

        sprintf(menuItem, "%-7s", menuItems[i]);
        mvwprintw(wmenu, i + 1, 2, "%s", menuItem);

        switch (ch) {
            case KEY_UP:
            case 'k':
                i--;
                i = (i < 0) ? 1 : i;
                infoMsg = "up";
                break;
            case KEY_DOWN:
            case 'j':
                i++;
                i = (i > 1) ? 0: i;
                infoMsg = "down";
                break;
            case KEY_ENTER: /* numpad enter */
            case '\n':      /* keyboard return */
                if (i == 1) exitRequested = true;
                else if (i == 0) gameRequested = true;
                break;

        }

        infoPanel->push((infoPos + ' ' + infoKey + ' ' + infoMsg));

        wattron(wmenu, A_STANDOUT);
        sprintf(menuItem, "%-7s", menuItems[i]);
        mvwprintw(wmenu, i + 1, 2, "%s", menuItem);
        wattroff(wmenu, A_STANDOUT);

        if (exitRequested == true) {
            break;
        } else if (gameRequested) {
            delwin(wmenu);
            delwin(wmain);

            startGame();
            break;
        }
    }

    /*
     * exit
     */

    endwin();

}

void close() {
    endwin();
}

void menuShow(WINDOW *wnd, string title) {

    wmove(wnd, 5, 5);

    for (size_t i = 0; i < title.size(); i++) {
        waddch(wnd, title[i]);
        waddch(wnd, ' ');
    }

    wrefresh(wnd);
}

void startGame() {

    game_area = {
        {0, 0},
        {80, 40}
    };

    WINDOW *wgame = newwin(40, 80, 1, 1);
    box(wgame, '-', '.');
    keypad(wgame, true);

    /*
     * Randomly place player anywhere in game area
     */
    random_device rd;
    uniform_int_distribution<int> distx(game_area.left(), game_area.right());
    uniform_int_distribution<int> disty(game_area.top(), game_area.bot());
    int randx = distx(rd) + 1;
    int randy = disty(rd) + 1;
    player.pos = {
        randx, randy
    };
    player.disp_char = '@';

    wmove(wgame, player.pos.y, player.pos.x);
    waddch(wgame, player.disp_char);

    int ch, i;
    string infoKey, infoMsg;
    vec2i infoPos;
    while (( ch = wgetch(wgame)) != 'q') {

        infoMsg = "";
        infoKey = to_string(ch);

        werase(wgame);
        box(wgame, '-', '.');

        switch (ch) {
            case KEY_UP:
            case 'k':
                if (player.pos.y > game_area.top() + 1) player.pos.y--;
                break;
            case KEY_DOWN:
            case 'j':
                if (player.pos.y < game_area.bot() - 2) player.pos.y++;
                break;
            case KEY_LEFT:
            case 'h':
                if (player.pos.x > game_area.left() + 1) player.pos.x--;
                break;
            case KEY_RIGHT:
            case 'l':
                if (player.pos.x < game_area.right() - 2) player.pos.x++;
                break;
            case KEY_ENTER: /* numpad enter */
            case '\n':      /* keyboard return */
                break;

        }

        wmove(wgame, player.pos.y, player.pos.x);
        waddch(wgame, player.disp_char);

        infoPanel->push('{'
            + std::to_string(player.pos.x) + ','
            + std::to_string(player.pos.y) + '}'
            + " - right & left: {"
            + std::to_string(game_area.right()) + ','
            + std::to_string(game_area.left()) + '}'
            + " top & bot: {"
            + std::to_string(game_area.top()) + ','
            + std::to_string(game_area.bot()) + '}'
        );

        wrefresh(wgame);

    }

    delwin(wgame);
}

<commit_msg>Replace custom game border with default box<commit_after>#include <ncurses.h>

#include <string>
#include <random>

#include "game.h"
#include "InfoPanel.h"

using namespace std;

void menuShow(WINDOW *wnd, string title);
void startGame();

WINDOW *wmenu, *wmain;

InfoPanel *infoPanel = new InfoPanel();

struct {
    vec2i pos;
    rect bounds;
    char disp_char;
} player;

rect game_area;

int init() {

    initscr();

    /*
     * init main window
     */

    wmain = newwin(40, 80, 1, 1);
    box(wmain, 0, 0);

    /*
     * init menu window
     */

    wmenu = newwin(10, 12, 10, 10);
    wborder(wmenu,
            ACS_BULLET, ACS_BULLET, ACS_BULLET, ACS_BULLET,     /* ls, rs, ts, bs */
            '+', '+', '+', '+');                                /* tl, tr, bl, br */

    noecho();
    keypad(wmenu, true);
    curs_set(0);

    return 0;
}

void run() {
    char menuItems[2][10] = {
        "start",
        "quit"
    };
    char menuItem[7];
    int ch, i = 0, width = 7;

    /*
     * init title, menu
     */

    for (i = 0; i < 2; i++) {
        if (i == 0) wattron(wmenu, A_STANDOUT);
        else wattroff(wmenu, A_STANDOUT);

        sprintf(menuItem, "%-7s", menuItems[i]);
        mvwprintw(wmenu, i + 1, 2, "%s", menuItem);
    }

    wrefresh(wmain);
    wrefresh(wmenu);
    infoPanel->update();
    menuShow(wmain, "TERMINAL QUEST");
    i = 0;

    string infoPos, infoKey, infoMsg;
    bool exitRequested = false, gameRequested = false;
    while (( ch = wgetch(wmenu)) != 'q') {
        infoMsg = "";
        infoPos = to_string(ch);
        infoKey = to_string(i);

        sprintf(menuItem, "%-7s", menuItems[i]);
        mvwprintw(wmenu, i + 1, 2, "%s", menuItem);

        switch (ch) {
            case KEY_UP:
            case 'k':
                i--;
                i = (i < 0) ? 1 : i;
                infoMsg = "up";
                break;
            case KEY_DOWN:
            case 'j':
                i++;
                i = (i > 1) ? 0: i;
                infoMsg = "down";
                break;
            case KEY_ENTER: /* numpad enter */
            case '\n':      /* keyboard return */
                if (i == 1) exitRequested = true;
                else if (i == 0) gameRequested = true;
                break;

        }

        infoPanel->push((infoPos + ' ' + infoKey + ' ' + infoMsg));

        wattron(wmenu, A_STANDOUT);
        sprintf(menuItem, "%-7s", menuItems[i]);
        mvwprintw(wmenu, i + 1, 2, "%s", menuItem);
        wattroff(wmenu, A_STANDOUT);

        if (exitRequested == true) {
            break;
        } else if (gameRequested) {
            delwin(wmenu);
            delwin(wmain);

            startGame();
            break;
        }
    }

    /*
     * exit
     */

    endwin();

}

void close() {
    endwin();
}

void menuShow(WINDOW *wnd, string title) {

    wmove(wnd, 5, 5);

    for (size_t i = 0; i < title.size(); i++) {
        waddch(wnd, title[i]);
        waddch(wnd, ' ');
    }

    wrefresh(wnd);
}

void startGame() {

    game_area = {
        {0, 0},
        {80, 40}
    };

    WINDOW *wgame = newwin(40, 80, 1, 1);
    box(wgame, 0, 0);
    keypad(wgame, true);

    /*
     * Randomly place player anywhere in game area
     */
    random_device rd;
    uniform_int_distribution<int> distx(game_area.left(), game_area.right());
    uniform_int_distribution<int> disty(game_area.top(), game_area.bot());
    int randx = distx(rd) + 1;
    int randy = disty(rd) + 1;
    player.pos = {
        randx, randy
    };
    player.disp_char = '@';

    wmove(wgame, player.pos.y, player.pos.x);
    waddch(wgame, player.disp_char);

    int ch, i;
    string infoKey, infoMsg;
    vec2i infoPos;
    while (( ch = wgetch(wgame)) != 'q') {

        infoMsg = "";
        infoKey = to_string(ch);

        werase(wgame);
        box(wgame, 0, 0);

        switch (ch) {
            case KEY_UP:
            case 'k':
                if (player.pos.y > game_area.top() + 1) player.pos.y--;
                break;
            case KEY_DOWN:
            case 'j':
                if (player.pos.y < game_area.bot() - 2) player.pos.y++;
                break;
            case KEY_LEFT:
            case 'h':
                if (player.pos.x > game_area.left() + 1) player.pos.x--;
                break;
            case KEY_RIGHT:
            case 'l':
                if (player.pos.x < game_area.right() - 2) player.pos.x++;
                break;
            case KEY_ENTER: /* numpad enter */
            case '\n':      /* keyboard return */
                break;

        }

        wmove(wgame, player.pos.y, player.pos.x);
        waddch(wgame, player.disp_char);

        infoPanel->push('{'
            + std::to_string(player.pos.x) + ','
            + std::to_string(player.pos.y) + '}'
            + " - right & left: {"
            + std::to_string(game_area.right()) + ','
            + std::to_string(game_area.left()) + '}'
            + " top & bot: {"
            + std::to_string(game_area.top()) + ','
            + std::to_string(game_area.bot()) + '}'
        );

        wrefresh(wgame);

    }

    delwin(wgame);
}

<|endoftext|>


<commit_before>#pragma ident "$Id$"

//============================================================================
//
//  This file is part of GPSTk, the GPS Toolkit.
//
//  The GPSTk 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
//  any later version.
//
//  The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Copyright 2004, The University of Texas at Austin
//
//============================================================================

//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
//                           release, distribution is unlimited.
//
//=============================================================================

/**
 * @file EphemerisStore.hpp
 * Base for ephemeris storage classes
 */

#ifndef GPSTK_EPHEMERISSTORE_HPP
#define GPSTK_EPHEMERISSTORE_HPP

#include <iostream>
#include <string>
#include <list>
#include <map>

#include "Exception.hpp"
#include "SatID.hpp"
#include "DayTime.hpp"
#include "Xvt.hpp"

namespace gpstk
{
   /** @addtogroup ephemstore */
   //@{

      ///  This class defines an interface to hide how we are getting an SV's
      /// position at some point in time.
   class EphemerisStore
   {
   public:
         /// Thrown when attempting to read an ephemeris that isn't stored.
         /// @ingroup exceptiongroup
      NEW_EXCEPTION_CLASS(NoEphemerisFound, gpstk::Exception);

         /// destructor.
      virtual ~EphemerisStore() {}

         /** This returns the PVT of the SV in ECEF coordinates at the
          * indicated time.
          * @param sat the SV's SatID
          * @param t the time to look up
          * @return the Xvt of the SV at time t
          */
      virtual Xvt getSatXvt(SatID sat,
                            const gpstk::DayTime& t) const
         throw(NoEphemerisFound) = 0;

         /// \deprecated use the SatID version getSatXvt
      virtual Xvt getPrnXvt(short prn,
                            const gpstk::DayTime& t) const
         throw(NoEphemerisFound) = 0;

         /** Dumps all the ephemeris data stored in this object.
          * @param detail the level of detail to provide
          */
      virtual void dump(short detail = 0,
                        std::ostream& s = std::cout) const = 0;

         /// Edit the dataset, removing data outside this time interval
      virtual void edit(const DayTime& tmin,
                        const DayTime& tmax
                        = DayTime(DayTime::END_OF_TIME) ) = 0;

         /** Return the time of the first ephemeris in the object.
          * @return the time of the first ephemeris in the object
          */
      virtual gpstk::DayTime getInitialTime() const = 0;

         /** Return the time of the last ephemeris in the object.
          * @return the time of the last ephemeris in the object
          */
      virtual gpstk::DayTime getFinalTime() const = 0;

   }; // end class EphemerisStore

   //@}

} // namespace

#endif
<commit_msg>src/EphemerisStore.hpp: Added virtual method getTGD().<commit_after>#pragma ident "$Id$"

//============================================================================
//
//  This file is part of GPSTk, the GPS Toolkit.
//
//  The GPSTk 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
//  any later version.
//
//  The GPSTk 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 GPSTk; if not, write to the Free Software Foundation,
//  Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
//
//  Copyright 2004, The University of Texas at Austin
//
//============================================================================

//============================================================================
//
//This software developed by Applied Research Laboratories at the University of
//Texas at Austin, under contract to an agency or agencies within the U.S.
//Department of Defense. The U.S. Government retains all rights to use,
//duplicate, distribute, disclose, or release this software.
//
//Pursuant to DoD Directive 523024
//
// DISTRIBUTION STATEMENT A: This software has been approved for public
//                           release, distribution is unlimited.
//
//=============================================================================

/**
 * @file EphemerisStore.hpp
 * Base for ephemeris storage classes
 */

#ifndef GPSTK_EPHEMERISSTORE_HPP
#define GPSTK_EPHEMERISSTORE_HPP

#include <iostream>
#include <string>
#include <list>
#include <map>

#include "Exception.hpp"
#include "SatID.hpp"
#include "DayTime.hpp"
#include "Xvt.hpp"

namespace gpstk
{
   /** @addtogroup ephemstore */
   //@{

      ///  This class defines an interface to hide how we are getting an SV's
      /// position at some point in time.
   class EphemerisStore
   {
   public:
         /// Thrown when attempting to read an ephemeris that isn't stored.
         /// @ingroup exceptiongroup
      NEW_EXCEPTION_CLASS(NoEphemerisFound, gpstk::Exception);

         /// destructor.
      virtual ~EphemerisStore() {}

         /** This returns the PVT of the SV in ECEF coordinates at the
          * indicated time.
          * @param sat the SV's SatID
          * @param t the time to look up
          * @return the Xvt of the SV at time t
          */
      virtual Xvt getSatXvt(SatID sat,
                            const gpstk::DayTime& t) const
         throw(NoEphemerisFound) = 0;

         /// \deprecated use the SatID version getSatXvt
      virtual Xvt getPrnXvt(short prn,
                            const gpstk::DayTime& t) const
         throw(NoEphemerisFound) = 0;

       /** This method returns the Total Group Delay of the SV (in meters) at the
        * indicated time.
        * @param sat    the SV's SatID
        * @param t      the time to look up
        * @return       the TGD (in meters) of the SV at time t
        */
      virtual double getTGD(SatID sat, const gpstk::DayTime& t) const
         throw(NoEphemerisFound) = 0;

         /** Dumps all the ephemeris data stored in this object.
          * @param detail the level of detail to provide
          */
      virtual void dump(short detail = 0,
                        std::ostream& s = std::cout) const = 0;

         /// Edit the dataset, removing data outside this time interval
      virtual void edit(const DayTime& tmin,
                        const DayTime& tmax
                        = DayTime(DayTime::END_OF_TIME) ) = 0;

         /** Return the time of the first ephemeris in the object.
          * @return the time of the first ephemeris in the object
          */
      virtual gpstk::DayTime getInitialTime() const = 0;

         /** Return the time of the last ephemeris in the object.
          * @return the time of the last ephemeris in the object
          */
      virtual gpstk::DayTime getFinalTime() const = 0;

   }; // end class EphemerisStore

   //@}

} // namespace

#endif
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////

// commodity.cc

#include "stdsneezy.h"
#include "shop.h"
#include "obj_commodity.h"

TCommodity::TCommodity() :
  TObj()
{
}

TCommodity::TCommodity(const TCommodity &a) :
  TObj(a)
{
}

TCommodity & TCommodity::operator=(const TCommodity &a)
{
  if (this == &a) return *this;
  TObj::operator=(a);
  return *this;
}

TCommodity::~TCommodity()
{
}

void TCommodity::assignFourValues(int, int, int, int)
{
}

void TCommodity::getFourValues(int *x1, int *x2, int *x3, int *x4) const
{
  *x1 = 0;
  *x2 = 0;
  *x3 = 0;
  *x4 = 0;
}

sstring TCommodity::statObjInfo() const
{
  sstring a("");
  return a;
}

void TCommodity::lowCheck()
{
  if (!isname("commodity", name)) {
    vlogf(LOG_LOW, fmt("raw material without COMMODITY in name (%s : %d)") %
               getName() % objVnum());
  }
  if (!numUnits()) {
    vlogf(LOG_LOW, fmt("raw material needs weight above 0.0 (%s : %d)") %
               getName() % objVnum());
  }
  if (!pricePerUnit()) {
    vlogf(LOG_LOW, fmt("raw material needs price above 0 (%s : %d)") %
               getName() % objVnum());
  }

  TObj::lowCheck();
}

int TCommodity::sellPrice(int num, int shop_nr, float, const TBeing *ch)
{
  int cost_per;
  int price;

  cost_per = pricePerUnit();
  price = (int) (numUnits() * cost_per * shop_index[shop_nr].getProfitSell(this,ch));

  if (obj_flags.cost <= 1) {
    price = max(0, price);
  } else {
    price = max(1, price);
  }

  return price;
}

int TCommodity::shopPrice(int num, int shop_nr, float, const TBeing *ch) const
{
  int cost_per;
  int price;

  cost_per = pricePerUnit();
  price = (int) (num * cost_per * shop_index[shop_nr].getProfitBuy(this, ch));
  price = max(1, price);

  return price;
}

int TCommodity::buyMe(TBeing *ch, TMonster *keeper, int num, int shop_nr)
{
  char buf[256];
  char buf2[80];
  int price, cost_per, vnum;
  TObj *obj2;

  if (parent != keeper) {
    vlogf(LOG_BUG, "Error: buy_treasure():shop.cc  obj not on keeper");
    return -1;
  }
  if (!shop_index[shop_nr].willBuy(this)) {
    keeper->doTell(ch->getName(), shop_index[shop_nr].do_not_buy);
    return -1;
  }
  if (num > (int) (numUnits())) {
    num = (int) (numUnits());
    keeper->doTell(ch->getName(), fmt("I don't have that much %s.  Here's the %d that I do have.") % fname(name) % num);
  }
  cost_per = pricePerUnit();
  price = shopPrice(num, shop_nr, -1, ch);
  vnum = objVnum();

  if (ch->getMoney() < price) {
    keeper->doTell(ch->name, shop_index[shop_nr].missing_cash2);

    switch (shop_index[shop_nr].temper1) {
      case 0:
        keeper->doAction(ch->name, CMD_SMILE);
        return -1;
      case 1:
        act("$n grins happily.", 0, keeper, 0, 0, TO_ROOM);
        return -1;
      default:
        return -1;
    }
  }
  strcpy(buf2, fname(name).c_str());
  --(*this);
  int num2 = (int) (numUnits()) - num;
  if (num2) {
    describeTreasure(buf2, num2, cost_per);
    *keeper += *this;
  } else {
    delete this;
  }

  if (num) {
    obj2 = read_object(vnum, VIRTUAL);
    obj2->describeTreasure(buf2, num, cost_per);
    *ch += *obj2;
    keeper->doTell(ch->getName(), fmt("Here ya go.  That's %d units of %s.") %
		   num % buf2);
    act("$n buys $p.", TRUE, ch, obj2, keeper, TO_NOTVICT);

    ch->giveMoney(keeper, price, GOLD_COMM);
    shoplog(shop_nr, ch, keeper, obj2->getName(), price, "buying");

  } else {
    // this happens with sub zero weight components
    vlogf(LOG_BUG, fmt("Bogus num %d in buyMe component at %d.  wgt=%.2f") %  num % ch->in_room % getWeight());
  }

  sprintf(buf, "%s/%d", SHOPFILE_PATH, shop_nr);
  keeper->saveItems(buf);
  ch->doSave(SILENT_YES);
  return price;
}

void TCommodity::sellMe(TBeing *ch, TMonster *keeper, int shop_nr, int)
{
  TThing *t;
  TCommodity *obj2 = NULL;
  int num, price;
  char buf[256], buf2[80];

  strcpy(buf2, fname(name).c_str());
  price = sellPrice(1, shop_nr, -1, ch);

  if (isObjStat(ITEM_NODROP)) {
    ch->sendTo("You can't let go of it, it must be CURSED!\n\r");
    return;
  }
  if (isObjStat(ITEM_PROTOTYPE)) {
    ch->sendTo("That's a prototype, no selling that!\n\r");
    return;
  }
  if (will_not_buy(ch, keeper, this, shop_nr))
    return;

  if (!shop_index[shop_nr].willBuy(this)) {
    keeper->doTell(ch->getName(), shop_index[shop_nr].do_not_buy);
    return;
  }
  if (keeper->getMoney() < price) {
    keeper->doTell(ch->getName(), shop_index[shop_nr].missing_cash1);
    return;
  }
  for (t = keeper->getStuff(); t; t = t->nextThing) {
    obj2 = dynamic_cast<TCommodity *>(t);
    if (!obj2)
      continue;

    if (obj2->objVnum() == objVnum())
      break;
  }
  if (!t) {
    TObj *to = read_object(objVnum(), VIRTUAL);
    obj2 = dynamic_cast<TCommodity *>(to);
    obj2->setWeight(0.0);
  } else
    --(*obj2);
  num = obj2->numUnits() + numUnits();
  num = max(min(num, 10000), 0);

  if (num) {
    int cost_per = pricePerUnit();
    obj2->describeTreasure(buf2, num, cost_per);
    *keeper += *obj2;
    --(*this);

    keeper->giveMoney(ch, price, GOLD_COMM);
    shoplog(shop_nr, ch, keeper, obj2->getName(), -price, "selling");

    keeper->doTell(ch->getName(), fmt("Thanks, here's your %d talens.") % price);
    act("$n sells $p.", TRUE, ch, this, 0, TO_ROOM);
    if (ch->isAffected(AFF_GROUP) && ch->desc &&
            IS_SET(ch->desc->autobits, AUTO_SPLIT) &&
            (ch->master || ch->followers)){
      sprintf(buf, "%d", price);
      ch->doSplit(buf, false);
    }
    delete this;
  }
  ch->doSave(SILENT_YES);
  sprintf(buf, "%s/%d", SHOPFILE_PATH, shop_nr);
  keeper->saveItems(buf);
  return;
}

int TCommodity::sellCommod(TBeing *ch, TMonster *keeper, int shop_nr, TThing *bag)
{
  int rc;

  if (equippedBy)
    *ch += *ch->unequip(eq_pos);

  if (bag && bag != ch) {
    rc = get(ch, this, bag, GETOBJOBJ, true);
    if (IS_SET_DELETE(rc, DELETE_ITEM)) {
      return DELETE_THIS;
    }
    if (IS_SET_DELETE(rc, DELETE_VICT)) {
      return DELETE_ITEM;
    }
    if (IS_SET_DELETE(rc, DELETE_THIS)) {
      return DELETE_VICT;
    }
    if (!dynamic_cast<TBeing *>(parent)) {
      // could fail on volume or sumthing
      return FALSE;
    }
  }

  sellMe(ch, keeper, shop_nr, 1);
  return FALSE;
}

void TCommodity::valueMe(TBeing *ch, TMonster *keeper, int shop_nr, int)
{
  int price;
  char buf2[80];

  strcpy(buf2, fname(name).c_str());
  price = sellPrice(1, shop_nr, -1, ch);

  if (!shop_index[shop_nr].willBuy(this)) {
    keeper->doTell(ch->getName(), shop_index[shop_nr].do_not_buy);
    return;
  }

  keeper->doTell(ch->getName(), "Hmm, I'd give you %d talens for that.", price);
  return;
}

const sstring TCommodity::shopList(const TBeing *ch, const sstring &arg, int min_amt, int max_amt, int, int, int k, unsigned long int) const
{
  char buf[256];
  int cost = pricePerUnit();

  sprintf(buf, "[%2d] COMMODITY: %-20.20s  : %5d units    %5d talens (per unit)\n\r",
            k + 1, fname(name).c_str(),
            (int) (numUnits()), (int) cost);
  if (arg.empty() && min_amt == 999999)     /* everything */
  /* specific item */
    return buf;
  else if (isname(arg, name) && min_amt == 999999)
    return buf;
  /* specific item and specific cost */
  else if (isname(arg, name) && cost >= min_amt && cost <= max_amt)
    return buf;
  else if (arg.empty() && cost >= min_amt && cost <= max_amt)   /* specific cost */
    return buf;
  else
    return "";
}

int TCommodity::numUnits() const
{
  return (int) (10.0 * getWeight());
}

int TCommodity::pricePerUnit() const
{
  int num = numUnits();
  int price = (int) (num ? obj_flags.cost / num : 0);

  if (obj_flags.cost) {
    price = max(price, 1);
//    obj_flags.cost = price * num;  // just correct it
  }

  return price;
}
<commit_msg>added reserve handling<commit_after>//////////////////////////////////////////////////////////////////////////
//
// SneezyMUD - All rights reserved, SneezyMUD Coding Team
//
//////////////////////////////////////////////////////////////////////////

// commodity.cc

#include "stdsneezy.h"
#include "shop.h"
#include "obj_commodity.h"
#include "shopowned.h"

TCommodity::TCommodity() :
  TObj()
{
}

TCommodity::TCommodity(const TCommodity &a) :
  TObj(a)
{
}

TCommodity & TCommodity::operator=(const TCommodity &a)
{
  if (this == &a) return *this;
  TObj::operator=(a);
  return *this;
}

TCommodity::~TCommodity()
{
}

void TCommodity::assignFourValues(int, int, int, int)
{
}

void TCommodity::getFourValues(int *x1, int *x2, int *x3, int *x4) const
{
  *x1 = 0;
  *x2 = 0;
  *x3 = 0;
  *x4 = 0;
}

sstring TCommodity::statObjInfo() const
{
  sstring a("");
  return a;
}

void TCommodity::lowCheck()
{
  if (!isname("commodity", name)) {
    vlogf(LOG_LOW, fmt("raw material without COMMODITY in name (%s : %d)") %
               getName() % objVnum());
  }
  if (!numUnits()) {
    vlogf(LOG_LOW, fmt("raw material needs weight above 0.0 (%s : %d)") %
               getName() % objVnum());
  }
  if (!pricePerUnit()) {
    vlogf(LOG_LOW, fmt("raw material needs price above 0 (%s : %d)") %
               getName() % objVnum());
  }

  TObj::lowCheck();
}

int TCommodity::sellPrice(int num, int shop_nr, float, const TBeing *ch)
{
  int cost_per;
  int price;

  cost_per = pricePerUnit();
  price = (int) (numUnits() * cost_per * shop_index[shop_nr].getProfitSell(this,ch));

  if (obj_flags.cost <= 1) {
    price = max(0, price);
  } else {
    price = max(1, price);
  }

  return price;
}

int TCommodity::shopPrice(int num, int shop_nr, float, const TBeing *ch) const
{
  int cost_per;
  int price;

  cost_per = pricePerUnit();
  price = (int) (num * cost_per * shop_index[shop_nr].getProfitBuy(this, ch));
  price = max(1, price);

  return price;
}

int TCommodity::buyMe(TBeing *ch, TMonster *keeper, int num, int shop_nr)
{
  char buf[256];
  char buf2[80];
  int price, cost_per, vnum;
  TObj *obj2;

  if (parent != keeper) {
    vlogf(LOG_BUG, "Error: buy_treasure():shop.cc  obj not on keeper");
    return -1;
  }
  if (!shop_index[shop_nr].willBuy(this)) {
    keeper->doTell(ch->getName(), shop_index[shop_nr].do_not_buy);
    return -1;
  }
  if (num > (int) (numUnits())) {
    num = (int) (numUnits());
    keeper->doTell(ch->getName(), fmt("I don't have that much %s.  Here's the %d that I do have.") % fname(name) % num);
  }
  cost_per = pricePerUnit();
  price = shopPrice(num, shop_nr, -1, ch);
  vnum = objVnum();

  if (ch->getMoney() < price) {
    keeper->doTell(ch->name, shop_index[shop_nr].missing_cash2);

    switch (shop_index[shop_nr].temper1) {
      case 0:
        keeper->doAction(ch->name, CMD_SMILE);
        return -1;
      case 1:
        act("$n grins happily.", 0, keeper, 0, 0, TO_ROOM);
        return -1;
      default:
        return -1;
    }
  }
  strcpy(buf2, fname(name).c_str());
  --(*this);
  int num2 = (int) (numUnits()) - num;
  if (num2) {
    describeTreasure(buf2, num2, cost_per);
    *keeper += *this;
  } else {
    delete this;
  }

  if (num) {
    obj2 = read_object(vnum, VIRTUAL);
    obj2->describeTreasure(buf2, num, cost_per);
    *ch += *obj2;
    keeper->doTell(ch->getName(), fmt("Here ya go.  That's %d units of %s.") %
		   num % buf2);
    act("$n buys $p.", TRUE, ch, obj2, keeper, TO_NOTVICT);

    ch->giveMoney(keeper, price, GOLD_COMM);
    shoplog(shop_nr, ch, keeper, obj2->getName(), price, "buying");

    TShopOwned tso(shop_nr, keeper, ch);
    tso.doReserve();

  } else {
    // this happens with sub zero weight components
    vlogf(LOG_BUG, fmt("Bogus num %d in buyMe component at %d.  wgt=%.2f") %  num % ch->in_room % getWeight());
  }

  sprintf(buf, "%s/%d", SHOPFILE_PATH, shop_nr);
  keeper->saveItems(buf);
  ch->doSave(SILENT_YES);
  return price;
}

void TCommodity::sellMe(TBeing *ch, TMonster *keeper, int shop_nr, int)
{
  TThing *t;
  TCommodity *obj2 = NULL;
  int num, price;
  char buf[256], buf2[80];

  strcpy(buf2, fname(name).c_str());
  price = sellPrice(1, shop_nr, -1, ch);

  if (isObjStat(ITEM_NODROP)) {
    ch->sendTo("You can't let go of it, it must be CURSED!\n\r");
    return;
  }
  if (isObjStat(ITEM_PROTOTYPE)) {
    ch->sendTo("That's a prototype, no selling that!\n\r");
    return;
  }
  if (will_not_buy(ch, keeper, this, shop_nr))
    return;

  if (!shop_index[shop_nr].willBuy(this)) {
    keeper->doTell(ch->getName(), shop_index[shop_nr].do_not_buy);
    return;
  }
  if (keeper->getMoney() < price) {
    keeper->doTell(ch->getName(), shop_index[shop_nr].missing_cash1);
    return;
  }
  for (t = keeper->getStuff(); t; t = t->nextThing) {
    obj2 = dynamic_cast<TCommodity *>(t);
    if (!obj2)
      continue;

    if (obj2->objVnum() == objVnum())
      break;
  }
  if (!t) {
    TObj *to = read_object(objVnum(), VIRTUAL);
    obj2 = dynamic_cast<TCommodity *>(to);
    obj2->setWeight(0.0);
  } else
    --(*obj2);
  num = obj2->numUnits() + numUnits();
  num = max(min(num, 10000), 0);

  if (num) {
    int cost_per = pricePerUnit();
    obj2->describeTreasure(buf2, num, cost_per);
    *keeper += *obj2;
    --(*this);

    keeper->giveMoney(ch, price, GOLD_COMM);
    shoplog(shop_nr, ch, keeper, obj2->getName(), -price, "selling");

    TShopOwned tso(shop_nr, keeper, ch);
    tso.doReserve();

    keeper->doTell(ch->getName(), fmt("Thanks, here's your %d talens.") % price);
    act("$n sells $p.", TRUE, ch, this, 0, TO_ROOM);
    if (ch->isAffected(AFF_GROUP) && ch->desc &&
            IS_SET(ch->desc->autobits, AUTO_SPLIT) &&
            (ch->master || ch->followers)){
      sprintf(buf, "%d", price);
      ch->doSplit(buf, false);
    }
    delete this;
  }
  ch->doSave(SILENT_YES);
  sprintf(buf, "%s/%d", SHOPFILE_PATH, shop_nr);
  keeper->saveItems(buf);
  return;
}

int TCommodity::sellCommod(TBeing *ch, TMonster *keeper, int shop_nr, TThing *bag)
{
  int rc;

  if (equippedBy)
    *ch += *ch->unequip(eq_pos);

  if (bag && bag != ch) {
    rc = get(ch, this, bag, GETOBJOBJ, true);
    if (IS_SET_DELETE(rc, DELETE_ITEM)) {
      return DELETE_THIS;
    }
    if (IS_SET_DELETE(rc, DELETE_VICT)) {
      return DELETE_ITEM;
    }
    if (IS_SET_DELETE(rc, DELETE_THIS)) {
      return DELETE_VICT;
    }
    if (!dynamic_cast<TBeing *>(parent)) {
      // could fail on volume or sumthing
      return FALSE;
    }
  }

  sellMe(ch, keeper, shop_nr, 1);
  return FALSE;
}

void TCommodity::valueMe(TBeing *ch, TMonster *keeper, int shop_nr, int)
{
  int price;
  char buf2[80];

  strcpy(buf2, fname(name).c_str());
  price = sellPrice(1, shop_nr, -1, ch);

  if (!shop_index[shop_nr].willBuy(this)) {
    keeper->doTell(ch->getName(), shop_index[shop_nr].do_not_buy);
    return;
  }

  keeper->doTell(ch->getName(), "Hmm, I'd give you %d talens for that.", price);
  return;
}

const sstring TCommodity::shopList(const TBeing *ch, const sstring &arg, int min_amt, int max_amt, int, int, int k, unsigned long int) const
{
  char buf[256];
  int cost = pricePerUnit();

  sprintf(buf, "[%2d] COMMODITY: %-20.20s  : %5d units    %5d talens (per unit)\n\r",
            k + 1, fname(name).c_str(),
            (int) (numUnits()), (int) cost);
  if (arg.empty() && min_amt == 999999)     /* everything */
  /* specific item */
    return buf;
  else if (isname(arg, name) && min_amt == 999999)
    return buf;
  /* specific item and specific cost */
  else if (isname(arg, name) && cost >= min_amt && cost <= max_amt)
    return buf;
  else if (arg.empty() && cost >= min_amt && cost <= max_amt)   /* specific cost */
    return buf;
  else
    return "";
}

int TCommodity::numUnits() const
{
  return (int) (10.0 * getWeight());
}

int TCommodity::pricePerUnit() const
{
  int num = numUnits();
  int price = (int) (num ? obj_flags.cost / num : 0);

  if (obj_flags.cost) {
    price = max(price, 1);
//    obj_flags.cost = price * num;  // just correct it
  }

  return price;
}
<|endoftext|>


<commit_before>//
// Created by bentoo on 9/28/16.
//

#include "FreeListAllocator.h"

namespace Memory
{
	FreeListAllocator::FreeListAllocator(void *memory, std::size_t size)
		: Allocator(memory, size)
	{

	}

	void* FreeListAllocator::allocate(std::size_t size, std::size_t alignment, std::size_t offset)
	{

	}

	std::size_t FreeListAllocator::getAllocationSize(const void *ptr) const
	{

	}

	void FreeListAllocator::deallocate(void *ptr)
	{

	}

	bool FreeListAllocator::hasAddress(const void *ptr) const
	{

	}
}
<commit_msg>Mocked FreeListAllocator<commit_after>//
// Created by bentoo on 9/28/16.
//

#include "FreeListAllocator.h"

namespace Memory
{
	FreeListAllocator::FreeListAllocator(void *memory, std::size_t size)
		: Allocator(memory, size)
	{

	}

	void* FreeListAllocator::allocate(std::size_t size, std::size_t alignment, std::size_t offset)
	{
		return nullptr;
	}

	std::size_t FreeListAllocator::getAllocationSize(const void *ptr) const
	{
		return 0;
	}

	void FreeListAllocator::deallocate(void *ptr)
	{

	}

	bool FreeListAllocator::hasAddress(const void *ptr) const
	{
		return false;
	}
}
<|endoftext|>


<commit_before>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                          License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/

#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__

#if defined _MSC_VER && _MSC_VER >= 1200
    // disable warnings related to inline functions
    #pragma warning( disable: 4251 4711 4710 4514 )
#endif

#ifdef HAVE_CVCONFIG_H
#include "cvconfig.h"
#endif

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/core/internal.hpp"
#include <math.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <float.h>

#ifdef HAVE_TEGRA_OPTIMIZATION
#include "opencv2/imgproc/imgproc_tegra.hpp"
#endif

/* helper tables */
extern const uchar icvSaturate8u_cv[];
#define CV_FAST_CAST_8U(t)  (assert(-256 <= (t) || (t) <= 512), icvSaturate8u_cv[(t)+256])
#define CV_CALC_MIN_8U(a,b) (a) -= CV_FAST_CAST_8U((a) - (b))
#define CV_CALC_MAX_8U(a,b) (a) += CV_FAST_CAST_8U((b) - (a))

// -256.f ... 511.f
extern const float icv8x32fTab_cv[];
#define CV_8TO32F(x)  icv8x32fTab_cv[(x)+256]

// (-128.f)^2 ... (255.f)^2
extern const float icv8x32fSqrTab[];
#define CV_8TO32F_SQR(x)  icv8x32fSqrTab[(x)+128]

namespace cv
{

static inline Point normalizeAnchor( Point anchor, Size ksize )
{
    if( anchor.x == -1 )
        anchor.x = ksize.width/2;
    if( anchor.y == -1 )
        anchor.y = ksize.height/2;
    CV_Assert( anchor.inside(Rect(0, 0, ksize.width, ksize.height)) );
    return anchor;
}

void preprocess2DKernel( const Mat& kernel, vector<Point>& coords, vector<uchar>& coeffs );
void crossCorr( const Mat& src, const Mat& templ, Mat& dst,
                Size corrsize, int ctype,
                Point anchor=Point(0,0), double delta=0,
                int borderType=BORDER_REFLECT_101 );

}

typedef struct CvPyramid
{
    uchar **ptr;
    CvSize *sz;
    double *rate;
    int *step;
    uchar *state;
    int level;
}
CvPyramid;

#define  CV_COPY( dst, src, len, idx ) \
    for( (idx) = 0; (idx) < (len); (idx)++) (dst)[idx] = (src)[idx]

#define  CV_SET( dst, val, len, idx )  \
    for( (idx) = 0; (idx) < (len); (idx)++) (dst)[idx] = (val)

/* performs convolution of 2d floating-point array with 3x1, 1x3 or separable 3x3 mask */
void icvSepConvSmall3_32f( float* src, int src_step, float* dst, int dst_step,
            CvSize src_size, const float* kx, const float* ky, float* buffer );

#undef   CV_CALC_MIN
#define  CV_CALC_MIN(a, b) if((a) > (b)) (a) = (b)

#undef   CV_CALC_MAX
#define  CV_CALC_MAX(a, b) if((a) < (b)) (a) = (b)

CvStatus CV_STDCALL
icvCopyReplicateBorder_8u( const uchar* src, int srcstep, CvSize srcroi,
                           uchar* dst, int dststep, CvSize dstroi,
                           int left, int right, int cn, const uchar* value = 0 );

CvStatus CV_STDCALL icvGetRectSubPix_8u_C1R
( const uchar* src, int src_step, CvSize src_size,
  uchar* dst, int dst_step, CvSize win_size, CvPoint2D32f center );
CvStatus CV_STDCALL icvGetRectSubPix_8u32f_C1R
( const uchar* src, int src_step, CvSize src_size,
  float* dst, int dst_step, CvSize win_size, CvPoint2D32f center );
CvStatus CV_STDCALL icvGetRectSubPix_32f_C1R
( const float* src, int src_step, CvSize src_size,
  float* dst, int dst_step, CvSize win_size, CvPoint2D32f center );

CvStatus CV_STDCALL icvGetQuadrangleSubPix_8u_C1R
( const uchar* src, int src_step, CvSize src_size,
  uchar* dst, int dst_step, CvSize win_size, const float *matrix );
CvStatus CV_STDCALL icvGetQuadrangleSubPix_8u32f_C1R
( const uchar* src, int src_step, CvSize src_size,
  float* dst, int dst_step, CvSize win_size, const float *matrix );
CvStatus CV_STDCALL icvGetQuadrangleSubPix_32f_C1R
( const float* src, int src_step, CvSize src_size,
  float* dst, int dst_step, CvSize win_size, const float *matrix );

#include "_geom.h"

#endif /*__OPENCV_CV_INTERNAL_H_*/
<commit_msg>Added missed macro<commit_after>/*M///////////////////////////////////////////////////////////////////////////////////////
//
//  IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
//  By downloading, copying, installing or using the software you agree to this license.
//  If you do not agree to this license, do not download, install,
//  copy or use the software.
//
//
//                          License Agreement
//                For Open Source Computer Vision Library
//
// Copyright (C) 2000-2008, Intel Corporation, all rights reserved.
// Copyright (C) 2009, Willow Garage Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
//   * Redistribution's of source code must retain the above copyright notice,
//     this list of conditions and the following disclaimer.
//
//   * Redistribution's 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.
//
//   * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/

#ifndef __OPENCV_PRECOMP_H__
#define __OPENCV_PRECOMP_H__

#if defined _MSC_VER && _MSC_VER >= 1200
    // disable warnings related to inline functions
    #pragma warning( disable: 4251 4711 4710 4514 )
#endif

#ifdef HAVE_CVCONFIG_H
#include "cvconfig.h"
#endif

#include "opencv2/imgproc/imgproc.hpp"
#include "opencv2/imgproc/imgproc_c.h"
#include "opencv2/core/internal.hpp"
#include <math.h>
#include <assert.h>
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <float.h>

#ifdef HAVE_TEGRA_OPTIMIZATION
#include "opencv2/imgproc/imgproc_tegra.hpp"
#else
#define GET_OPTIMIZED(func) (func)
#endif

/* helper tables */
extern const uchar icvSaturate8u_cv[];
#define CV_FAST_CAST_8U(t)  (assert(-256 <= (t) || (t) <= 512), icvSaturate8u_cv[(t)+256])
#define CV_CALC_MIN_8U(a,b) (a) -= CV_FAST_CAST_8U((a) - (b))
#define CV_CALC_MAX_8U(a,b) (a) += CV_FAST_CAST_8U((b) - (a))

// -256.f ... 511.f
extern const float icv8x32fTab_cv[];
#define CV_8TO32F(x)  icv8x32fTab_cv[(x)+256]

// (-128.f)^2 ... (255.f)^2
extern const float icv8x32fSqrTab[];
#define CV_8TO32F_SQR(x)  icv8x32fSqrTab[(x)+128]

namespace cv
{

static inline Point normalizeAnchor( Point anchor, Size ksize )
{
    if( anchor.x == -1 )
        anchor.x = ksize.width/2;
    if( anchor.y == -1 )
        anchor.y = ksize.height/2;
    CV_Assert( anchor.inside(Rect(0, 0, ksize.width, ksize.height)) );
    return anchor;
}

void preprocess2DKernel( const Mat& kernel, vector<Point>& coords, vector<uchar>& coeffs );
void crossCorr( const Mat& src, const Mat& templ, Mat& dst,
                Size corrsize, int ctype,
                Point anchor=Point(0,0), double delta=0,
                int borderType=BORDER_REFLECT_101 );

}

typedef struct CvPyramid
{
    uchar **ptr;
    CvSize *sz;
    double *rate;
    int *step;
    uchar *state;
    int level;
}
CvPyramid;

#define  CV_COPY( dst, src, len, idx ) \
    for( (idx) = 0; (idx) < (len); (idx)++) (dst)[idx] = (src)[idx]

#define  CV_SET( dst, val, len, idx )  \
    for( (idx) = 0; (idx) < (len); (idx)++) (dst)[idx] = (val)

/* performs convolution of 2d floating-point array with 3x1, 1x3 or separable 3x3 mask */
void icvSepConvSmall3_32f( float* src, int src_step, float* dst, int dst_step,
            CvSize src_size, const float* kx, const float* ky, float* buffer );

#undef   CV_CALC_MIN
#define  CV_CALC_MIN(a, b) if((a) > (b)) (a) = (b)

#undef   CV_CALC_MAX
#define  CV_CALC_MAX(a, b) if((a) < (b)) (a) = (b)

CvStatus CV_STDCALL
icvCopyReplicateBorder_8u( const uchar* src, int srcstep, CvSize srcroi,
                           uchar* dst, int dststep, CvSize dstroi,
                           int left, int right, int cn, const uchar* value = 0 );

CvStatus CV_STDCALL icvGetRectSubPix_8u_C1R
( const uchar* src, int src_step, CvSize src_size,
  uchar* dst, int dst_step, CvSize win_size, CvPoint2D32f center );
CvStatus CV_STDCALL icvGetRectSubPix_8u32f_C1R
( const uchar* src, int src_step, CvSize src_size,
  float* dst, int dst_step, CvSize win_size, CvPoint2D32f center );
CvStatus CV_STDCALL icvGetRectSubPix_32f_C1R
( const float* src, int src_step, CvSize src_size,
  float* dst, int dst_step, CvSize win_size, CvPoint2D32f center );

CvStatus CV_STDCALL icvGetQuadrangleSubPix_8u_C1R
( const uchar* src, int src_step, CvSize src_size,
  uchar* dst, int dst_step, CvSize win_size, const float *matrix );
CvStatus CV_STDCALL icvGetQuadrangleSubPix_8u32f_C1R
( const uchar* src, int src_step, CvSize src_size,
  float* dst, int dst_step, CvSize win_size, const float *matrix );
CvStatus CV_STDCALL icvGetQuadrangleSubPix_32f_C1R
( const float* src, int src_step, CvSize src_size,
  float* dst, int dst_step, CvSize win_size, const float *matrix );

#include "_geom.h"

#endif /*__OPENCV_CV_INTERNAL_H_*/
<|endoftext|>