<commit_before>#pragma once

#include <string>
#include <vector>
#include <memory>

#include "acmacs-base/throw.hh"
#include "acmacs-base/range.hh"
#include "acmacs-base/timeit.hh"
#include "acmacs-chart-2/chart.hh"
#include "acmacs-draw/viewport.hh"
#include "acmacs-map-draw/point-style-draw.hh"
#include "acmacs-map-draw/map-elements.hh"
#include "acmacs-map-draw/labels.hh"

class Surface;

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

class DrawingOrder : public std::vector<size_t>
{
 public:
    DrawingOrder(acmacs::chart::Chart& aChart);
    inline DrawingOrder& operator=(const std::vector<size_t>& aSource) { std::vector<size_t>::operator=(aSource); return *this; }

    void raise(size_t aPointNo);
    void lower(size_t aPointNo);

}; // class DrawingOrder

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

class ChartDraw
{
 public:
    ChartDraw(acmacs::chart::Chart& aChart, size_t aProjectionNo);

    void prepare();
    void draw(Surface& aSurface) const;
    void draw(std::string aFilename, double aSize, report_time aTimer = report_time::No) const;
    const acmacs::Viewport& calculate_viewport(bool verbose = true);

    inline const std::vector<PointStyleDraw>& point_styles() const { return mPointStyles; }
    inline std::vector<acmacs::PointStyle> point_styles_base() const { std::vector<acmacs::PointStyle> ps{mPointStyles.begin(), mPointStyles.end()}; return ps; }
    inline auto& chart() { return mChart; }
    inline const auto& chart() const { return mChart; }
    inline auto projection_no() const { return mProjectionNo; }
    inline std::shared_ptr<acmacs::chart::Layout> layout() const { return chart().projection(projection_no())->layout(); }
    // inline auto& layout() { return chart().projection(projection_no()).layout(); }

      // for "found_in_previous" and "not_found_in_previous" select keys
    inline void previous_chart(acmacs::chart::Chart& aPreviousChart) { mPreviousChart = &aPreviousChart; }
    inline const auto& previous_chart() const { return mPreviousChart; }

    template <typename index_type> inline void modify(index_type aIndex, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
        {
            const auto index = static_cast<size_t>(aIndex);
            mPointStyles.at(index) = aStyle;
            switch (aPointDrawingOrder) {
              case PointDrawingOrder::Raise:
                  drawing_order().raise(index);
                  break;
              case PointDrawingOrder::Lower:
                  drawing_order().lower(index);
                  break;
              case PointDrawingOrder::NoChange:
                  break;
            }
        }

    template <typename index_type> inline void modify_serum(index_type aSerumNo, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
        {
            modify(static_cast<size_t>(aSerumNo) + number_of_antigens(), aStyle, aPointDrawingOrder);
        }

    template <typename IndexIterator> inline void modify(IndexIterator first, IndexIterator last, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
        {
            for (; first != last; ++first)
                modify(*first, aStyle, aPointDrawingOrder);
        }

    inline void modify(const acmacs::chart::Indexes& aIndexes, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
        {
            for (auto index: aIndexes)
                modify(index, aStyle, aPointDrawingOrder);
        }

    template <typename IndexIterator> inline void modify_sera(IndexIterator first, IndexIterator last, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
        {
            for (; first != last; ++first)
                modify_serum(*first, aStyle, aPointDrawingOrder);
        }

    inline void modify_sera(const acmacs::chart::Indexes& aIndexes, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
        {
            for (auto index: aIndexes)
                modify_serum(index, aStyle, aPointDrawingOrder);
        }

    void hide_all_except(const std::vector<size_t>& aNotHide);
    void mark_egg_antigens();
    void mark_reassortant_antigens();
    void mark_all_grey(Color aColor);
    void scale_points(double aPointScale, double aOulineScale);
    void modify_all_sera(const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange);

    inline void rotate(double aAngle)
        {
            if (!float_zero(aAngle))
                log("rotate radians:", aAngle, " degrees:", 180.0 * aAngle / M_PI, " ", aAngle > 0 ? "counter-" : "", "clockwise");
            mTransformation.rotate(aAngle);
        }

    inline void flip(double aX, double aY)
        {
            // std::cout << "INFO: flip " << aX << " " << aY << std::endl;
            log("flip ", aX, " ", aY);
            mTransformation.flip(aX, aY); // reflect about a line specified with vector [aX, aY]
        }
    inline const acmacs::Transformation& transformation() const { return mTransformation; }

    inline void viewport(double aX, double aY, double aSize) { mViewport.set(aX, aY, aSize); }
    inline void viewport(const acmacs::Viewport& aViewport) { mViewport = aViewport; }
    inline const acmacs::Viewport& viewport() const { return mViewport; }

    DrawingOrder& drawing_order() { return mDrawingOrder; }

    inline void background_color(Color aBackgroud) { DYNAMIC_CAST(map_elements::BackgroundBorderGrid&, (mMapElements["background-border-grid"])).background_color(aBackgroud); }
    inline void grid(Color aGridColor, double aGridLineWidth) { DYNAMIC_CAST(map_elements::BackgroundBorderGrid&, (mMapElements["background-border-grid"])).grid(aGridColor, aGridLineWidth); }
    inline void border(Color aBorderColor, double aBorderWidth) { DYNAMIC_CAST(map_elements::BackgroundBorderGrid&, (mMapElements["background-border-grid"])).border(aBorderColor, aBorderWidth); }
    inline void continent_map(const acmacs::Location& aOffset, Pixels aWidth) { DYNAMIC_CAST(map_elements::ContinentMap&, (mMapElements["continent-map"])).offset_width(aOffset, aWidth); }
    inline map_elements::LegendPointLabel& legend(const acmacs::Location& aOffset) { auto& legend = DYNAMIC_CAST(map_elements::LegendPointLabel&, (mMapElements["legend-point-label"])); legend.offset(aOffset); return legend; }
    inline map_elements::LegendPointLabel& legend() { return DYNAMIC_CAST(map_elements::LegendPointLabel&, (mMapElements["legend-point-label"])); }
    inline void remove_legend() { mMapElements.remove("legend-point-label"); }
    inline map_elements::Title& title(const acmacs::Location& aOffset) { auto& title = DYNAMIC_CAST(map_elements::Title&, (mMapElements["title"])); title.offset(aOffset); return title; }
    inline map_elements::Title& title() { return DYNAMIC_CAST(map_elements::Title&, (mMapElements["title"])); }
    inline map_elements::Labels& labels() { return mLabels; }
    inline map_elements::Label& add_label(size_t aIndex) { return mLabels.add(aIndex, mChart); }
    inline void remove_label(size_t aIndex) { return mLabels.remove(aIndex); }
    map_elements::SerumCircle& serum_circle(size_t aSerumNo, Scaled aRadius);
    map_elements::Line& line(const acmacs::Location& aBegin, const acmacs::Location& aEnd);
    map_elements::Arrow& arrow(const acmacs::Location& aBegin, const acmacs::Location& aEnd);
    map_elements::Point& point(const acmacs::Location& aCenter, Pixels aSize);
    map_elements::Rectangle& rectangle(const acmacs::Location& aCorner1, const acmacs::Location& aCorner2);
    map_elements::Circle& circle(const acmacs::Location& aCenter, Scaled aSize);
    void remove_serum_circles();

    inline const acmacs::chart::Layout& transformed_layout() const
        {
            if (!mTransformedLayout) {
                mTransformedLayout = std::unique_ptr<acmacs::chart::Layout>(mChart.projection(mProjectionNo)->layout()->transform(mTransformation));
            }
            return *mTransformedLayout;
        }

    size_t number_of_antigens() const;
    size_t number_of_sera() const;
    inline size_t number_of_points() const { return number_of_antigens() + number_of_sera(); }

    void save(std::string aFilename, std::string aProgramName);

 private:
    acmacs::chart::Chart& mChart;
    acmacs::chart::Chart* mPreviousChart = nullptr;
    size_t mProjectionNo;
    acmacs::Viewport mViewport;
    acmacs::Transformation mTransformation;
    std::vector<PointStyleDraw> mPointStyles;
    DrawingOrder mDrawingOrder;
    map_elements::Elements mMapElements;
    map_elements::Labels mLabels;
    mutable std::unique_ptr<acmacs::chart::Layout> mTransformedLayout;

}; // class ChartDraw

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<commit_msg>reset transformed layout on rotation/flipping<commit_after>#pragma once

#include <string>
#include <vector>
#include <memory>

#include "acmacs-base/throw.hh"
#include "acmacs-base/range.hh"
#include "acmacs-base/timeit.hh"
#include "acmacs-chart-2/chart.hh"
#include "acmacs-draw/viewport.hh"
#include "acmacs-map-draw/point-style-draw.hh"
#include "acmacs-map-draw/map-elements.hh"
#include "acmacs-map-draw/labels.hh"

class Surface;

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

class DrawingOrder : public std::vector<size_t>
{
 public:
    DrawingOrder(acmacs::chart::Chart& aChart);
    inline DrawingOrder& operator=(const std::vector<size_t>& aSource) { std::vector<size_t>::operator=(aSource); return *this; }

    void raise(size_t aPointNo);
    void lower(size_t aPointNo);

}; // class DrawingOrder

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

class ChartDraw
{
 public:
    ChartDraw(acmacs::chart::Chart& aChart, size_t aProjectionNo);

    void prepare();
    void draw(Surface& aSurface) const;
    void draw(std::string aFilename, double aSize, report_time aTimer = report_time::No) const;
    const acmacs::Viewport& calculate_viewport(bool verbose = true);

    inline const std::vector<PointStyleDraw>& point_styles() const { return mPointStyles; }
    inline std::vector<acmacs::PointStyle> point_styles_base() const { std::vector<acmacs::PointStyle> ps{mPointStyles.begin(), mPointStyles.end()}; return ps; }
    inline auto& chart() { return mChart; }
    inline const auto& chart() const { return mChart; }
    inline auto projection_no() const { return mProjectionNo; }
    inline std::shared_ptr<acmacs::chart::Layout> layout() const { return chart().projection(projection_no())->layout(); }
    // inline auto& layout() { return chart().projection(projection_no()).layout(); }

      // for "found_in_previous" and "not_found_in_previous" select keys
    inline void previous_chart(acmacs::chart::Chart& aPreviousChart) { mPreviousChart = &aPreviousChart; }
    inline const auto& previous_chart() const { return mPreviousChart; }

    template <typename index_type> inline void modify(index_type aIndex, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
        {
            const auto index = static_cast<size_t>(aIndex);
            mPointStyles.at(index) = aStyle;
            switch (aPointDrawingOrder) {
              case PointDrawingOrder::Raise:
                  drawing_order().raise(index);
                  break;
              case PointDrawingOrder::Lower:
                  drawing_order().lower(index);
                  break;
              case PointDrawingOrder::NoChange:
                  break;
            }
        }

    template <typename index_type> inline void modify_serum(index_type aSerumNo, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
        {
            modify(static_cast<size_t>(aSerumNo) + number_of_antigens(), aStyle, aPointDrawingOrder);
        }

    template <typename IndexIterator> inline void modify(IndexIterator first, IndexIterator last, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
        {
            for (; first != last; ++first)
                modify(*first, aStyle, aPointDrawingOrder);
        }

    inline void modify(const acmacs::chart::Indexes& aIndexes, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
        {
            for (auto index: aIndexes)
                modify(index, aStyle, aPointDrawingOrder);
        }

    template <typename IndexIterator> inline void modify_sera(IndexIterator first, IndexIterator last, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
        {
            for (; first != last; ++first)
                modify_serum(*first, aStyle, aPointDrawingOrder);
        }

    inline void modify_sera(const acmacs::chart::Indexes& aIndexes, const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange)
        {
            for (auto index: aIndexes)
                modify_serum(index, aStyle, aPointDrawingOrder);
        }

    void hide_all_except(const std::vector<size_t>& aNotHide);
    void mark_egg_antigens();
    void mark_reassortant_antigens();
    void mark_all_grey(Color aColor);
    void scale_points(double aPointScale, double aOulineScale);
    void modify_all_sera(const acmacs::PointStyle& aStyle, PointDrawingOrder aPointDrawingOrder = PointDrawingOrder::NoChange);

    inline void rotate(double aAngle)
        {
            if (!float_zero(aAngle))
                log("rotate radians:", aAngle, " degrees:", 180.0 * aAngle / M_PI, " ", aAngle > 0 ? "counter-" : "", "clockwise");
            mTransformation.rotate(aAngle);
            mTransformedLayout.reset();
        }

    inline void flip(double aX, double aY)
        {
            // std::cout << "INFO: flip " << aX << " " << aY << std::endl;
            log("flip ", aX, " ", aY);
            mTransformation.flip(aX, aY); // reflect about a line specified with vector [aX, aY]
            mTransformedLayout.reset();
        }
    inline const acmacs::Transformation& transformation() const { return mTransformation; }

    inline void viewport(double aX, double aY, double aSize) { mViewport.set(aX, aY, aSize); }
    inline void viewport(const acmacs::Viewport& aViewport) { mViewport = aViewport; }
    inline const acmacs::Viewport& viewport() const { return mViewport; }

    DrawingOrder& drawing_order() { return mDrawingOrder; }

    inline void background_color(Color aBackgroud) { DYNAMIC_CAST(map_elements::BackgroundBorderGrid&, (mMapElements["background-border-grid"])).background_color(aBackgroud); }
    inline void grid(Color aGridColor, double aGridLineWidth) { DYNAMIC_CAST(map_elements::BackgroundBorderGrid&, (mMapElements["background-border-grid"])).grid(aGridColor, aGridLineWidth); }
    inline void border(Color aBorderColor, double aBorderWidth) { DYNAMIC_CAST(map_elements::BackgroundBorderGrid&, (mMapElements["background-border-grid"])).border(aBorderColor, aBorderWidth); }
    inline void continent_map(const acmacs::Location& aOffset, Pixels aWidth) { DYNAMIC_CAST(map_elements::ContinentMap&, (mMapElements["continent-map"])).offset_width(aOffset, aWidth); }
    inline map_elements::LegendPointLabel& legend(const acmacs::Location& aOffset) { auto& legend = DYNAMIC_CAST(map_elements::LegendPointLabel&, (mMapElements["legend-point-label"])); legend.offset(aOffset); return legend; }
    inline map_elements::LegendPointLabel& legend() { return DYNAMIC_CAST(map_elements::LegendPointLabel&, (mMapElements["legend-point-label"])); }
    inline void remove_legend() { mMapElements.remove("legend-point-label"); }
    inline map_elements::Title& title(const acmacs::Location& aOffset) { auto& title = DYNAMIC_CAST(map_elements::Title&, (mMapElements["title"])); title.offset(aOffset); return title; }
    inline map_elements::Title& title() { return DYNAMIC_CAST(map_elements::Title&, (mMapElements["title"])); }
    inline map_elements::Labels& labels() { return mLabels; }
    inline map_elements::Label& add_label(size_t aIndex) { return mLabels.add(aIndex, mChart); }
    inline void remove_label(size_t aIndex) { return mLabels.remove(aIndex); }
    map_elements::SerumCircle& serum_circle(size_t aSerumNo, Scaled aRadius);
    map_elements::Line& line(const acmacs::Location& aBegin, const acmacs::Location& aEnd);
    map_elements::Arrow& arrow(const acmacs::Location& aBegin, const acmacs::Location& aEnd);
    map_elements::Point& point(const acmacs::Location& aCenter, Pixels aSize);
    map_elements::Rectangle& rectangle(const acmacs::Location& aCorner1, const acmacs::Location& aCorner2);
    map_elements::Circle& circle(const acmacs::Location& aCenter, Scaled aSize);
    void remove_serum_circles();

    inline const acmacs::chart::Layout& transformed_layout() const
        {
            if (!mTransformedLayout) {
                mTransformedLayout = std::unique_ptr<acmacs::chart::Layout>(mChart.projection(mProjectionNo)->layout()->transform(mTransformation));
            }
            return *mTransformedLayout;
        }

    size_t number_of_antigens() const;
    size_t number_of_sera() const;
    inline size_t number_of_points() const { return number_of_antigens() + number_of_sera(); }

    void save(std::string aFilename, std::string aProgramName);

 private:
    acmacs::chart::Chart& mChart;
    acmacs::chart::Chart* mPreviousChart = nullptr;
    size_t mProjectionNo;
    acmacs::Viewport mViewport;
    acmacs::Transformation mTransformation;
    std::vector<PointStyleDraw> mPointStyles;
    DrawingOrder mDrawingOrder;
    map_elements::Elements mMapElements;
    map_elements::Labels mLabels;
    mutable std::unique_ptr<acmacs::chart::Layout> mTransformedLayout;

}; // class ChartDraw

// ----------------------------------------------------------------------
/// Local Variables:
/// eval: (if (fboundp 'eu-rename-buffer) (eu-rename-buffer))
/// End:
<|endoftext|>


<commit_before>#include <algorithm>
#include <iterator>
#include <sstream>
#include <string>

#include <pybind11/numpy.h>
#include <pybind11/operators.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <gsl/gsl>

#include "xchainer/dtype.h"
#include "xchainer/error.h"
#include "xchainer/scalar.h"

namespace xchainer {
namespace {

namespace py = pybind11;  // standard convention

void InitXchainerModule(pybind11::module& m) {
    m.doc() = "xChainer";
    m.attr("__name__") = "xchainer";  // Show each member as "xchainer.*" instead of "xchainer.core.*"

    py::register_exception<XchainerError>(m, "XchainerError");
    py::register_exception<DtypeError>(m, "DtypeError");

    //
    // Types
    //

    {
        py::enum_<Dtype> dtype_type(m, "Dtype");
        for (Dtype dtype : GetAllDtypes()) {
            dtype_type.value(GetDtypeName(dtype), dtype);
        }
        dtype_type.export_values();
        dtype_type.def(py::init(&GetDtype));
        dtype_type.def_property_readonly("char", [](Dtype dtype) { return std::string(1, GetCharCode(dtype)); });
        dtype_type.def_property_readonly("itemsize", &GetElementSize);
        dtype_type.def_property_readonly("name", &GetDtypeName);
    }

    py::class_<Scalar>(m, "Scalar")
        .def(py::init<bool>())
        .def(py::init<int64_t>())
        .def(py::init<double>())
        .def(+py::self)
        .def(-py::self)
        .def("__bool__", &Scalar::UnwrapAndCast<bool>)
        .def("__int__", &Scalar::UnwrapAndCast<int64_t>)
        .def("__float__", &Scalar::UnwrapAndCast<double>)
        .def("__repr__", &Scalar::ToString)
        .def_property_readonly("dtype", &Scalar::dtype);
}

}  // namespace
}  // namespace xchainer

PYBIND11_MODULE(_core, m) { xchainer::InitXchainerModule(m); }
<commit_msg>Cleaner Scalar method bindings<commit_after>#include <algorithm>
#include <iterator>
#include <sstream>
#include <string>

#include <pybind11/numpy.h>
#include <pybind11/operators.h>
#include <pybind11/pybind11.h>
#include <pybind11/stl.h>
#include <gsl/gsl>

#include "xchainer/dtype.h"
#include "xchainer/error.h"
#include "xchainer/scalar.h"

namespace xchainer {
namespace {

namespace py = pybind11;  // standard convention

void InitXchainerModule(pybind11::module& m) {
    m.doc() = "xChainer";
    m.attr("__name__") = "xchainer";  // Show each member as "xchainer.*" instead of "xchainer.core.*"

    py::register_exception<XchainerError>(m, "XchainerError");
    py::register_exception<DtypeError>(m, "DtypeError");

    //
    // Types
    //

    {
        py::enum_<Dtype> dtype_type(m, "Dtype");
        for (Dtype dtype : GetAllDtypes()) {
            dtype_type.value(GetDtypeName(dtype), dtype);
        }
        dtype_type.export_values();
        dtype_type.def(py::init(&GetDtype));
        dtype_type.def_property_readonly("char", [](Dtype dtype) { return std::string(1, GetCharCode(dtype)); });
        dtype_type.def_property_readonly("itemsize", &GetElementSize);
        dtype_type.def_property_readonly("name", &GetDtypeName);
    }

    py::class_<Scalar>(m, "Scalar")
        .def(py::init<bool>())
        .def(py::init<int64_t>())
        .def(py::init<double>())
        .def(+py::self)
        .def(-py::self)
        .def("__bool__", &Scalar::operator bool)
        .def("__int__", &Scalar::operator int64_t)
        .def("__float__", &Scalar::operator double)
        .def("__repr__", &Scalar::ToString)
        .def_property_readonly("dtype", &Scalar::dtype);
}

}  // namespace
}  // namespace xchainer

PYBIND11_MODULE(_core, m) { xchainer::InitXchainerModule(m); }
<|endoftext|>


<commit_before>#include <QLabel>
#include <QScrollArea>
#include <QPixmap>
#include <QImage>
#include <QMouseEvent>
#include <QApplication>
#include <math.h>

#ifndef QT_NO_WHEELEVENT
#include <QWheelEvent>
#endif

#include <stdio.h>

#include "widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent)
{

}

Widget::~Widget()
{

}

bool Widget::showPicture() {
    imageLabel = new QLabel(this);
    imageLabel->setBackgroundRole(QPalette::Base);
    imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    imageLabel->setScaledContents(true);

    setWindowTitle(mFilename);
    //resize(500, 400);

    QImage image(mFilename);

    if(image.isNull()) {
        fprintf(stderr, "Can't load %s\n", mFilename.toLocal8Bit().data());
        return false;
    }

    imageLabel->setPixmap(QPixmap::fromImage(image));
    resize(imageLabel->pixmap()->size());
    imageLabel->resize(this->width(), this->height());
    imageLabel->move(0,0);
    return true;
}

void Widget::resizeEvent(QResizeEvent *e) {
    this->QWidget::resizeEvent(e);

    imageLabel->resize(this->width(), this->height());
    imageLabel->move(0,0);
}

void Widget::mousePressEvent(QMouseEvent *e) {
    if(e->modifiers() != 0) {
        if(e->modifiers() == Qt::ControlModifier && e->button() == Qt::LeftButton) {
            this->rememberedPointForPanning = e->pos();
        }
        return;
    }
    switch(e->button()) {
        case Qt::RightButton:
            QApplication::exit(0);
            break;
        case Qt::LeftButton:
            this->printCoordinates(this->coordWindowToPicture( e->pos()));
            break;
        case Qt::MiddleButton:
            this->rememberedPointForPanning = e->pos();
            break;
    }
}

void Widget::mouseMoveEvent(QMouseEvent *e) {
    int buttonSet = e->buttons().operator int();
    int modifierSet = e->modifiers().operator int();

    if(buttonSet == Qt::MiddleButton ||
            (modifierSet == Qt::ControlModifier && buttonSet == Qt::LeftButton)) {
        imageLabel->move(imageLabel->pos() + e->pos() - this->rememberedPointForPanning);
        this->rememberedPointForPanning = e->pos();
    }
}

QPoint Widget::coordWindowToPicture(QPoint in) {
    int pictureWidth = imageLabel->pixmap()->size().width();
    int pictureHeight = imageLabel->pixmap()->size().height();
    int windowWidth = imageLabel->width();
    int windowHeight = imageLabel->height();

    int xx = (in.x() - imageLabel->x()) * pictureWidth  / windowWidth;
    int yy = (in.y() - imageLabel->y()) * pictureHeight / windowHeight;

    return QPoint(xx, yy);
}

QPoint Widget::coordPictureToWindow(QPoint in) {
    int pictureWidth = imageLabel->pixmap()->size().width();
    int pictureHeight = imageLabel->pixmap()->size().height();
    int windowWidth = imageLabel->width();
    int windowHeight = imageLabel->height();

    int xx = in.x()  * windowWidth / pictureWidth  + imageLabel->x();
    int yy = in.y() * windowHeight / pictureHeight +  imageLabel->y();

    return QPoint(xx, yy);
}

void Widget::printCoordinates(QPoint coords) {
    fprintf(stdout, "%d,%d\n", coords.x(), coords.y());
    fflush(stdout);
}

#ifndef QT_NO_WHEELEVENT
void Widget::wheelEvent(QWheelEvent * e) {
    int d = e->delta();

    double q = exp(0.001*d);

    //fprintf(stderr, "D: %d %g\n", d, q);

    QPoint pictCoords = this->coordWindowToPicture( e->pos());

    imageLabel->resize(imageLabel->size()*q);

    QPoint windowCoords = this->coordPictureToWindow(pictCoords) - imageLabel->pos();

    imageLabel->move(e->pos() - windowCoords );
}
#endif
<commit_msg>Make it buildable again<commit_after>#include <QLabel>
#include <QScrollArea>
#include <QPixmap>
#include <QImage>
#include <QMouseEvent>
#include <QApplication>
#include <math.h>

#ifndef QT_NO_WHEELEVENT
#include <QWheelEvent>
#endif

#include <stdio.h>

#include "widget.h"

Widget::Widget(QWidget *parent) :
    QWidget(parent)
{

}

Widget::~Widget()
{

}

bool Widget::showPicture() {
    imageLabel = new QLabel(this);
    imageLabel->setBackgroundRole(QPalette::Base);
    imageLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Ignored);
    imageLabel->setScaledContents(true);

    setWindowTitle(mFilename);
    //resize(500, 400);

    QImage image(mFilename);

    if(image.isNull()) {
        fprintf(stderr, "Can't load %s\n", mFilename.toLocal8Bit().data());
        return false;
    }

    imageLabel->setPixmap(QPixmap::fromImage(image));
    resize(imageLabel->pixmap()->size());
    imageLabel->resize(this->width(), this->height());
    imageLabel->move(0,0);
    return true;
}

void Widget::resizeEvent(QResizeEvent *e) {
    this->QWidget::resizeEvent(e);

    imageLabel->resize(this->width(), this->height());
    imageLabel->move(0,0);
}

void Widget::mousePressEvent(QMouseEvent *e) {
    if(e->modifiers() != 0) {
        if(e->modifiers() == Qt::ControlModifier && e->button() == Qt::LeftButton) {
            this->rememberedPointForPanning = e->pos();
        }
        return;
    }
    switch(e->button()) {
        case Qt::RightButton:
            QApplication::exit(0);
            break;
        case Qt::LeftButton:
            this->printCoordinates(this->coordWindowToPicture( e->pos()));
            break;
        case Qt::MiddleButton:
            this->rememberedPointForPanning = e->pos();
            break;
    }
}

void Widget::mouseMoveEvent(QMouseEvent *e) {
    Qt::MouseButtons buttonSet = e->buttons();
    Qt::KeyboardModifiers modifierSet = e->modifiers();

    if(buttonSet == Qt::MiddleButton ||
            (modifierSet == Qt::ControlModifier && buttonSet == Qt::LeftButton)) {
        imageLabel->move(imageLabel->pos() + e->pos() - this->rememberedPointForPanning);
        this->rememberedPointForPanning = e->pos();
    }
}

QPoint Widget::coordWindowToPicture(QPoint in) {
    int pictureWidth = imageLabel->pixmap()->size().width();
    int pictureHeight = imageLabel->pixmap()->size().height();
    int windowWidth = imageLabel->width();
    int windowHeight = imageLabel->height();

    int xx = (in.x() - imageLabel->x()) * pictureWidth  / windowWidth;
    int yy = (in.y() - imageLabel->y()) * pictureHeight / windowHeight;

    return QPoint(xx, yy);
}

QPoint Widget::coordPictureToWindow(QPoint in) {
    int pictureWidth = imageLabel->pixmap()->size().width();
    int pictureHeight = imageLabel->pixmap()->size().height();
    int windowWidth = imageLabel->width();
    int windowHeight = imageLabel->height();

    int xx = in.x()  * windowWidth / pictureWidth  + imageLabel->x();
    int yy = in.y() * windowHeight / pictureHeight +  imageLabel->y();

    return QPoint(xx, yy);
}

void Widget::printCoordinates(QPoint coords) {
    fprintf(stdout, "%d,%d\n", coords.x(), coords.y());
    fflush(stdout);
}

#ifndef QT_NO_WHEELEVENT
void Widget::wheelEvent(QWheelEvent * e) {
    int d = e->delta();

    double q = exp(0.001*d);

    //fprintf(stderr, "D: %d %g\n", d, q);

    QPoint pictCoords = this->coordWindowToPicture( e->pos());

    imageLabel->resize(imageLabel->size()*q);

    QPoint windowCoords = this->coordPictureToWindow(pictCoords) - imageLabel->pos();

    imageLabel->move(e->pos() - windowCoords );
}
#endif
<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *            (C) 2019  Eddie Hung    <eddie@fpgeh.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/yosys.h"
#include "kernel/sigtools.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

// for peepopt_pm
bool did_something;

#include "passes/pmgen/xilinx_srl_pm.h"
#include "passes/pmgen/ice40_dsp_pm.h"
#include "passes/pmgen/peepopt_pm.h"

void run_fixed(xilinx_srl_pm &pm)
{
	auto &st = pm.st_fixed;
	auto &ud = pm.ud_fixed;
	auto param_def = [&ud](Cell *cell, IdString param) {
		auto def = ud.default_params.at(std::make_pair(cell->type,param));
		return cell->parameters.at(param, def);
	};

	log("Found fixed chain of length %d (%s):\n", GetSize(ud.longest_chain), log_id(st.first->type));

	auto last_cell = ud.longest_chain.back();

	SigSpec initval;
	for (auto cell : ud.longest_chain) {
		log_debug("    %s\n", log_id(cell));
		if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_))) {
			SigBit Q = cell->getPort(ID(Q));
			log_assert(Q.wire);
			auto it = Q.wire->attributes.find(ID(init));
			if (it != Q.wire->attributes.end()) {
				initval.append(it->second[Q.offset]);
			}
			else
				initval.append(State::Sx);
		}
		else if (cell->type.in(ID(FDRE), ID(FDRE_1)))
			initval.append(param_def(cell, ID(INIT)));
		else
			log_abort();
		if (cell != last_cell)
			pm.autoremove(cell);
	}

	Cell *c = last_cell;
	SigBit Q = st.first->getPort(ID(Q));
	c->setPort(ID(Q), Q);

	if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID(FDRE), ID(FDRE_1))) {
		c->parameters.clear();
		c->setParam(ID(DEPTH), GetSize(ud.longest_chain));
		c->setParam(ID(INIT), initval.as_const());
		if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
			c->setParam(ID(CLKPOL), 1);
		else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_), ID(FDRE_1)))
			c->setParam(ID(CLKPOL), 0);
		else if (c->type.in(ID(FDRE)))
			c->setParam(ID(CLKPOL), param_def(c, ID(IS_C_INVERTED)).as_bool() ? 0 : 1);
		else
			log_abort();
		if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_)))
			c->setParam(ID(ENPOL), 1);
		else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_)))
			c->setParam(ID(ENPOL), 0);
		else
			c->setParam(ID(ENPOL), 2);
		if (c->type.in(ID($_DFF_N_), ID($_DFF_P_)))
			c->setPort(ID(E), State::S1);
		c->setPort(ID(L), GetSize(ud.longest_chain)-1);
		c->type = ID($__XILINX_SHREG_);
	}
	else
		log_abort();

	log("    -> %s (%s)\n", log_id(c), log_id(c->type));
}

void run_variable(xilinx_srl_pm &pm)
{
	auto &st = pm.st_variable;
	auto &ud = pm.ud_variable;

	log("Found variable chain of length %d (%s):\n", GetSize(ud.chain), log_id(st.first->type));

	auto last_cell = ud.chain.back().first;
	auto last_slice = ud.chain.back().second;

	SigSpec initval;
	for (const auto &i : ud.chain) {
		auto cell = i.first;
		auto slice = i.second;
		log_debug("    %s\n", log_id(cell));
		if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID($dff), ID($dffe))) {
			SigBit Q = cell->getPort(ID(Q))[slice];
			log_assert(Q.wire);
			auto it = Q.wire->attributes.find(ID(init));
			if (it != Q.wire->attributes.end()) {
				initval.append(it->second[Q.offset]);
			}
			else
				initval.append(State::Sx);
		}
		else
			log_abort();
		if (cell != last_cell)
			cell->connections_.at(ID(Q))[slice] = pm.module->addWire(NEW_ID);
	}
	pm.autoremove(st.shiftx);

	Cell *c = last_cell;
	SigBit Q = st.first->getPort(ID(Q))[last_slice];
	c->setPort(ID(Q), Q);

	if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID($dff), ID($dffe))) {
		Const clkpol, enpol;
		if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
			clkpol = 1;
		else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_)))
			clkpol = 0;
		else if (c->type.in(ID($dff), ID($dffe))) {
			clkpol = c->getParam(ID(CLK_POLARITY));
			c->setPort(ID(C), c->getPort(ID(CLK)));
			c->unsetPort(ID(CLK));
		}
		else
			log_abort();
		if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_)))
			enpol = 1;
		else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_)))
			enpol = 0;
		else if (c->type.in(ID($dffe))) {
			enpol = c->getParam(ID(EN_POLARITY));
			c->setPort(ID(E), c->getPort(ID(EN)));
			c->unsetPort(ID(EN));
		}
		else
			enpol = 2;
		c->parameters.clear();
		c->setParam(ID(DEPTH), GetSize(ud.chain));
		c->setParam(ID(INIT), initval.as_const());
		c->setParam(ID(CLKPOL), clkpol);
		c->setParam(ID(ENPOL), enpol);
		if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($dff)))
			c->setPort(ID(E), State::S1);
		c->setPort(ID(L), st.shiftx->getPort(ID(B)));
		c->setPort(ID(Q), st.shiftx->getPort(ID(Y)));
		c->type = ID($__XILINX_SHREG_);
	}
	else
		log_abort();

	log("    -> %s (%s)\n", log_id(c), log_id(c->type));

}

struct XilinxSrlPass : public Pass {
	XilinxSrlPass() : Pass("xilinx_srl", "Xilinx shift register extraction") { }
	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    xilinx_srl [options] [selection]\n");
		log("\n");
		log("This pass converts chains of built-in flops ($_DFF_[NP]_, $_DFFE_*) as well as\n");
		log("Xilinx flops (FDRE, FDRE_1) into a $__XILINX_SHREG cell. Chains must be of the\n");
		log("same type, clock, clock polarity, enable, enable polarity (when relevant).\n");
		log("Flops with resets cannot be mapped to Xilinx devices and will not be inferred.");
		log("\n");
		log("    -minlen N\n");
		log("        min length of shift register (default = 3)\n");
		log("\n");
		log("    -fixed\n");
		log("        infer fixed-length shift registers.\n");
		log("\n");
		log("    -variable\n");
		log("        infer variable-length shift registers (i.e. fixed-length shifts where\n");
		log("        each element also fans-out to a $shiftx cell.\n");
		log("\n");
	}

	void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		log_header(design, "Executing XILINX_SRL pass (Xilinx shift register extraction).\n");

		bool fixed = false;
		bool variable = false;
		int minlen = 3;

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			if (args[argidx] == "-minlen" && argidx+1 < args.size()) {
				minlen = atoi(args[++argidx].c_str());
				continue;
			}
			if (args[argidx] == "-fixed") {
				fixed = true;
				continue;
			}
			if (args[argidx] == "-variable") {
				variable = true;
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		if (!fixed && !variable)
			log_cmd_error("'-fixed' and/or '-variable' must be specified.\n");

		for (auto module : design->selected_modules()) {
			auto pm = xilinx_srl_pm(module, module->selected_cells());
			pm.ud_fixed.minlen = minlen;
			pm.ud_variable.minlen = minlen;

			if (fixed) {
				// TODO: How to get these automatically?
				pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(INIT))] = State::S0;
				pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_C_INVERTED))] = State::S0;
				pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_D_INVERTED))] = State::S0;
				pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_R_INVERTED))] = State::S0;
				pm.run_fixed(run_fixed);
			}
			if (variable)
				pm.run_variable(run_variable);
		}
	}
} XilinxSrlPass;

PRIVATE_NAMESPACE_END
<commit_msg>Remove (* init *) entry when consumed into SRL<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *            (C) 2019  Eddie Hung    <eddie@fpgeh.com>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/yosys.h"
#include "kernel/sigtools.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

// for peepopt_pm
bool did_something;

#include "passes/pmgen/xilinx_srl_pm.h"
#include "passes/pmgen/ice40_dsp_pm.h"
#include "passes/pmgen/peepopt_pm.h"

void run_fixed(xilinx_srl_pm &pm)
{
	auto &st = pm.st_fixed;
	auto &ud = pm.ud_fixed;
	auto param_def = [&ud](Cell *cell, IdString param) {
		auto def = ud.default_params.at(std::make_pair(cell->type,param));
		return cell->parameters.at(param, def);
	};

	log("Found fixed chain of length %d (%s):\n", GetSize(ud.longest_chain), log_id(st.first->type));

	auto last_cell = ud.longest_chain.back();

	SigSpec initval;
	for (auto cell : ud.longest_chain) {
		log_debug("    %s\n", log_id(cell));
		if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_))) {
			SigBit Q = cell->getPort(ID(Q));
			log_assert(Q.wire);
			auto it = Q.wire->attributes.find(ID(init));
			if (it != Q.wire->attributes.end()) {
				auto &i = it->second[Q.offset];
				initval.append(i);
				i = State::Sx;
			}
			else
				initval.append(State::Sx);
		}
		else if (cell->type.in(ID(FDRE), ID(FDRE_1)))
			initval.append(param_def(cell, ID(INIT)));
		else
			log_abort();
		if (cell != last_cell)
			pm.autoremove(cell);
	}

	Cell *c = last_cell;
	SigBit Q = st.first->getPort(ID(Q));
	c->setPort(ID(Q), Q);

	if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID(FDRE), ID(FDRE_1))) {
		c->parameters.clear();
		c->setParam(ID(DEPTH), GetSize(ud.longest_chain));
		c->setParam(ID(INIT), initval.as_const());
		if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
			c->setParam(ID(CLKPOL), 1);
		else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_), ID(FDRE_1)))
			c->setParam(ID(CLKPOL), 0);
		else if (c->type.in(ID(FDRE)))
			c->setParam(ID(CLKPOL), param_def(c, ID(IS_C_INVERTED)).as_bool() ? 0 : 1);
		else
			log_abort();
		if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_)))
			c->setParam(ID(ENPOL), 1);
		else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_)))
			c->setParam(ID(ENPOL), 0);
		else
			c->setParam(ID(ENPOL), 2);
		if (c->type.in(ID($_DFF_N_), ID($_DFF_P_)))
			c->setPort(ID(E), State::S1);
		c->setPort(ID(L), GetSize(ud.longest_chain)-1);
		c->type = ID($__XILINX_SHREG_);
	}
	else
		log_abort();

	log("    -> %s (%s)\n", log_id(c), log_id(c->type));
}

void run_variable(xilinx_srl_pm &pm)
{
	auto &st = pm.st_variable;
	auto &ud = pm.ud_variable;

	log("Found variable chain of length %d (%s):\n", GetSize(ud.chain), log_id(st.first->type));

	auto last_cell = ud.chain.back().first;
	auto last_slice = ud.chain.back().second;

	SigSpec initval;
	for (const auto &i : ud.chain) {
		auto cell = i.first;
		auto slice = i.second;
		log_debug("    %s\n", log_id(cell));
		if (cell->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID($dff), ID($dffe))) {
			SigBit Q = cell->getPort(ID(Q))[slice];
			log_assert(Q.wire);
			auto it = Q.wire->attributes.find(ID(init));
			if (it != Q.wire->attributes.end()) {
				auto &i = it->second[Q.offset];
				initval.append(i);
				i = State::Sx;
			}
			else
				initval.append(State::Sx);
		}
		else
			log_abort();
		if (cell != last_cell)
			cell->connections_.at(ID(Q))[slice] = pm.module->addWire(NEW_ID);
	}
	pm.autoremove(st.shiftx);

	Cell *c = last_cell;
	SigBit Q = st.first->getPort(ID(Q))[last_slice];
	c->setPort(ID(Q), Q);

	if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($_DFFE_NN_), ID($_DFFE_NP_), ID($_DFFE_PN_), ID($_DFFE_PP_), ID($dff), ID($dffe))) {
		Const clkpol, enpol;
		if (c->type.in(ID($_DFF_P_), ID($_DFFE_PN_), ID($_DFFE_PP_)))
			clkpol = 1;
		else if (c->type.in(ID($_DFF_N_), ID($DFFE_NN_), ID($_DFFE_NP_)))
			clkpol = 0;
		else if (c->type.in(ID($dff), ID($dffe))) {
			clkpol = c->getParam(ID(CLK_POLARITY));
			c->setPort(ID(C), c->getPort(ID(CLK)));
			c->unsetPort(ID(CLK));
		}
		else
			log_abort();
		if (c->type.in(ID($_DFFE_NP_), ID($_DFFE_PP_)))
			enpol = 1;
		else if (c->type.in(ID($_DFFE_NN_), ID($_DFFE_PN_)))
			enpol = 0;
		else if (c->type.in(ID($dffe))) {
			enpol = c->getParam(ID(EN_POLARITY));
			c->setPort(ID(E), c->getPort(ID(EN)));
			c->unsetPort(ID(EN));
		}
		else
			enpol = 2;
		c->parameters.clear();
		c->setParam(ID(DEPTH), GetSize(ud.chain));
		c->setParam(ID(INIT), initval.as_const());
		c->setParam(ID(CLKPOL), clkpol);
		c->setParam(ID(ENPOL), enpol);
		if (c->type.in(ID($_DFF_N_), ID($_DFF_P_), ID($dff)))
			c->setPort(ID(E), State::S1);
		c->setPort(ID(L), st.shiftx->getPort(ID(B)));
		c->setPort(ID(Q), st.shiftx->getPort(ID(Y)));
		c->type = ID($__XILINX_SHREG_);
	}
	else
		log_abort();

	log("    -> %s (%s)\n", log_id(c), log_id(c->type));

}

struct XilinxSrlPass : public Pass {
	XilinxSrlPass() : Pass("xilinx_srl", "Xilinx shift register extraction") { }
	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    xilinx_srl [options] [selection]\n");
		log("\n");
		log("This pass converts chains of built-in flops ($_DFF_[NP]_, $_DFFE_*) as well as\n");
		log("Xilinx flops (FDRE, FDRE_1) into a $__XILINX_SHREG cell. Chains must be of the\n");
		log("same type, clock, clock polarity, enable, enable polarity (when relevant).\n");
		log("Flops with resets cannot be mapped to Xilinx devices and will not be inferred.");
		log("\n");
		log("    -minlen N\n");
		log("        min length of shift register (default = 3)\n");
		log("\n");
		log("    -fixed\n");
		log("        infer fixed-length shift registers.\n");
		log("\n");
		log("    -variable\n");
		log("        infer variable-length shift registers (i.e. fixed-length shifts where\n");
		log("        each element also fans-out to a $shiftx cell.\n");
		log("\n");
	}

	void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		log_header(design, "Executing XILINX_SRL pass (Xilinx shift register extraction).\n");

		bool fixed = false;
		bool variable = false;
		int minlen = 3;

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			if (args[argidx] == "-minlen" && argidx+1 < args.size()) {
				minlen = atoi(args[++argidx].c_str());
				continue;
			}
			if (args[argidx] == "-fixed") {
				fixed = true;
				continue;
			}
			if (args[argidx] == "-variable") {
				variable = true;
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		if (!fixed && !variable)
			log_cmd_error("'-fixed' and/or '-variable' must be specified.\n");

		for (auto module : design->selected_modules()) {
			auto pm = xilinx_srl_pm(module, module->selected_cells());
			pm.ud_fixed.minlen = minlen;
			pm.ud_variable.minlen = minlen;

			if (fixed) {
				// TODO: How to get these automatically?
				pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(INIT))] = State::S0;
				pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_C_INVERTED))] = State::S0;
				pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_D_INVERTED))] = State::S0;
				pm.ud_fixed.default_params[std::make_pair(ID(FDRE),ID(IS_R_INVERTED))] = State::S0;
				pm.run_fixed(run_fixed);
			}
			if (variable)
				pm.run_variable(run_variable);
		}
	}
} XilinxSrlPass;

PRIVATE_NAMESPACE_END
<|endoftext|>


<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/register.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

void split_portname_pair(std::string &port1, std::string &port2)
{
	size_t pos = port1.find_first_of(':');
	if (pos != std::string::npos) {
		port2 = port1.substr(pos+1);
		port1 = port1.substr(0, pos);
	}
}

struct IopadmapPass : public Pass {
	IopadmapPass() : Pass("iopadmap", "technology mapping of i/o pads (or buffers)") { }
	virtual void help()
	{
		log("\n");
		log("    iopadmap [options] [selection]\n");
		log("\n");
		log("Map module inputs/outputs to PAD cells from a library. This pass\n");
		log("can only map to very simple PAD cells. Use 'techmap' to further map\n");
		log("the resulting cells to more sophisticated PAD cells.\n");
		log("\n");
		log("    -inpad <celltype> <portname>[:<portname>]\n");
		log("        Map module input ports to the given cell type with\n");
		log("        the given port name. if a 2nd portname is given, the\n");
		log("        signal is passed through the pad call, using the 2nd\n");
		log("        portname as output.\n");
		log("\n");
		log("    -outpad <celltype> <portname>[:<portname>]\n");
		log("    -inoutpad <celltype> <portname>[:<portname>]\n");
		log("        Similar to -inpad, but for output and inout ports.\n");
		log("\n");
		log("    -widthparam <param_name>\n");
		log("        Use the specified parameter name to set the port width.\n");
		log("\n");
		log("    -nameparam <param_name>\n");
		log("        Use the specified parameter to set the port name.\n");
		log("\n");
		log("    -bits\n");
		log("        create individual bit-wide buffers even for ports that\n");
		log("        are wider. (the default behavior is to create word-wide\n");
		log("        buffers using -widthparam to set the word size on the cell.)\n");
		log("\n");
	}
	virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
	{
		log_header("Executing IOPADMAP pass (mapping inputs/outputs to IO-PAD cells).\n");

		std::string inpad_celltype, inpad_portname, inpad_portname2;
		std::string outpad_celltype, outpad_portname, outpad_portname2;
		std::string inoutpad_celltype, inoutpad_portname, inoutpad_portname2;
		std::string widthparam, nameparam;
		bool flag_bits = false;

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			std::string arg = args[argidx];
			if (arg == "-inpad" && argidx+2 < args.size()) {
				inpad_celltype = args[++argidx];
				inpad_portname = args[++argidx];
				split_portname_pair(inpad_portname, inpad_portname2);
				continue;
			}
			if (arg == "-outpad" && argidx+2 < args.size()) {
				outpad_celltype = args[++argidx];
				outpad_portname = args[++argidx];
				split_portname_pair(outpad_portname, outpad_portname2);
				continue;
			}
			if (arg == "-inoutpad" && argidx+2 < args.size()) {
				inoutpad_celltype = args[++argidx];
				inoutpad_portname = args[++argidx];
				split_portname_pair(inoutpad_portname, inoutpad_portname2);
				continue;
			}
			if (arg == "-widthparam" && argidx+1 < args.size()) {
				widthparam = args[++argidx];
				continue;
			}
			if (arg == "-nameparam" && argidx+1 < args.size()) {
				nameparam = args[++argidx];
				continue;
			}
			if (arg == "-bits") {
				flag_bits = true;
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		for (auto module : design->selected_modules())
		{
			for (auto wire : module->selected_wires())
			{
				if (!wire->port_id)
					continue;

				std::string celltype, portname, portname2;

				if (wire->port_input && !wire->port_output) {
					if (inpad_celltype.empty()) {
						log("Don't map input port %s.%s: Missing option -inpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
						continue;
					}
					celltype = inpad_celltype;
					portname = inpad_portname;
					portname2 = inpad_portname2;
				} else
				if (!wire->port_input && wire->port_output) {
					if (outpad_celltype.empty()) {
						log("Don't map output port %s.%s: Missing option -outpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
						continue;
					}
					celltype = outpad_celltype;
					portname = outpad_portname;
					portname2 = outpad_portname2;
				} else
				if (wire->port_input && wire->port_output) {
					if (inoutpad_celltype.empty()) {
						log("Don't map inout port %s.%s: Missing option -inoutpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
						continue;
					}
					celltype = inoutpad_celltype;
					portname = inoutpad_portname;
					portname2 = inoutpad_portname2;
				} else
					log_abort();

				if (!flag_bits && wire->width != 1 && widthparam.empty()) {
					log("Don't map multi-bit port %s.%s: Missing option -widthparam or -bits.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
					continue;
				}

				log("Mapping port %s.%s using %s.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name), celltype.c_str());

				RTLIL::Wire *new_wire = NULL;
				if (!portname2.empty()) {
					new_wire = module->addWire(NEW_ID, wire);
					module->swap_names(new_wire, wire);
				}

				if (flag_bits)
				{
					for (int i = 0; i < wire->width; i++)
					{
						RTLIL::Cell *cell = module->addCell(NEW_ID, RTLIL::escape_id(celltype));
						cell->setPort(RTLIL::escape_id(portname), RTLIL::SigSpec(wire, i));
						if (!portname2.empty())
							cell->setPort(RTLIL::escape_id(portname2), RTLIL::SigSpec(new_wire, i));
						if (!widthparam.empty())
							cell->parameters[RTLIL::escape_id(widthparam)] = RTLIL::Const(1);
						if (!nameparam.empty())
							cell->parameters[RTLIL::escape_id(nameparam)] = RTLIL::Const(stringf("%s[%d]", RTLIL::id2cstr(wire->name), i));
						cell->attributes["\\keep"] = RTLIL::Const(1);
					}
				}
				else
				{
					RTLIL::Cell *cell = module->addCell(NEW_ID, RTLIL::escape_id(celltype));
					cell->setPort(RTLIL::escape_id(portname), RTLIL::SigSpec(wire));
					if (!portname2.empty())
						cell->setPort(RTLIL::escape_id(portname2), RTLIL::SigSpec(new_wire));
					if (!widthparam.empty())
						cell->parameters[RTLIL::escape_id(widthparam)] = RTLIL::Const(wire->width);
					if (!nameparam.empty())
						cell->parameters[RTLIL::escape_id(nameparam)] = RTLIL::Const(RTLIL::id2cstr(wire->name));
					cell->attributes["\\keep"] = RTLIL::Const(1);
				}

				wire->port_id = 0;
				wire->port_input = false;
				wire->port_output = false;
			}

			module->fixup_ports();
		}
	}
} IopadmapPass;

PRIVATE_NAMESPACE_END
<commit_msg>Fixed iopadmap help message<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/register.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

void split_portname_pair(std::string &port1, std::string &port2)
{
	size_t pos = port1.find_first_of(':');
	if (pos != std::string::npos) {
		port2 = port1.substr(pos+1);
		port1 = port1.substr(0, pos);
	}
}

struct IopadmapPass : public Pass {
	IopadmapPass() : Pass("iopadmap", "technology mapping of i/o pads (or buffers)") { }
	virtual void help()
	{
		log("\n");
		log("    iopadmap [options] [selection]\n");
		log("\n");
		log("Map module inputs/outputs to PAD cells from a library. This pass\n");
		log("can only map to very simple PAD cells. Use 'techmap' to further map\n");
		log("the resulting cells to more sophisticated PAD cells.\n");
		log("\n");
		log("    -inpad <celltype> <portname>[:<portname>]\n");
		log("        Map module input ports to the given cell type with the\n");
		log("        given output port name. if a 2nd portname is given, the\n");
		log("        signal is passed through the pad call, using the 2nd\n");
		log("        portname as input.\n");
		log("\n");
		log("    -outpad <celltype> <portname>[:<portname>]\n");
		log("    -inoutpad <celltype> <portname>[:<portname>]\n");
		log("        Similar to -inpad, but for output and inout ports.\n");
		log("\n");
		log("    -widthparam <param_name>\n");
		log("        Use the specified parameter name to set the port width.\n");
		log("\n");
		log("    -nameparam <param_name>\n");
		log("        Use the specified parameter to set the port name.\n");
		log("\n");
		log("    -bits\n");
		log("        create individual bit-wide buffers even for ports that\n");
		log("        are wider. (the default behavior is to create word-wide\n");
		log("        buffers using -widthparam to set the word size on the cell.)\n");
		log("\n");
	}
	virtual void execute(std::vector<std::string> args, RTLIL::Design *design)
	{
		log_header("Executing IOPADMAP pass (mapping inputs/outputs to IO-PAD cells).\n");

		std::string inpad_celltype, inpad_portname, inpad_portname2;
		std::string outpad_celltype, outpad_portname, outpad_portname2;
		std::string inoutpad_celltype, inoutpad_portname, inoutpad_portname2;
		std::string widthparam, nameparam;
		bool flag_bits = false;

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			std::string arg = args[argidx];
			if (arg == "-inpad" && argidx+2 < args.size()) {
				inpad_celltype = args[++argidx];
				inpad_portname = args[++argidx];
				split_portname_pair(inpad_portname, inpad_portname2);
				continue;
			}
			if (arg == "-outpad" && argidx+2 < args.size()) {
				outpad_celltype = args[++argidx];
				outpad_portname = args[++argidx];
				split_portname_pair(outpad_portname, outpad_portname2);
				continue;
			}
			if (arg == "-inoutpad" && argidx+2 < args.size()) {
				inoutpad_celltype = args[++argidx];
				inoutpad_portname = args[++argidx];
				split_portname_pair(inoutpad_portname, inoutpad_portname2);
				continue;
			}
			if (arg == "-widthparam" && argidx+1 < args.size()) {
				widthparam = args[++argidx];
				continue;
			}
			if (arg == "-nameparam" && argidx+1 < args.size()) {
				nameparam = args[++argidx];
				continue;
			}
			if (arg == "-bits") {
				flag_bits = true;
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		for (auto module : design->selected_modules())
		{
			for (auto wire : module->selected_wires())
			{
				if (!wire->port_id)
					continue;

				std::string celltype, portname, portname2;

				if (wire->port_input && !wire->port_output) {
					if (inpad_celltype.empty()) {
						log("Don't map input port %s.%s: Missing option -inpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
						continue;
					}
					celltype = inpad_celltype;
					portname = inpad_portname;
					portname2 = inpad_portname2;
				} else
				if (!wire->port_input && wire->port_output) {
					if (outpad_celltype.empty()) {
						log("Don't map output port %s.%s: Missing option -outpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
						continue;
					}
					celltype = outpad_celltype;
					portname = outpad_portname;
					portname2 = outpad_portname2;
				} else
				if (wire->port_input && wire->port_output) {
					if (inoutpad_celltype.empty()) {
						log("Don't map inout port %s.%s: Missing option -inoutpad.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
						continue;
					}
					celltype = inoutpad_celltype;
					portname = inoutpad_portname;
					portname2 = inoutpad_portname2;
				} else
					log_abort();

				if (!flag_bits && wire->width != 1 && widthparam.empty()) {
					log("Don't map multi-bit port %s.%s: Missing option -widthparam or -bits.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name));
					continue;
				}

				log("Mapping port %s.%s using %s.\n", RTLIL::id2cstr(module->name), RTLIL::id2cstr(wire->name), celltype.c_str());

				RTLIL::Wire *new_wire = NULL;
				if (!portname2.empty()) {
					new_wire = module->addWire(NEW_ID, wire);
					module->swap_names(new_wire, wire);
				}

				if (flag_bits)
				{
					for (int i = 0; i < wire->width; i++)
					{
						RTLIL::Cell *cell = module->addCell(NEW_ID, RTLIL::escape_id(celltype));
						cell->setPort(RTLIL::escape_id(portname), RTLIL::SigSpec(wire, i));
						if (!portname2.empty())
							cell->setPort(RTLIL::escape_id(portname2), RTLIL::SigSpec(new_wire, i));
						if (!widthparam.empty())
							cell->parameters[RTLIL::escape_id(widthparam)] = RTLIL::Const(1);
						if (!nameparam.empty())
							cell->parameters[RTLIL::escape_id(nameparam)] = RTLIL::Const(stringf("%s[%d]", RTLIL::id2cstr(wire->name), i));
						cell->attributes["\\keep"] = RTLIL::Const(1);
					}
				}
				else
				{
					RTLIL::Cell *cell = module->addCell(NEW_ID, RTLIL::escape_id(celltype));
					cell->setPort(RTLIL::escape_id(portname), RTLIL::SigSpec(wire));
					if (!portname2.empty())
						cell->setPort(RTLIL::escape_id(portname2), RTLIL::SigSpec(new_wire));
					if (!widthparam.empty())
						cell->parameters[RTLIL::escape_id(widthparam)] = RTLIL::Const(wire->width);
					if (!nameparam.empty())
						cell->parameters[RTLIL::escape_id(nameparam)] = RTLIL::Const(RTLIL::id2cstr(wire->name));
					cell->attributes["\\keep"] = RTLIL::Const(1);
				}

				wire->port_id = 0;
				wire->port_input = false;
				wire->port_output = false;
			}

			module->fixup_ports();
		}
	}
} IopadmapPass;

PRIVATE_NAMESPACE_END
<|endoftext|>


<commit_before>#include <stdio.h>
#include <graphics.h>
#include <windows.h>
#include <stdlib.h>
#define panjang 600
#define MAX_INPUT_LEN 15

//typedef struct{
	//char *name;
	//int score;
	//int lives;
//}playerControl;

int kursor(int, int, int);
void tampilan();
void tampilan2();
void menuutama();
void player1();
void player2();
void menuplay();
void menuscore();
void howtoplay();
void aboutus();
void inputnama();

int main()
{
int gd=DETECT, gm;
initwindow(800,600);
menuutama();
getch();
closegraph();
return 0;
}

int kursor(int option, int x, int y)
{
	int select=1, p=x+25, q=y+25;
	int input;
	readimagefile("picture/pacman1.bmp",x, y, p, q); //menampilkan lambang kursor
	do
	{
		input=getch();
		if(input==80) //80 kode ASCII kursor bawah
		{
			readimagefile("picture/black.bmp",x, y, p, q);
			y=y+25;
			q=q+25;
			select++;
			if(select>option)
			{
				y=y-(25*option);
				q=q-(25*option);
				select=1;
			}
			readimagefile("picture/pacman1.bmp",x, y, p, q);
		}
		if(input==72) //72 kode ASCII kursor atas
		{
			readimagefile("picture/black.bmp",x, y, p, q);
			y=y-25;
			q=q-25;
			select--;
			if (select<1)
			{
				y=y+(25*option);
				q=q+(25*option);
				select=option;
			}
			readimagefile("picture/pacman1.bmp",x, y, p, q);
		}
	}
	while(input!=13);
	return select;
}

void tampilan()
{
    //setbkcolor(2);
    setfillstyle(SOLID_FILL, 10);
    readimagefile("picture/pecimen.bmp",100, 10 , 700, 210);
    readimagefile("picture/pacman.bmp",50, 250, 300, 550);
}
void tampilan2()
{
    //setbkcolor(2);
    setfillstyle(SOLID_FILL, 10);
    readimagefile("picture/pecimen.bmp",100, 10 , 700, 210);
    readimagefile("picture/pacman2.bmp",0, 200, 150, 580);
    readimagefile("picture/pacman2.bmp",650, 200, 800, 580);
}
void player1()
{
    cleardevice();
    tampilan();
    //outtextxy(475,300,"1 player ");
    inputnama();
}

void player2()
{
    cleardevice();
    tampilan();
    //outtextxy(475,300,"2 player ");
    inputnama();
}

void menuplay()
{
    cleardevice();
    tampilan();
    //cleardevice();
    setcolor(15);
    settextstyle(9,HORIZ_DIR,2);
    outtextxy(375,300, "PLAYER");
    settextstyle(8,HORIZ_DIR,1);
    setcolor(9);
    outtextxy(390,350, "1 PLAYER");
    outtextxy(390,375, "2 PLAYER");
    setcolor(4);
    outtextxy(370,400, "BACK TO MENU");
    setcolor(15);
    int player = kursor(3,325,350);
    switch(player) //kursor di 4 posisi, x=50, y=32
{
	case 1 : player1();break;
	case 2 : player2();break;
    case 3 : menuutama();break;
	}
}

void menuscore()
{
    cleardevice();
    tampilan2();
    outtextxy(400,300,"score: ");
    	setcolor(4);
	outtextxy(370,570,"BACK TO MENU");
	int skor = kursor(1,325,570);
    switch(skor)
    {
        case 1 : menuutama();break;
    }
}

void howtoplay()
{ int a=5,b=32,c=17;
    cleardevice();
    readimagefile("picture/pacman1.bmp",200, 5, 225, 30);
    readimagefile("picture/pacman1.bmp",575, 5, 600, 30);
    settextstyle(8,HORIZ_DIR,3);
    outtextxy(320,5, "How To Play");
    settextstyle(8,HORIZ_DIR,1);
    outtextxy(a,b,"> Game ini dapat dimainkan 1  2 Orang  ");
    outtextxy(a,b+(1*c),"> Peci-men dikontrol menggunakan keyboard. ");
    outtextxy(a,b+(2*c),"> Setiap player menggerakan 1 Peci-men. ?  ");
    outtextxy(a,b+(3*c),"> Kontrol Player 1 :   ");
    outtextxy(a+50,b+(4*c),"o Arrow atas untuk menggerakan ke atas ");
    outtextxy(a+50,b+(5*c),"o Arrow bawah untuk menggerakan ke bawah  ");
    outtextxy(a+50,b+(6*c),"o Arrow kanan untuk menggerakan ke kanan  ");
    outtextxy(a+50,b+(7*c),"o Arrow kiri untuk menggerakan ke kiri ");
    outtextxy(a,b+(8*c),"> Kontrol Player 2 :   ");
	outtextxy(a+50,b+(9*c),"o Tombol W untuk menggerakan ke atas  ");
	outtextxy(a+50,b+(10*c),"o Tombol S untuk menggerakan ke bawah  ");
	outtextxy(a+50,b+(11*c),"o Tombol D untuk menggerakan ke kanan  ");
	outtextxy(a+50,b+(12*c),"o Tombol A untuk menggerakan ke kiri  ");
    outtextxy(a,b+(13*c),"> Peci-Men tidak dapat menembus pembatas/dinding labirin  ");
    outtextxy(a,b+(14*c),"> Pada sisi kanan dan kiri ada pintu khusus yang membuat Peci-Men");
    outtextxy(a,b+(15*c),"  berpindah tempat / teleport dari satu sisi ke sisi lainnya.  ");
    outtextxy(a,b+(16*c),"> Setiap player diberikan 3 Nyawa ? Terdapat bonus / sesajen untuk");
    outtextxy(a,b+(17*c),"  menambah skor dan lives (nyawa) dari karakter Pac-Man yang dimainkan.  ");
    outtextxy(a,b+(18*c),"> Dalam mode multi-player, Peci-Men yang paling cepat menghabiskan");
    outtextxy(a,b+(19*c),"  dan mendapat skor yang paling tinggi menjadi pemenangnya  ");
    outtextxy(a,b+(20*c),"> Peci-Men dapat memakan musuh dengan memakan bonus, sehingga musuh");
    outtextxy(a,b+(21*c),"  berubah warna dan mencoba menghindari Peci-Men.  ");
    outtextxy(a,b+(22*c),"> Kondisi menang ditentukan saat semua Pac-Dot termakan oleh karakter");
    outtextxy(a,b+(23*c),"  Peci-Men ? Player akan dinyatakan kalah / Game Over jika Peci-Men");
    outtextxy(a,b+(24*c),"  terkena musuh.");
    outtextxy(a,b+(25*c),"> Jika nyawa Peci-Men habis maka game akan dihentikan.  ");
    outtextxy(a,b+(26*c),"> Kemampuan tiap hantu :  ");
	outtextxy(a+50,b+(27*c),"o Tuyul : Lari cepat dan mengambil skor ")  ;
	outtextxy(a+50,b+(28*c),"o Kuntilanak : Bisa menembut 1 tembok  ");
	outtextxy(a+50,b+(29*c),"o Pocong : Meloncat 2 petak  ");
	outtextxy(a+50,b+(30*c),"o Tengkorak : Mengfreze peci-men ");
	setcolor(4);
	outtextxy(370,570,"BACK TO MENU");
	int how = kursor(1,325,570);
    switch(how)
    {
        case 1 : menuutama();break;
    }
}

void aboutus()
{
    cleardevice();
    outtextxy(45,30, "  AAA    BBBBBBB   OOOOO  UUUU UUUU TTTTTTT   UUUU UUUU SSSSSSS");
    outtextxy(45,47, " AA AA    BB   BB OO   OO  UU   UU    TTT      UU   UU  SS   SS");
    outtextxy(45,64, "AA   AA   BB   BB OO   OO  UU   UU    TTT      UU   UU  SS");
    outtextxy(45,81, "AAAAAAA   BBBBBB  OO   OO  UU   UU    TTT      UU   UU  SSSSSSS");
    outtextxy(45,98, "AA   AA   BB   BB OO   OO  UU   UU    TTT      UU   UU       SS");
    outtextxy(45,115,"AA   AA   BB   BB OO   OO  UU   UU    TTT      UU   UU  SS   SS");
    outtextxy(35,130,"AAAA AAAA BBBBBBB   OOOOO   UUUUUUU    TTT      UUUUUUU  SSSSSSS ");
    rectangle(20,164,755,270);
    rectangle(20,270,755,490);
    outtextxy(350,185,"<Leader>");
    outtextxy(280,220,"Nama : Pega Kurniawan");
    outtextxy(280,240,"NIM  : 161511060");
    outtextxy(25,300,"Nama : Auliya Aqma Dinilah");
    outtextxy(25,320,"NIM  : 161511006");
    outtextxy(25,380,"Nama : Haya Utami Lutfi");
    outtextxy(25,400,"NIM  : 161511011");
    outtextxy(400,300,"Nama : Achmad Fadhitya Muharram");
    outtextxy(400,320,"NIM  : 161511034");
    outtextxy(400,380,"Nama : Fahmi Rosdiansyah Mahdani");
    outtextxy(400,400,"NIM  : 161511044");
    outtextxy(280,440,"Nama : Muhamad Hisyam Anshory");
    outtextxy(280,460,"NIM  : 161511052");

    setcolor(15);
    settextstyle(8,HORIZ_DIR,1);
    outtextxy(200,550,"Kelompok 9 - D3 Teknik Informatika");
    outtextxy(250,570,"POLITEKNIK NEGERI BANDUNG");

    setcolor(4);
    outtextxy(350,505, "BACK TO MENU");

    setcolor(15);
    int player = kursor(1,325,500);
    switch(player) //kursor di 4 posisi, x=50, y=32
    {
        case 1 : menuutama();break;
	}
}

void menuutama()
{
    cleardevice();
    tampilan();
    menu :
    setcolor(15);
    settextstyle(9,HORIZ_DIR,2);
    outtextxy(385,300, "MENU");
    settextstyle(8,HORIZ_DIR,1);
    setcolor(9);
    outtextxy(400,350, "PLAY");
    outtextxy(395,375, "SCORE");
    outtextxy(370,400, "HOW TO PLAY");
    outtextxy(385,425, "ABOUT US");
    setcolor(4);
    outtextxy(400,450, "EXIT");
    setcolor(15);
    int menu = kursor(5,325,350);
    switch(menu) //kursor di 5 posisi, x=350, y=350
{
	case 1 : menuplay();break;
	case 2 : menuscore ();break;
	case 3 : howtoplay(); break;
	case 4 : aboutus();break;
	case 5 : exit;
	}
}

void inputnama() {
    char inputbuf[MAX_INPUT_LEN];
    for(int idx=0;idx<MAX_INPUT_LEN;idx++)
        inputbuf[idx]=0;
    int input_pos = 0;
    int the_end=0;
    char c;
    do
    {
       cleardevice();
       readimagefile("picture/pecimen.bmp",100,10,700,160);
       rectangle(100,250,700,400);
       settextstyle(3, HORIZ_DIR,4);
       outtextxy(280,260,"Nama Player:");
       outtextxy (280, 300, inputbuf);
       c = getch();
       switch (c)
       {
            case 8: /* backspace */
              if (input_pos)
              {
                 input_pos--;
                 inputbuf[input_pos] = 0;
              }
              break;
            case 13: /* return */
              the_end = 1;
              break;
            case 27: /* Escape = Abort */
              inputbuf[0] = 0;
              the_end = 1;
              break;
            default:
              if (input_pos < MAX_INPUT_LEN-1 && c >= ' ' && c <= '~')
              {
                 inputbuf[input_pos] = c;
                 input_pos++;
                 inputbuf[input_pos] = 0;
              }
       }

    } while (!the_end);
    //getchar(playerControl player1.name);
}
<commit_msg>tampilan menu baru<commit_after>#include <stdio.h>
#include <graphics.h>
#include <windows.h>
#include <stdlib.h>

#define panjang 600
#define MAX_INPUT_LEN 15

//typedef struct{
	//char *name;
	//int score;
	//int lives;
//}playerControl;

int kursor(int, int, int);
void tampilan();
void tampilan2();
void menuutama();
void player1();
void player2();
void menuplay();
void menuscore();
void howtoplay();
void aboutus();
void inputnama();

int main()
{
int gd=DETECT, gm;
initwindow(800,600);
menuutama();
getch();
closegraph();
return 0;
}

int kursor(int option, int x, int y)
{
	int select=1, p=x+25, q=y+25;
	int input;
	readimagefile("picture/pacman1.bmp",x, y, p, q); //menampilkan lambang kursor
	do
	{
		input=getch();
		if(input==80) //80 kode ASCII kursor bawah
		{
			readimagefile("picture/black.bmp",x, y, p, q);
			y=y+25;
			q=q+25;
			select++;
			if(select>option)
			{
				y=y-(25*option);
				q=q-(25*option);
				select=1;
			}
			readimagefile("picture/pacman1.bmp",x, y, p, q);
		}
		if(input==72) //72 kode ASCII kursor atas
		{
			readimagefile("picture/black.bmp",x, y, p, q);
			y=y-25;
			q=q-25;
			select--;
			if (select<1)
			{
				y=y+(25*option);
				q=q+(25*option);
				select=option;
			}
			readimagefile("picture/pacman1.bmp",x, y, p, q);
		}
	}
	while(input!=13);
	return select;
}

void tampilan()
{
    //setbkcolor(2);
    setfillstyle(SOLID_FILL, 10);
    readimagefile("picture/pecimen.bmp",100, 10 , 700, 210);
    readimagefile("picture/pacman.bmp",50, 250, 300, 550);
}

void tampilan2()
{
    //setbkcolor(2);
    setfillstyle(SOLID_FILL, 10);
    readimagefile("picture/pecimen.bmp",100, 10 , 700, 210);
    readimagefile("picture/pacman2.bmp",0, 200, 150, 580);
    readimagefile("picture/pacman2.bmp",650, 200, 800, 580);
}

void player1()
{
    cleardevice();
    tampilan();
    //outtextxy(500,300,"1 player ");
    inputnama();
}

void player2()
{
    cleardevice();
    tampilan();
    //outtextxy(500,300,"2 player ");
    inputnama();
}

void menuplay()
{
    cleardevice();
    tampilan();
    //cleardevice();
    setcolor(15);
    settextstyle(9,HORIZ_DIR,2);
    outtextxy(375,300, "PLAYER");
    settextstyle(8,HORIZ_DIR,1);
    setcolor(9);
    outtextxy(390,355, "1 PLAYER");
    outtextxy(390,382, "2 PLAYER");
    setcolor(4);
    outtextxy(370,408, "BACK TO MENU");
    setcolor(15);
    int player = kursor(3,325,350);
    switch(player) //kursor di 4 posisi, x=50, y=32
{
	case 1 : player1();break;
	case 2 : player2();break;
    case 3 : menuutama();break;
	}
}

void menuscore()
{
    cleardevice();
    tampilan2();
    outtextxy(400,300,"score: ");
    	setcolor(4);
	outtextxy(370,570,"BACK TO MENU");
	int skor = kursor(1,325,570);
    switch(skor)
    {
        case 1 : menuutama();break;
    }
}

void howtoplay()
{ int a=5,b=32,c=17;
    cleardevice();
    readimagefile("picture/pacman1.bmp",200, 5, 225, 30);
    readimagefile("picture/pacman1.bmp",575, 5, 600, 30);
    settextstyle(8,HORIZ_DIR,3);
    outtextxy(320,5, "How To Play");
    settextstyle(8,HORIZ_DIR,1);
    outtextxy(a,b,"> Game ini dapat dimainkan 1  2 Orang  ");
    outtextxy(a,b+(1*c),"> Peci-men dikontrol menggunakan keyboard. ");
    outtextxy(a,b+(2*c),"> Setiap player menggerakan 1 Peci-men. ");
    outtextxy(a,b+(3*c),"> Kontrol Player 1 :   ");
    outtextxy(a+50,b+(4*c),"o Arrow atas untuk menggerakan ke atas ");
    outtextxy(a+50,b+(5*c),"o Arrow bawah untuk menggerakan ke bawah  ");
    outtextxy(a+50,b+(6*c),"o Arrow kanan untuk menggerakan ke kanan  ");
    outtextxy(a+50,b+(7*c),"o Arrow kiri untuk menggerakan ke kiri ");
    outtextxy(a,b+(8*c),"> Kontrol Player 2 :   ");
	outtextxy(a+50,b+(9*c),"o Tombol W untuk menggerakan ke atas  ");
	outtextxy(a+50,b+(10*c),"o Tombol S untuk menggerakan ke bawah  ");
	outtextxy(a+50,b+(11*c),"o Tombol D untuk menggerakan ke kanan  ");
	outtextxy(a+50,b+(12*c),"o Tombol A untuk menggerakan ke kiri  ");
    outtextxy(a,b+(13*c),"> Peci-Men tidak dapat menembus pembatas/dinding labirin  ");
    outtextxy(a,b+(14*c),"> Pada sisi kanan dan kiri ada pintu khusus yang membuat Peci-Men");
    outtextxy(a,b+(15*c),"  berpindah tempat / teleport dari satu sisi ke sisi lainnya.  ");
    outtextxy(a,b+(16*c),"> Setiap player diberikan 3 Nyawa ? Terdapat bonus / sesajen untuk");
    outtextxy(a,b+(17*c),"  menambah skor dan lives (nyawa) dari karakter Pac-Man yang dimainkan.  ");
    outtextxy(a,b+(18*c),"> Dalam mode multi-player, Peci-Men yang paling cepat menghabiskan");
    outtextxy(a,b+(19*c),"  dan mendapat skor yang paling tinggi menjadi pemenangnya  ");
    outtextxy(a,b+(20*c),"> Peci-Men dapat memakan musuh dengan memakan bonus, sehingga musuh");
    outtextxy(a,b+(21*c),"  berubah warna dan mencoba menghindari Peci-Men.  ");
    outtextxy(a,b+(22*c),"> Kondisi menang ditentukan saat semua Pac-Dot termakan oleh karakter");
    outtextxy(a,b+(23*c),"  Peci-Men ? Player akan dinyatakan kalah / Game Over jika Peci-Men");
    outtextxy(a,b+(24*c),"  terkena musuh.");
    outtextxy(a,b+(25*c),"> Jika nyawa Peci-Men habis maka game akan dihentikan.  ");
    outtextxy(a,b+(26*c),"> Kemampuan tiap hantu :  ");
	outtextxy(a+50,b+(27*c),"o Tuyul : Lari cepat dan mengambil skor ")  ;
	outtextxy(a+50,b+(28*c),"o Kuntilanak : Bisa menembut 1 tembok  ");
	outtextxy(a+50,b+(29*c),"o Pocong : Meloncat 2 petak  ");
	outtextxy(a+50,b+(30*c),"o Tengkorak : Mengfreze peci-men ");
	setcolor(4);
	outtextxy(370,570,"BACK TO MENU");
	int how = kursor(1,325,570);
    switch(how)
    {
        case 1 : menuutama();break;
    }
}

void aboutus()
{
    cleardevice();
    outtextxy(45,30, "  AAA    BBBBBBB   OOOOO  UUUU UUUU TTTTTTT   UUUU UUUU SSSSSSS");
    outtextxy(45,47, " AA AA    BB   BB OO   OO  UU   UU    TTT      UU   UU  SS   SS");
    outtextxy(45,64, "AA   AA   BB   BB OO   OO  UU   UU    TTT      UU   UU  SS");
    outtextxy(45,81, "AAAAAAA   BBBBBB  OO   OO  UU   UU    TTT      UU   UU  SSSSSSS");
    outtextxy(45,98, "AA   AA   BB   BB OO   OO  UU   UU    TTT      UU   UU       SS");
    outtextxy(45,115,"AA   AA   BB   BB OO   OO  UU   UU    TTT      UU   UU  SS   SS");
    outtextxy(35,130,"AAAA AAAA BBBBBBB   OOOOO   UUUUUUU    TTT      UUUUUUU  SSSSSSS ");
    rectangle(20,164,755,270);
    rectangle(20,270,755,490);
    outtextxy(350,185,"<Leader>");
    outtextxy(280,220,"Nama : Pega Kurniawan");
    outtextxy(280,240,"NIM  : 161511060");
    outtextxy(25,300,"Nama : Auliya Aqma Dinilah");
    outtextxy(25,320,"NIM  : 161511006");
    outtextxy(25,380,"Nama : Haya Utami Lutfi");
    outtextxy(25,400,"NIM  : 161511011");
    outtextxy(400,300,"Nama : Achmad Fadhitya Muharram");
    outtextxy(400,320,"NIM  : 161511034");
    outtextxy(400,380,"Nama : Fahmi Rosdiansyah Mahdani");
    outtextxy(400,400,"NIM  : 161511044");
    outtextxy(280,440,"Nama : Muhamad Hisyam Anshory");
    outtextxy(280,460,"NIM  : 161511052");

    setcolor(15);
    settextstyle(8,HORIZ_DIR,1);
    outtextxy(200,550,"Kelompok 9 - D3 Teknik Informatika");
    outtextxy(250,570,"POLITEKNIK NEGERI BANDUNG");

    setcolor(4);
    outtextxy(350,505, "BACK TO MENU");

    setcolor(15);
    int player = kursor(1,325,500);
    switch(player) //kursor di 4 posisi, x=50, y=32
    {
        case 1 : menuutama();break;
	}
}

void menuutama()
{
    cleardevice();
    tampilan();
    menu :
    setcolor(15);
    rectangle(350,280,505,340);
    settextstyle(9,HORIZ_DIR,2);
    outtextxy(385,300, "MENU");
    settextstyle(8,HORIZ_DIR,1);
    setcolor(9);
    outtextxy(400,355, "PLAY");
    outtextxy(395,380, "SCORE");
    outtextxy(370,406, "HOW TO PLAY");
    outtextxy(385,430, "ABOUT US");
    setcolor(4);
    outtextxy(400,458, "EXIT");
    setcolor(15);
    int menu = kursor(5,325,350);
    switch(menu) //kursor di 5 posisi, x=350, y=350
{
	case 1 : menuplay();break;
	case 2 : menuscore ();break;
	case 3 : howtoplay(); break;
	case 4 : aboutus();break;
	case 5 : exit;
	}
}

void inputnama() {
    char inputbuf[MAX_INPUT_LEN];
    for(int idx=0;idx<MAX_INPUT_LEN;idx++)
        inputbuf[idx]=0;
    int input_pos = 0;
    int the_end=0;
    char c;
    do
    {
       cleardevice();
       readimagefile("picture/pecimen.bmp",100,10,700,160);
       rectangle(100,250,700,400);
       settextstyle(3, HORIZ_DIR,4);
       outtextxy(280,260,"Nama Player:");
       outtextxy (280, 300, inputbuf);
       c = getch();
       switch (c)
       {
            case 8: /* backspace */
              if (input_pos)
              {
                 input_pos--;
                 inputbuf[input_pos] = 0;
              }
              break;
            case 13: /* return */
              the_end = 1;
              break;
            case 27: /* Escape = Abort */
              inputbuf[0] = 0;
              the_end = 1;
              break;
            default:
              if (input_pos < MAX_INPUT_LEN-1 && c >= ' ' && c <= '~')
              {
                 inputbuf[input_pos] = c;
                 input_pos++;
                 inputbuf[input_pos] = 0;
              }
       }

    } while (!the_end);
    //getchar(playerControl player1.name);
}
<|endoftext|>


<commit_before>/*
 *  menuQA.C
 *
 *
 *  Created by schutz on 01/08/08.
 *  Copyright 2008 CERN. All rights reserved.
 *fQA
 */
gROOT->Reset("a") ;

TControlBar * fQA   = NULL ;
TControlBar * fDet  = NULL ;
TControlBar * fHist = NULL ;
const Int_t fRun = atoi(gSystem->Getenv("RUNNUM")) ;
AliQA * fQAResult = NULL ;
TCanvas * fCa = NULL ;

void menuQA()
{
	cout << AliQA::GetQAResultFileName()  << endl ;
	TFile * qaResultFile = TFile::Open("QA.root") ; //AliQA::GetQAResultFileName() ) ;
	if ( ! qaResultFile ) {
		printf("File %s not found in current directory\n", AliQA::GetQAResultFileName() ) ;
		return ;
	}
	fQAResult = (AliQA *)qaResultFile->Get("QA") ;
	if ( ! fQAResult ) {
		printf("QA object not found in %s\n", AliQA::GetQAResultFileName() ) ;
		return ;
	}

	TFile * qaDataFile = TFile::Open(Form("Merged.QA.%d.root", fRun)) ;
	if ( ! qaDataFile ) {
		printf("File Merged.QA.%d.root not found in current directory\n", fRun) ;
		return ;
	}
	if (fQA)
		delete fQA ;
	fQA = new TControlBar("vertical", Form("Active detectors in Run %d", fRun), 40, 20);
	fQA->SetButtonWidth(400) ;
	fQA->AddButton("Clean Screen", "Cls()", "Clean the screen");
	// search active detectors
	TList * listOfDetectors = qaDataFile->GetListOfKeys() ;
	for (Int_t det = 0 ; det < listOfDetectors->GetEntries() ; det++) {
		char * detName = listOfDetectors->At(det)->GetName() ;
		if (fQAResult->IsSetAny(AliQA::GetDetIndex(detName)))
			char * buttonName = Form("QA SIGNALLED !! : %s", detName) ;
		else
			char * buttonName = Form("QA OK : %s", detName) ;
	  fQA->AddButton(buttonName, Form("MakeDetMenu(\"%s\")", detName), Form("Display the QA histograms for %s", detName));
	}
	fQA->Show();
}

void MakeDetMenu(char * detName)
{
	if (fDet)
		delete fDet ;
	if (fHist)
		delete fHist ;
	if (fCa)
		delete fCa ;
	fDet = new TControlBar("vertical", detName, 9000, 8000);
	fDet->SetButtonWidth(300) ;
	// serach all the QA tasks
	TDirectory * save = gDirectory ;
	gDirectory->cd(detName) ;
	TList * listOfTasks = gDirectory->GetListOfKeys() ;
	for (Int_t task = 0 ; task < listOfTasks->GetEntries() ; task++) {
		TString taskName = listOfTasks->At(task)->GetName() ;
		AliQA::ALITASK_t tt = AliQA::kNULLTASK ;
		if (taskName.Contains(AliQA::GetTaskName(AliQA::kRAWS)) )
			tt = AliQA::kRAW ;
		else if (taskName.Contains(AliQA::GetTaskName(AliQA::kRECPOINTS)) ||
				taskName.Contains(AliQA::GetTaskName(AliQA::kESDs)) )
			tt = AliQA::kREC ;
		else if (taskName.Contains(AliQA::GetTaskName(AliQA::kHITS)) ||
						 taskName.Contains(AliQA::GetTaskName(AliQA::kSDIGITS)) ||
						 taskName.Contains(AliQA::GetTaskName(AliQA::kDIGITS)) )
			tt = AliQA::kSIM ;
		if (fQAResult->IsSetAny(AliQA::GetDetIndex(detName), tt))
			char * buttonName = Form("QA SIGNALLED !! : %s", taskName.Data()) ;
		else
			char * buttonName = Form("QA OK : %s", taskName.Data()) ;
			fDet->AddButton(buttonName, Form("MakeTaskMenu(\"%s\", \"%s\")", detName, taskName.Data()), Form("Display the QA histograms for %s", taskName.Data()));
	}
	fDet->Show() ;
	gDirectory = save ;
}

void MakeTaskMenu(char * detName, char * taskName )
{
	if (fHist)
		delete fHist ;
	if (fCa)
		delete fCa ;
	fHist = new TControlBar("vertical", Form("QA histos for %s/%s", detName, taskName), 900, 300);
	fHist->SetButtonWidth(300) ;
	fHist->AddButton("ALL", Form("DisplayAll(\"%s\", \"%s\")", detName, taskName), Form("Display the QA histograms for %s", detName));
	TDirectory * save = gDirectory ;
	gDirectory->cd(Form("%s/%s", detName, taskName)) ;
	TList * listOfHistos = gDirectory->GetListOfKeys() ;
	for (Int_t h = 0 ; h < listOfHistos->GetEntries() ; h++) {
		char * hName = listOfHistos->At(h)->GetName() ;
		fHist->AddButton(hName, Form("Display(\"%s\")", hName), Form("Display the QA histograms %s", hName));
	}
	fHist->Show() ;
	gDirectory = save ;
}

void Display(char * hName)
{
	if (fCa)
		delete fCa ;
	cout << Display << " " << hName << endl ;
	fCa = new TCanvas(hName, "test", 800, 600) ;
	fCa->SetLogy() ;
	TH1 * hh = dynamic_cast<TH1*>(gDirectory->FindObjectAny(hName));
	if (hh) {
		hh->Draw() ;
		fCa->Modified() ;
		fCa->Update() ;
	}
}

void DisplayAll(char * detName, char * taskName)
{
	cout << Display << " " << detName << endl ;
	TDirectory * save = gDirectory ;
	gDirectory->cd(Form("%s/%s", detName, taskName)) ;
	TList * listOfHistos = gDirectory->GetListOfKeys() ;
	Int_t nHisto = listOfHistos->GetEntries() ;
	Int_t ny = TMath::Sqrt(nHisto) ;
	Int_t nx = nHisto / ny + 1 ;
	if (fCa)
		delete fCa ;
	fCa = new TCanvas(Form("QA %s in %s", taskName, detName), Form("QA %s in %s", taskName, detName), nx*300, ny*300) ;
	fCa->Divide(nx, ny) ;
	for (Int_t h = 0 ; h < listOfHistos->GetEntries() ; h++) {
		char * hName = listOfHistos->At(h)->GetName() ;
		TH1 * hh = dynamic_cast<TH1*>(gDirectory->FindObjectAny(hName));
		TPad * pad = fCa->cd(h+1) ;
		pad->SetLogy() ;
		if (hh) {
			hh->Draw() ;
			fCa->Modified() ;
			fCa->Update() ;
		}
	}
	fCa->Modified() ;
	fCa->Update() ;
	gDirectory = save ;
}

void Cls()
{
	if (fDet)
		delete fDet ;
	if (fHist)
		delete fHist ;
	if (fCa)
		delete fCa ;
}
<commit_msg>typo<commit_after>/*
 *  menuQA.C
 *
 *
 *  Created by schutz on 01/08/08.
 *  Copyright 2008 CERN. All rights reserved.
 *fQA
 */
gROOT->Reset("a") ;

TControlBar * fQA   = NULL ;
TControlBar * fDet  = NULL ;
TControlBar * fHist = NULL ;
const Int_t fRun = atoi(gSystem->Getenv("RUNNUM")) ;
AliQA * fQAResult = NULL ;
TCanvas * fCa = NULL ;

void menuQA()
{
	cout << AliQA::GetQAResultFileName()  << endl ;
	TFile * qaResultFile = TFile::Open("QA.root") ; //AliQA::GetQAResultFileName() ) ;
	if ( ! qaResultFile ) {
		printf("File %s not found in current directory\n", AliQA::GetQAResultFileName() ) ;
		return ;
	}
	fQAResult = (AliQA *)qaResultFile->Get("QA") ;
	if ( ! fQAResult ) {
		printf("QA object not found in %s\n", AliQA::GetQAResultFileName() ) ;
		return ;
	}

	TFile * qaDataFile = TFile::Open(Form("Merged.QA.%d.root", fRun)) ;
	if ( ! qaDataFile ) {
		printf("File Merged.QA.%d.root not found in current directory\n", fRun) ;
		return ;
	}
	if (fQA)
		delete fQA ;
	fQA = new TControlBar("vertical", Form("Active detectors in Run %d", fRun), 40, 20);
	fQA->SetButtonWidth(400) ;
	fQA->AddButton("Clean Screen", "Cls()", "Clean the screen");
	// search active detectors
	TList * listOfDetectors = qaDataFile->GetListOfKeys() ;
	for (Int_t det = 0 ; det < listOfDetectors->GetEntries() ; det++) {
		char * detName = listOfDetectors->At(det)->GetName() ;
		if (fQAResult->IsSetAny(AliQA::GetDetIndex(detName)))
			char * buttonName = Form("QA SIGNALLED !! : %s", detName) ;
		else
			char * buttonName = Form("QA OK : %s", detName) ;
	  fQA->AddButton(buttonName, Form("MakeDetMenu(\"%s\")", detName), Form("Display the QA histograms for %s", detName));
	}
	fQA->Show();
}

void MakeDetMenu(char * detName)
{
	if (fDet)
		delete fDet ;
	if (fHist)
		delete fHist ;
	if (fCa)
		delete fCa ;
	fDet = new TControlBar("vertical", detName, 9000, 8000);
	fDet->SetButtonWidth(300) ;
	// serach all the QA tasks
	TDirectory * save = gDirectory ;
	gDirectory->cd(detName) ;
	TList * listOfTasks = gDirectory->GetListOfKeys() ;
	for (Int_t task = 0 ; task < listOfTasks->GetEntries() ; task++) {
		TString taskName = listOfTasks->At(task)->GetName() ;
		AliQA::ALITASK_t tt = AliQA::kNULLTASK ;
		if (taskName.Contains(AliQA::GetTaskName(AliQA::kRAWS)) )
			tt = AliQA::kRAW ;
		else if (taskName.Contains(AliQA::GetTaskName(AliQA::kRECPOINTS)) ||
				taskName.Contains(AliQA::GetTaskName(AliQA::kESDS)) )
			tt = AliQA::kREC ;
		else if (taskName.Contains(AliQA::GetTaskName(AliQA::kHITS)) ||
						 taskName.Contains(AliQA::GetTaskName(AliQA::kSDIGITS)) ||
						 taskName.Contains(AliQA::GetTaskName(AliQA::kDIGITS)) )
			tt = AliQA::kSIM ;
		if (fQAResult->IsSetAny(AliQA::GetDetIndex(detName), tt))
			char * buttonName = Form("QA SIGNALLED !! : %s", taskName.Data()) ;
		else
			char * buttonName = Form("QA OK : %s", taskName.Data()) ;
			fDet->AddButton(buttonName, Form("MakeTaskMenu(\"%s\", \"%s\")", detName, taskName.Data()), Form("Display the QA histograms for %s", taskName.Data()));
	}
	fDet->Show() ;
	gDirectory = save ;
}

void MakeTaskMenu(char * detName, char * taskName )
{
	if (fHist)
		delete fHist ;
	if (fCa)
		delete fCa ;
	fHist = new TControlBar("vertical", Form("QA histos for %s/%s", detName, taskName), 900, 300);
	fHist->SetButtonWidth(300) ;
	fHist->AddButton("ALL", Form("DisplayAll(\"%s\", \"%s\")", detName, taskName), Form("Display the QA histograms for %s", detName));
	TDirectory * save = gDirectory ;
	gDirectory->cd(Form("%s/%s", detName, taskName)) ;
	TList * listOfHistos = gDirectory->GetListOfKeys() ;
	for (Int_t h = 0 ; h < listOfHistos->GetEntries() ; h++) {
		char * hName = listOfHistos->At(h)->GetName() ;
		fHist->AddButton(hName, Form("Display(\"%s\")", hName), Form("Display the QA histograms %s", hName));
	}
	fHist->Show() ;
	gDirectory = save ;
}

void Display(char * hName)
{
	if (fCa)
		delete fCa ;
	cout << Display << " " << hName << endl ;
	fCa = new TCanvas(hName, "test", 800, 600) ;
	fCa->SetLogy() ;
	TH1 * hh = dynamic_cast<TH1*>(gDirectory->FindObjectAny(hName));
	if (hh) {
		hh->Draw() ;
		fCa->Modified() ;
		fCa->Update() ;
	}
}

void DisplayAll(char * detName, char * taskName)
{
	cout << Display << " " << detName << endl ;
	TDirectory * save = gDirectory ;
	gDirectory->cd(Form("%s/%s", detName, taskName)) ;
	TList * listOfHistos = gDirectory->GetListOfKeys() ;
	Int_t nHisto = listOfHistos->GetEntries() ;
	Int_t ny = TMath::Sqrt(nHisto) ;
	Int_t nx = nHisto / ny + 1 ;
	if (fCa)
		delete fCa ;
	fCa = new TCanvas(Form("QA %s in %s", taskName, detName), Form("QA %s in %s", taskName, detName), nx*300, ny*300) ;
	fCa->Divide(nx, ny) ;
	for (Int_t h = 0 ; h < listOfHistos->GetEntries() ; h++) {
		char * hName = listOfHistos->At(h)->GetName() ;
		TH1 * hh = dynamic_cast<TH1*>(gDirectory->FindObjectAny(hName));
		TPad * pad = fCa->cd(h+1) ;
		pad->SetLogy() ;
		if (hh) {
			hh->Draw() ;
			fCa->Modified() ;
			fCa->Update() ;
		}
	}
	fCa->Modified() ;
	fCa->Update() ;
	gDirectory = save ;
}

void Cls()
{
	if (fDet)
		delete fDet ;
	if (fHist)
		delete fHist ;
	if (fCa)
		delete fCa ;
}
<|endoftext|>


<commit_before>#ifndef TEST_MEMORY_CLEANUP
#define TEST_MEMORY_CLEANUP

#include <mapnik/warning.hpp>
MAPNIK_DISABLE_WARNING_PUSH
#include <mapnik/warning_ignore.hpp>

#if defined(HAVE_LIBXML2)
#include <libxml/parser.h>
#include <libxml/entities.h>
#include <libxml/globals.h>
#endif

#if defined(HAVE_CAIRO)
#include <cairo.h>
#endif

#include <unicode/uclean.h>
#ifdef MAPNIK_USE_PROJ4
#include <proj_api.h>
#endif

MAPNIK_DISABLE_WARNING_POP

namespace testing {

inline void run_cleanup()
{
    // only call this once, on exit
    // to make sure valgrind output is clean
    // http://xmlsoft.org/xmlmem.html
#if defined(HAVE_LIBXML2)
    xmlCleanupCharEncodingHandlers();
    xmlCleanupEncodingAliases();
    xmlCleanupGlobals();
    xmlCleanupParser();
    xmlCleanupThreads();
    xmlCleanupInputCallbacks();
    xmlCleanupOutputCallbacks();
    xmlCleanupMemory();
#endif

#if defined(HAVE_CAIRO)
    // http://cairographics.org/manual/cairo-Error-handling.html#cairo-debug-reset-static-data
    cairo_debug_reset_static_data();
#endif

    // http://icu-project.org/apiref/icu4c/uclean_8h.html#a93f27d0ddc7c196a1da864763f2d8920
    u_cleanup();

#ifdef MAPNIK_USE_PROJ4
    // http://trac.osgeo.org/proj/ticket/149
 #if PJ_VERSION >= 480
    pj_clear_initcache();
 #endif
    // https://trac.osgeo.org/proj/wiki/ProjAPI#EnvironmentFunctions
    pj_deallocate_grids();
#endif
}

}

#endif
<commit_msg>Remove proj4 related stuff<commit_after>#ifndef TEST_MEMORY_CLEANUP
#define TEST_MEMORY_CLEANUP

#include <mapnik/warning.hpp>
MAPNIK_DISABLE_WARNING_PUSH
#include <mapnik/warning_ignore.hpp>

#if defined(HAVE_LIBXML2)
#include <libxml/parser.h>
#include <libxml/entities.h>
#include <libxml/globals.h>
#endif

#if defined(HAVE_CAIRO)
#include <cairo.h>
#endif

#include <unicode/uclean.h>

MAPNIK_DISABLE_WARNING_POP

namespace testing {

inline void run_cleanup()
{
    // only call this once, on exit
    // to make sure valgrind output is clean
    // http://xmlsoft.org/xmlmem.html
#if defined(HAVE_LIBXML2)
    xmlCleanupCharEncodingHandlers();
    xmlCleanupEncodingAliases();
    xmlCleanupGlobals();
    xmlCleanupParser();
    xmlCleanupThreads();
    xmlCleanupInputCallbacks();
    xmlCleanupOutputCallbacks();
    xmlCleanupMemory();
#endif

#if defined(HAVE_CAIRO)
    // http://cairographics.org/manual/cairo-Error-handling.html#cairo-debug-reset-static-data
    cairo_debug_reset_static_data();
#endif

    // http://icu-project.org/apiref/icu4c/uclean_8h.html#a93f27d0ddc7c196a1da864763f2d8920
    u_cleanup();
}

}

#endif
<|endoftext|>


<commit_before>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <deque>

#include "catch.hpp"

#define DLL_SVM_SUPPORT

#include "dll/dyn_rbm.hpp"
#include "dll/dyn_dbn.hpp"

#include "dll/stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE( "dyn_dbn/mnist_1", "dbn::simple" ) {
    using dbn_t =
        dll::dyn_dbn_desc<
            dll::dbn_dyn_layers<
                dll::dyn_rbm_desc<dll::momentum, dll::init_weights>::rbm_t,
                dll::dyn_rbm_desc<dll::momentum>::rbm_t,
                dll::dyn_rbm_desc<dll::momentum, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t
        >>::dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(500);

    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>(
        std::make_tuple(28*28,100),
        std::make_tuple(100,200),
        std::make_tuple(200,10));

    dbn->pretrain(dataset.training_images, 20);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());

    std::cout << "test_error:" << test_error << std::endl;

    REQUIRE(test_error < 1.0);
}
<commit_msg>New test<commit_after>//=======================================================================
// Copyright (c) 2014 Baptiste Wicht
// Distributed under the terms of the MIT License.
// (See accompanying file LICENSE or copy at
//  http://opensource.org/licenses/MIT)
//=======================================================================

#include <deque>

#include "catch.hpp"

#define DLL_SVM_SUPPORT

#include "dll/dyn_rbm.hpp"
#include "dll/dyn_dbn.hpp"

#include "dll/stochastic_gradient_descent.hpp"

#include "mnist/mnist_reader.hpp"
#include "mnist/mnist_utils.hpp"

TEST_CASE( "dyn_dbn/mnist_1", "dbn::simple" ) {
    using dbn_t =
        dll::dyn_dbn_desc<
            dll::dbn_dyn_layers<
                dll::dyn_rbm_desc<dll::momentum, dll::init_weights>::rbm_t,
                dll::dyn_rbm_desc<dll::momentum>::rbm_t,
                dll::dyn_rbm_desc<dll::momentum, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t
        >>::dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(500);

    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>(
        std::make_tuple(28*28,100),
        std::make_tuple(100,200),
        std::make_tuple(200,10));

    dbn->pretrain(dataset.training_images, 20);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());

    std::cout << "test_error:" << test_error << std::endl;

    REQUIRE(test_error < 1.0);
}

TEST_CASE( "dyn_dbn/mnist_2", "dbn::parallel" ) {
    using dbn_t =
        dll::dyn_dbn_desc<
            dll::dbn_dyn_layers<
                dll::dyn_rbm_desc<dll::momentum, dll::parallel, dll::init_weights>::rbm_t,
                dll::dyn_rbm_desc<dll::momentum, dll::parallel>::rbm_t,
                dll::dyn_rbm_desc<dll::momentum, dll::parallel, dll::hidden<dll::unit_type::SOFTMAX>>::rbm_t
        >>::dbn_t;

    auto dataset = mnist::read_dataset<std::vector, std::vector, double>(500);

    REQUIRE(!dataset.training_images.empty());

    mnist::binarize_dataset(dataset);

    auto dbn = std::make_unique<dbn_t>(
        std::make_tuple(28*28,100),
        std::make_tuple(100,200),
        std::make_tuple(200,10));

    dbn->pretrain(dataset.training_images, 20);

    auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor());

    std::cout << "test_error:" << test_error << std::endl;

    REQUIRE(test_error < 1.0);
}
<|endoftext|>