<commit_before>#include "ContentWindowGraphicsItem.h"
#include "Content.h"
#include "ContentWindowManager.h"
#include "DisplayGroupManager.h"
#include "DisplayGroupGraphicsView.h"
#include "main.h"

qreal ContentWindowGraphicsItem::zCounter_ = 0;

ContentWindowGraphicsItem::ContentWindowGraphicsItem(boost::shared_ptr<ContentWindowManager> contentWindowManager) : ContentWindowInterface(contentWindowManager)
{
    // defaults
    resizing_ = false;

    // graphics items are movable
    setFlag(QGraphicsItem::ItemIsMovable, true);

    // default fill color / opacity
    setBrush(QBrush(QColor(0, 0, 0, 128)));

    // border based on if we're selected or not
    // use the -1 argument to force an update but not emit signals
    setSelected(selected_, (ContentWindowInterface *)-1);

    // current coordinates
    setRect(x_, y_, w_, h_);

    // new items at the front
    // we assume that interface items will be constructed in depth order so this produces the correct result...
    setZToFront();
}

void ContentWindowGraphicsItem::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
    QGraphicsRectItem::paint(painter, option, widget);

    boost::shared_ptr<ContentWindowManager> contentWindowManager = getContentWindowManager();

    if(contentWindowManager != NULL)
    {
        // default pen
        QPen pen;

        // button dimensions
        float buttonWidth, buttonHeight;
        getButtonDimensions(buttonWidth, buttonHeight);

        // draw close button
        QRectF closeRect(rect().x() + rect().width() - buttonWidth, rect().y(), buttonWidth, buttonHeight);
        pen.setColor(QColor(255,0,0));
        painter->setPen(pen);
        painter->drawRect(closeRect);
        painter->drawLine(QPointF(rect().x() + rect().width() - buttonWidth, rect().y()), QPointF(rect().x() + rect().width(), rect().y() + buttonHeight));
        painter->drawLine(QPointF(rect().x() + rect().width(), rect().y()), QPointF(rect().x() + rect().width() - buttonWidth, rect().y() + buttonHeight));

        // resize indicator
        QRectF resizeRect(rect().x() + rect().width() - buttonWidth, rect().y() + rect().height() - buttonHeight, buttonWidth, buttonHeight);
        pen.setColor(QColor(128,128,128));
        painter->setPen(pen);
        painter->drawRect(resizeRect);
        painter->drawLine(QPointF(rect().x() + rect().width(), rect().y() + rect().height() - buttonHeight), QPointF(rect().x() + rect().width() - buttonWidth, rect().y() + rect().height()));

        // text label

        // set the font
        float fontSize = 24.;

        QFont font;
        font.setPixelSize(fontSize);
        painter->setFont(font);

        // color the text black
        pen.setColor(QColor(0,0,0));
        painter->setPen(pen);

        // scale the text size down to the height of the graphics view
        // and, calculate the bounding rectangle for the text based on this scale
        // the dimensions of the view need to be corrected for the tiled display aspect ratio
        // recall the tiled display UI is only part of the graphics view since we show it at the correct aspect ratio
        float viewWidth = (float)scene()->views()[0]->width();
        float viewHeight = (float)scene()->views()[0]->height();

        float tiledDisplayAspect = (float)g_configuration->getTotalWidth() / (float)g_configuration->getTotalHeight();

        if(viewWidth / viewHeight > tiledDisplayAspect)
        {
            viewWidth = viewHeight * tiledDisplayAspect;
        }
        else if(viewWidth / viewHeight <= tiledDisplayAspect)
        {
            viewHeight = viewWidth / tiledDisplayAspect;
        }

        float verticalTextScale = 1. / viewHeight;
        float horizontalTextScale = viewHeight / viewWidth * verticalTextScale;

        painter->scale(horizontalTextScale, verticalTextScale);

        QRectF textBoundingRect = QRectF(rect().x() / horizontalTextScale, rect().y() / verticalTextScale, rect().width() / horizontalTextScale, rect().height() / verticalTextScale);

        // get the label and render it
        QString label(contentWindowManager->getContent()->getURI().c_str());
        QString labelSection = label.section("/", -1, -1).prepend(" ");
        painter->drawText(textBoundingRect, Qt::AlignLeft | Qt::AlignTop, labelSection);

        // draw window info at smaller scale
        verticalTextScale *= 0.5;
        horizontalTextScale *= 0.5;

        painter->scale(0.5, 0.5);

        textBoundingRect = QRectF(rect().x() / horizontalTextScale, rect().y() / verticalTextScale, rect().width() / horizontalTextScale, rect().height() / verticalTextScale);

        QString coordinatesLabel = QString(" (") + QString::number(x_, 'f', 2) + QString(" ,") + QString::number(y_, 'f', 2) + QString(", ") + QString::number(w_, 'f', 2) + QString(", ") + QString::number(h_, 'f', 2) + QString(")\n");
        QString zoomCenterLabel = QString(" zoom = ") + QString::number(zoom_, 'f', 2) + QString(" @ (") + QString::number(centerX_, 'f', 2) + QString(", ") + QString::number(centerY_, 'f', 2) + QString(")");

        QString windowInfoLabel = coordinatesLabel + zoomCenterLabel;
        painter->drawText(textBoundingRect, Qt::AlignLeft | Qt::AlignBottom, windowInfoLabel);
    }
}

void ContentWindowGraphicsItem::setCoordinates(double x, double y, double w, double h, ContentWindowInterface * source)
{
    ContentWindowInterface::setCoordinates(x, y, w, h, source);

    if(source != this)
    {
        setPos(x_, y_);
        setRect(mapRectFromScene(x_, y_, w_, h_));
    }
}

void ContentWindowGraphicsItem::setPosition(double x, double y, ContentWindowInterface * source)
{
    ContentWindowInterface::setPosition(x, y, source);

    if(source != this)
    {
        setPos(x_, y_);
        setRect(mapRectFromScene(x_, y_, w_, h_));
    }
}

void ContentWindowGraphicsItem::setSize(double w, double h, ContentWindowInterface * source)
{
    ContentWindowInterface::setSize(w, h, source);

    if(source != this)
    {
        setPos(x_, y_);
        setRect(mapRectFromScene(x_, y_, w_, h_));
    }
}

void ContentWindowGraphicsItem::setCenter(double centerX, double centerY, ContentWindowInterface * source)
{
    ContentWindowInterface::setCenter(centerX, centerY, source);

    if(source != this)
    {
        // force a redraw to update window info label
        update();
    }
}

void ContentWindowGraphicsItem::setZoom(double zoom, ContentWindowInterface * source)
{
    ContentWindowInterface::setZoom(zoom, source);

    if(source != this)
    {
        // force a redraw to update window info label
        update();
    }
}

void ContentWindowGraphicsItem::setSelected(bool selected, ContentWindowInterface * source)
{
    ContentWindowInterface::setSelected(selected, source);

    if(source != this)
    {
        // set the pen
        QPen p = pen();

        if(selected_ == true)
        {
            p.setColor(QColor(255,0,0));
        }
        else
        {
            p.setColor(QColor(0,0,0));
        }

        setPen(p);

        // force a redraw
        update();
    }
}

void ContentWindowGraphicsItem::setZToFront()
{
    zCounter_ = zCounter_ + 1;
    setZValue(zCounter_);
}

void ContentWindowGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event)
{
    // handle mouse movements differently depending on selected mode of item
    if(selected_ == false)
    {
        if(event->buttons().testFlag(Qt::LeftButton) == true)
        {
            if(resizing_ == true)
            {
                QRectF r = rect();
                QPointF eventPos = event->pos();

                r.setBottomRight(eventPos);

                QRectF sceneRect = mapRectToScene(r);

                double w = sceneRect.width();
                double h = sceneRect.height();

                setSize(w, h);
            }
            else
            {
                QPointF delta = event->pos() - event->lastPos();

                double x = x_ + delta.x();
                double y = y_ + delta.y();

                setPosition(x, y);
            }
        }
    }
    else
    {
        // handle zooms / pans
        QPointF delta = event->scenePos() - event->lastScenePos();

        if(event->buttons().testFlag(Qt::RightButton) == true)
        {
            // increment zoom

            // if this is a touch event, use cross-product for determining change in zoom (counterclockwise rotation == zoom in, etc.)
            // otherwise, use y as the change in zoom
            double zoomDelta;

            if(event->modifiers().testFlag(Qt::AltModifier) == true)
            {
                zoomDelta = (event->scenePos().x()-0.5) * delta.y() - (event->scenePos().y()-0.5) * delta.x();
                zoomDelta *= 2.;
            }
            else
            {
                zoomDelta = delta.y();
            }

            double zoom = zoom_ * (1. - zoomDelta);

            setZoom(zoom);
        }
        else if(event->buttons().testFlag(Qt::LeftButton) == true)
        {
            // pan (move center coordinates)
            double centerX = centerX_ + 2.*delta.x() / zoom_;
            double centerY = centerY_ + 2.*delta.y() / zoom_;

            setCenter(centerX, centerY);
        }

        // force a redraw to update window info label
        update();
    }
}

void ContentWindowGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent * event)
{
    // button dimensions
    float buttonWidth, buttonHeight;
    getButtonDimensions(buttonWidth, buttonHeight);

    // item rectangle and event position
    QRectF r = rect();
    QPointF eventPos = event->pos();

    // check to see if user clicked on the close button
    if(fabs((r.x()+r.width()) - eventPos.x()) <= buttonWidth && fabs((r.y()) - eventPos.y()) <= buttonHeight)
    {
        close();

        return;
    }

    // check to see if user clicked on the resize button
    if(fabs((r.x()+r.width()) - eventPos.x()) <= buttonWidth && fabs((r.y()+r.height()) - eventPos.y()) <= buttonHeight)
    {
        resizing_ = true;
    }

    // move to the front of the GUI display
    moveToFront();

    QGraphicsItem::mousePressEvent(event);
}

void ContentWindowGraphicsItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * event)
{
    bool selected = !selected_;

    setSelected(selected);

    QGraphicsItem::mouseDoubleClickEvent(event);
}

void ContentWindowGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event)
{
    resizing_ = false;

    QGraphicsItem::mouseReleaseEvent(event);
}

void ContentWindowGraphicsItem::wheelEvent(QGraphicsSceneWheelEvent * event)
{
    // handle wheel movements differently depending on selected mode of item
    if(selected_ == false)
    {
        // scale size based on wheel delta
        // typical delta value is 120, so scale based on that
        double factor = 1. + (double)event->delta() / (10. * 120.);

        scaleSize(factor);
    }
    else
    {
        // change zoom based on wheel delta
        // deltas are counted in 1/8 degrees. so, scale based on 180 degrees => delta = 180*8 = 1440
        double zoomDelta = (double)event->delta() / 1440.;
        double zoom = zoom_ * (1. + zoomDelta);

        setZoom(zoom);
    }
}
<commit_msg>Qt 4.7+ sends mouse events to the wrong graphics items on Mac. implemented a workaround to fix the problem.<commit_after>#include "ContentWindowGraphicsItem.h"
#include "Content.h"
#include "ContentWindowManager.h"
#include "DisplayGroupManager.h"
#include "DisplayGroupGraphicsView.h"
#include "main.h"

qreal ContentWindowGraphicsItem::zCounter_ = 0;

ContentWindowGraphicsItem::ContentWindowGraphicsItem(boost::shared_ptr<ContentWindowManager> contentWindowManager) : ContentWindowInterface(contentWindowManager)
{
    // defaults
    resizing_ = false;

    // graphics items are movable
    setFlag(QGraphicsItem::ItemIsMovable, true);

    // default fill color / opacity
    setBrush(QBrush(QColor(0, 0, 0, 128)));

    // border based on if we're selected or not
    // use the -1 argument to force an update but not emit signals
    setSelected(selected_, (ContentWindowInterface *)-1);

    // current coordinates
    setRect(x_, y_, w_, h_);

    // new items at the front
    // we assume that interface items will be constructed in depth order so this produces the correct result...
    setZToFront();
}

void ContentWindowGraphicsItem::paint(QPainter * painter, const QStyleOptionGraphicsItem * option, QWidget * widget)
{
    QGraphicsRectItem::paint(painter, option, widget);

    boost::shared_ptr<ContentWindowManager> contentWindowManager = getContentWindowManager();

    if(contentWindowManager != NULL)
    {
        // default pen
        QPen pen;

        // button dimensions
        float buttonWidth, buttonHeight;
        getButtonDimensions(buttonWidth, buttonHeight);

        // draw close button
        QRectF closeRect(rect().x() + rect().width() - buttonWidth, rect().y(), buttonWidth, buttonHeight);
        pen.setColor(QColor(255,0,0));
        painter->setPen(pen);
        painter->drawRect(closeRect);
        painter->drawLine(QPointF(rect().x() + rect().width() - buttonWidth, rect().y()), QPointF(rect().x() + rect().width(), rect().y() + buttonHeight));
        painter->drawLine(QPointF(rect().x() + rect().width(), rect().y()), QPointF(rect().x() + rect().width() - buttonWidth, rect().y() + buttonHeight));

        // resize indicator
        QRectF resizeRect(rect().x() + rect().width() - buttonWidth, rect().y() + rect().height() - buttonHeight, buttonWidth, buttonHeight);
        pen.setColor(QColor(128,128,128));
        painter->setPen(pen);
        painter->drawRect(resizeRect);
        painter->drawLine(QPointF(rect().x() + rect().width(), rect().y() + rect().height() - buttonHeight), QPointF(rect().x() + rect().width() - buttonWidth, rect().y() + rect().height()));

        // text label

        // set the font
        float fontSize = 24.;

        QFont font;
        font.setPixelSize(fontSize);
        painter->setFont(font);

        // color the text black
        pen.setColor(QColor(0,0,0));
        painter->setPen(pen);

        // scale the text size down to the height of the graphics view
        // and, calculate the bounding rectangle for the text based on this scale
        // the dimensions of the view need to be corrected for the tiled display aspect ratio
        // recall the tiled display UI is only part of the graphics view since we show it at the correct aspect ratio
        float viewWidth = (float)scene()->views()[0]->width();
        float viewHeight = (float)scene()->views()[0]->height();

        float tiledDisplayAspect = (float)g_configuration->getTotalWidth() / (float)g_configuration->getTotalHeight();

        if(viewWidth / viewHeight > tiledDisplayAspect)
        {
            viewWidth = viewHeight * tiledDisplayAspect;
        }
        else if(viewWidth / viewHeight <= tiledDisplayAspect)
        {
            viewHeight = viewWidth / tiledDisplayAspect;
        }

        float verticalTextScale = 1. / viewHeight;
        float horizontalTextScale = viewHeight / viewWidth * verticalTextScale;

        painter->scale(horizontalTextScale, verticalTextScale);

        QRectF textBoundingRect = QRectF(rect().x() / horizontalTextScale, rect().y() / verticalTextScale, rect().width() / horizontalTextScale, rect().height() / verticalTextScale);

        // get the label and render it
        QString label(contentWindowManager->getContent()->getURI().c_str());
        QString labelSection = label.section("/", -1, -1).prepend(" ");
        painter->drawText(textBoundingRect, Qt::AlignLeft | Qt::AlignTop, labelSection);

        // draw window info at smaller scale
        verticalTextScale *= 0.5;
        horizontalTextScale *= 0.5;

        painter->scale(0.5, 0.5);

        textBoundingRect = QRectF(rect().x() / horizontalTextScale, rect().y() / verticalTextScale, rect().width() / horizontalTextScale, rect().height() / verticalTextScale);

        QString coordinatesLabel = QString(" (") + QString::number(x_, 'f', 2) + QString(" ,") + QString::number(y_, 'f', 2) + QString(", ") + QString::number(w_, 'f', 2) + QString(", ") + QString::number(h_, 'f', 2) + QString(")\n");
        QString zoomCenterLabel = QString(" zoom = ") + QString::number(zoom_, 'f', 2) + QString(" @ (") + QString::number(centerX_, 'f', 2) + QString(", ") + QString::number(centerY_, 'f', 2) + QString(")");

        QString windowInfoLabel = coordinatesLabel + zoomCenterLabel;
        painter->drawText(textBoundingRect, Qt::AlignLeft | Qt::AlignBottom, windowInfoLabel);
    }
}

void ContentWindowGraphicsItem::setCoordinates(double x, double y, double w, double h, ContentWindowInterface * source)
{
    ContentWindowInterface::setCoordinates(x, y, w, h, source);

    if(source != this)
    {
        setPos(x_, y_);
        setRect(mapRectFromScene(x_, y_, w_, h_));
    }
}

void ContentWindowGraphicsItem::setPosition(double x, double y, ContentWindowInterface * source)
{
    ContentWindowInterface::setPosition(x, y, source);

    if(source != this)
    {
        setPos(x_, y_);
        setRect(mapRectFromScene(x_, y_, w_, h_));
    }
}

void ContentWindowGraphicsItem::setSize(double w, double h, ContentWindowInterface * source)
{
    ContentWindowInterface::setSize(w, h, source);

    if(source != this)
    {
        setPos(x_, y_);
        setRect(mapRectFromScene(x_, y_, w_, h_));
    }
}

void ContentWindowGraphicsItem::setCenter(double centerX, double centerY, ContentWindowInterface * source)
{
    ContentWindowInterface::setCenter(centerX, centerY, source);

    if(source != this)
    {
        // force a redraw to update window info label
        update();
    }
}

void ContentWindowGraphicsItem::setZoom(double zoom, ContentWindowInterface * source)
{
    ContentWindowInterface::setZoom(zoom, source);

    if(source != this)
    {
        // force a redraw to update window info label
        update();
    }
}

void ContentWindowGraphicsItem::setSelected(bool selected, ContentWindowInterface * source)
{
    ContentWindowInterface::setSelected(selected, source);

    if(source != this)
    {
        // set the pen
        QPen p = pen();

        if(selected_ == true)
        {
            p.setColor(QColor(255,0,0));
        }
        else
        {
            p.setColor(QColor(0,0,0));
        }

        setPen(p);

        // force a redraw
        update();
    }
}

void ContentWindowGraphicsItem::setZToFront()
{
    zCounter_ = zCounter_ + 1;
    setZValue(zCounter_);
}

void ContentWindowGraphicsItem::mouseMoveEvent(QGraphicsSceneMouseEvent * event)
{
    // handle mouse movements differently depending on selected mode of item
    if(selected_ == false)
    {
        if(event->buttons().testFlag(Qt::LeftButton) == true)
        {
            if(resizing_ == true)
            {
                QRectF r = rect();
                QPointF eventPos = event->pos();

                r.setBottomRight(eventPos);

                QRectF sceneRect = mapRectToScene(r);

                double w = sceneRect.width();
                double h = sceneRect.height();

                setSize(w, h);
            }
            else
            {
                QPointF delta = event->pos() - event->lastPos();

                double x = x_ + delta.x();
                double y = y_ + delta.y();

                setPosition(x, y);
            }
        }
    }
    else
    {
        // handle zooms / pans
        QPointF delta = event->scenePos() - event->lastScenePos();

        if(event->buttons().testFlag(Qt::RightButton) == true)
        {
            // increment zoom

            // if this is a touch event, use cross-product for determining change in zoom (counterclockwise rotation == zoom in, etc.)
            // otherwise, use y as the change in zoom
            double zoomDelta;

            if(event->modifiers().testFlag(Qt::AltModifier) == true)
            {
                zoomDelta = (event->scenePos().x()-0.5) * delta.y() - (event->scenePos().y()-0.5) * delta.x();
                zoomDelta *= 2.;
            }
            else
            {
                zoomDelta = delta.y();
            }

            double zoom = zoom_ * (1. - zoomDelta);

            setZoom(zoom);
        }
        else if(event->buttons().testFlag(Qt::LeftButton) == true)
        {
            // pan (move center coordinates)
            double centerX = centerX_ + 2.*delta.x() / zoom_;
            double centerY = centerY_ + 2.*delta.y() / zoom_;

            setCenter(centerX, centerY);
        }

        // force a redraw to update window info label
        update();
    }
}

void ContentWindowGraphicsItem::mousePressEvent(QGraphicsSceneMouseEvent * event)
{
    // on Mac we've seen that mouse events can go to the wrong graphics item
    // this is due to the bug: https://bugreports.qt.nokia.com/browse/QTBUG-20493
    // here we ignore the event if it shouldn't have been sent to us, which ensures
    // it will go to the correct item...
    if(boundingRect().contains(event->pos()) == false)
    {
        event->ignore();
        return;
    }

    // button dimensions
    float buttonWidth, buttonHeight;
    getButtonDimensions(buttonWidth, buttonHeight);

    // item rectangle and event position
    QRectF r = rect();
    QPointF eventPos = event->pos();

    // check to see if user clicked on the close button
    if(fabs((r.x()+r.width()) - eventPos.x()) <= buttonWidth && fabs((r.y()) - eventPos.y()) <= buttonHeight)
    {
        close();

        return;
    }

    // check to see if user clicked on the resize button
    if(fabs((r.x()+r.width()) - eventPos.x()) <= buttonWidth && fabs((r.y()+r.height()) - eventPos.y()) <= buttonHeight)
    {
        resizing_ = true;
    }

    // move to the front of the GUI display
    moveToFront();

    QGraphicsItem::mousePressEvent(event);
}

void ContentWindowGraphicsItem::mouseDoubleClickEvent(QGraphicsSceneMouseEvent * event)
{
    // on Mac we've seen that mouse events can go to the wrong graphics item
    // this is due to the bug: https://bugreports.qt.nokia.com/browse/QTBUG-20493
    // here we ignore the event if it shouldn't have been sent to us, which ensures
    // it will go to the correct item...
    if(boundingRect().contains(event->pos()) == false)
    {
        event->ignore();
        return;
    }

    bool selected = !selected_;

    setSelected(selected);

    QGraphicsItem::mouseDoubleClickEvent(event);
}

void ContentWindowGraphicsItem::mouseReleaseEvent(QGraphicsSceneMouseEvent * event)
{
    resizing_ = false;

    QGraphicsItem::mouseReleaseEvent(event);
}

void ContentWindowGraphicsItem::wheelEvent(QGraphicsSceneWheelEvent * event)
{
    // on Mac we've seen that mouse events can go to the wrong graphics item
    // this is due to the bug: https://bugreports.qt.nokia.com/browse/QTBUG-20493
    // here we ignore the event if it shouldn't have been sent to us, which ensures
    // it will go to the correct item...
    if(boundingRect().contains(event->pos()) == false)
    {
        event->ignore();
        return;
    }

    // handle wheel movements differently depending on selected mode of item
    if(selected_ == false)
    {
        // scale size based on wheel delta
        // typical delta value is 120, so scale based on that
        double factor = 1. + (double)event->delta() / (10. * 120.);

        scaleSize(factor);
    }
    else
    {
        // change zoom based on wheel delta
        // deltas are counted in 1/8 degrees. so, scale based on 180 degrees => delta = 180*8 = 1440
        double zoomDelta = (double)event->delta() / 1440.;
        double zoom = zoom_ * (1. + zoomDelta);

        setZoom(zoom);
    }
}
<|endoftext|>


<commit_before>/* Copyright (c) 2009-2012 Stanford University
 *
 * Permission to use, copy, modify, and 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(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS 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 "CoordinatorService.h"
#include "CoordinatorServiceRecovery.h"

namespace RAMCloud {

CoordinatorServiceRecovery::CoordinatorServiceRecovery(
        CoordinatorService& coordinatorService)
    : service(coordinatorService)
{
}

CoordinatorServiceRecovery::~CoordinatorServiceRecovery()
{
}

/**
 * Replay the LogCabin log, parse the log entries to extract the states,
 * and dispatch to the appropriate recovery methods in CoordinatorServerManger.
 */
void
CoordinatorServiceRecovery::replay(bool testing)
{
    // Get all the entries appended to the log.
    // TODO(ankitak): After ongaro has added curser API to LogCabin,
    // use that to read in one entry at a time.

    // Also, since LogCabin doesn't have a log cleaner yet, a read()
    // returns all entries, including those that were invalidated.
    // Thus, use the temporary workaround function,
    // LogCabinHelper::readValidEntries() that returns only valid entries.
    vector<Entry> entriesRead = service.logCabinHelper->readValidEntries();

    for (vector<Entry>::iterator it = entriesRead.begin();
            it < entriesRead.end(); it++) {

        EntryId entryId = it->getId();
        string entryType = service.logCabinHelper->getEntryType(*it);
        RAMCLOUD_LOG(DEBUG, "Entry Id: %lu, Entry Type: %s\n",
                             entryId, entryType.c_str());

        if (testing) continue;

        // Dispatch
        if (!entryType.compare("ServerEnlisted")) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerEnlisted");
            ProtoBuf::ServerInformation state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.serverList->recoverAliveServer(&state, entryId);

        } else if (!entryType.compare("AppendServerAlive")) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: AppendServerAlive");
            service.serverList->recoverAppendServerAlive(entryId);

        } else if (!entryType.compare("ServerEnlisting")) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerEnlisting");
            ProtoBuf::ServerInformation state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.serverList->recoverEnlistServer(&state, entryId);

        } else if (!entryType.compare("ServerCrashed")) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerCrashed");
            ProtoBuf::ServerCrashInfo state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.serverList->recoverServerCrashed(&state, entryId);

        } else if (!entryType.compare("ServerListVersion")) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerListVersion");
            ProtoBuf::ServerListVersion state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.serverList->recoverServerListVersion(&state, entryId);

        } else if (!entryType.compare("ServerNeedsRecovery")) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerNeedsRecovery");
            ProtoBuf::ServerCrashInfo state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.serverList->recoverServerNeedsRecovery(&state, entryId);

        } else if (!entryType.compare("ServerUpdate")) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerUpdate");
            ProtoBuf::ServerUpdate state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.serverList->recoverServerUpdate(&state, entryId);

        } else if (!entryType.compare("AliveTable")) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: AliveTable");
            ProtoBuf::TableInformation state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.tableManager->recoverAliveTable(&state, entryId);

        } else if (!entryType.compare("CreatingTable")) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: CreatingTable");
            ProtoBuf::TableInformation state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.tableManager->recoverCreateTable(&state, entryId);

        } else if (!entryType.compare("DroppingTable")) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: DroppingTable");
            ProtoBuf::TableDrop state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.tableManager->recoverDropTable(&state, entryId);

        } else if (!entryType.compare("SplitTablet")) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: SplitTablet");
            ProtoBuf::SplitTablet state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.tableManager->recoverSplitTablet(&state, entryId);

        } else if (!entryType.compare("TabletRecovered")) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: TabletRecovered");
            ProtoBuf::TabletRecovered state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.tableManager->recoverTabletRecovered(&state, entryId);

        } else {

            // Ignore, and continue.
            // There could be entries appended by processes other than the
            // Coordinator that we want to ignore.

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: Unknown type");
        }
    }
}

} // namespace RAMCloud
<commit_msg>Bug fix in Coordinator Recovery.<commit_after>/* Copyright (c) 2009-2012 Stanford University
 *
 * Permission to use, copy, modify, and 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(S) DISCLAIM ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS 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 "CoordinatorService.h"
#include "CoordinatorServiceRecovery.h"

namespace RAMCloud {

CoordinatorServiceRecovery::CoordinatorServiceRecovery(
        CoordinatorService& coordinatorService)
    : service(coordinatorService)
{
}

CoordinatorServiceRecovery::~CoordinatorServiceRecovery()
{
}

/**
 * Replay the LogCabin log, parse the log entries to extract the states,
 * and dispatch to the appropriate recovery methods in CoordinatorServerManger.
 */
void
CoordinatorServiceRecovery::replay(bool testing)
{
    // Get all the entries appended to the log.
    // TODO(ankitak): After ongaro has added curser API to LogCabin,
    // use that to read in one entry at a time.

    // Also, since LogCabin doesn't have a log cleaner yet, a read()
    // returns all entries, including those that were invalidated.
    // Thus, use the temporary workaround function,
    // LogCabinHelper::readValidEntries() that returns only valid entries.
    vector<Entry> entriesRead = service.logCabinHelper->readValidEntries();

    for (vector<Entry>::iterator it = entriesRead.begin();
            it < entriesRead.end(); it++) {

        EntryId entryId = it->getId();
        string entryType = service.logCabinHelper->getEntryType(*it);
        RAMCLOUD_LOG(DEBUG, "Entry Id: %lu, Entry Type: %s\n",
                             entryId, entryType.c_str());

        if (testing) continue;

        // Dispatch
        if (entryType.compare("ServerEnlisted") == 0) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerEnlisted");
            ProtoBuf::ServerInformation state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.serverList->recoverAliveServer(&state, entryId);

        } else if (entryType.compare("AppendServerAlive") == 0) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: AppendServerAlive");
            service.serverList->recoverAppendServerAlive(entryId);

        } else if (entryType.compare("ServerEnlisting") == 0) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerEnlisting");
            ProtoBuf::ServerInformation state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.serverList->recoverEnlistServer(&state, entryId);

        } else if (entryType.compare("ServerCrashed") == 0) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerCrashed");
            ProtoBuf::ServerCrashInfo state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.serverList->recoverServerCrashed(&state, entryId);

        } else if (entryType.compare("ServerListVersion") == 0) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerListVersion");
            ProtoBuf::ServerListVersion state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.serverList->recoverServerListVersion(&state, entryId);

        } else if (entryType.compare("ServerNeedsRecovery") == 0) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerNeedsRecovery");
            ProtoBuf::ServerCrashInfo state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.serverList->recoverServerNeedsRecovery(&state, entryId);

        } else if (entryType.compare("ServerUpdate") == 0) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: ServerUpdate");
            ProtoBuf::ServerUpdate state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.serverList->recoverServerUpdate(&state, entryId);

        } else if (entryType.compare("AliveTable") == 0) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: AliveTable");
            ProtoBuf::TableInformation state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.tableManager->recoverAliveTable(&state, entryId);

        } else if (entryType.compare("CreatingTable") == 0) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: CreatingTable");
            ProtoBuf::TableInformation state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.tableManager->recoverCreateTable(&state, entryId);

        } else if (entryType.compare("DroppingTable") == 0) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: DroppingTable");
            ProtoBuf::TableDrop state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.tableManager->recoverDropTable(&state, entryId);

        } else if (entryType.compare("SplitTablet") == 0) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: SplitTablet");
            ProtoBuf::SplitTablet state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.tableManager->recoverSplitTablet(&state, entryId);

        } else if (entryType.compare("TabletRecovered") == 0) {

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: TabletRecovered");
            ProtoBuf::TabletRecovered state;
            service.logCabinHelper->parseProtoBufFromEntry(*it, state);
            service.tableManager->recoverTabletRecovered(&state, entryId);

        } else {

            // Ignore, and continue.
            // There could be entries appended by processes other than the
            // Coordinator that we want to ignore.

            RAMCLOUD_LOG(DEBUG, "ServiceRecovery: Unknown type");
        }
    }
}

} // namespace RAMCloud
<|endoftext|>


<commit_before>#include <osg/Transform>
#include <osg/Billboard>
#include <osg/Geode>
#include <osg/Group>
#include <osg/Notify>
#include <osg/Material>
#include <osg/PolygonOffset>
#include <osg/PolygonMode>

#include <osgDB/Registry>
#include <osgDB/ReadFile>

#include <osgUtil/TrackballManipulator>
#include <osgUtil/FlightManipulator>
#include <osgUtil/DriveManipulator>

#include <osgGLUT/glut>
#include <osgGLUT/Viewer>

#include <osgUtil/Optimizer>

void write_usage(std::ostream& out,const std::string& name)
{
    out << std::endl;
    out <<"usage:"<< std::endl;
    out <<"    "<<name<<" [options] infile1 [infile2 ...]"<< std::endl;
    out << std::endl;
    out <<"options:"<< std::endl;
    out <<"    -l libraryName      - load plugin of name libraryName"<< std::endl;
    out <<"                          i.e. -l osgdb_pfb"<< std::endl;
    out <<"                          Useful for loading reader/writers which can load"<< std::endl;
    out <<"                          other file formats in addition to its extension."<< std::endl;
    out <<"    -e extensionName    - load reader/wrter plugin for file extension"<< std::endl;
    out <<"                          i.e. -e pfb"<< std::endl;
    out <<"                          Useful short hand for specifying full library name as"<< std::endl;
    out <<"                          done with -l above, as it automatically expands to"<< std::endl;
    out <<"                          the full library name appropriate for each platform."<< std::endl;
    out <<std::endl;
    out <<"    -stereo             - switch on stereo rendering, using the default of,"<< std::endl;
    out <<"                          ANAGLYPHIC or the value set in the OSG_STEREO_MODE "<< std::endl;
    out <<"                          environmental variable. See doc/stereo.html for "<< std::endl;
    out <<"                          further details on setting up accurate stereo "<< std::endl;
    out <<"                          for your system. "<< std::endl;
    out <<"    -stereo ANAGLYPHIC  - switch on anaglyphic(red/cyan) stereo rendering."<< std::endl;
    out <<"    -stereo QUAD_BUFFER - switch on quad buffered stereo rendering."<< std::endl;
    out <<std::endl;
    out <<"    -stencil            - use a visual with stencil buffer enabled, this "<< std::endl;
    out <<"                          also allows the depth complexity statistics mode"<< std::endl;
    out <<"                          to be used (press 'p' three times to cycle to it)."<< std::endl;
    out << std::endl;
}

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

    // initialize the GLUT
    glutInit( &argc, argv );

    if (argc<2)
    {
        write_usage(osg::notify(osg::NOTICE),argv[0]);
        return 0;
    }

    // create the commandline args.
    std::vector<std::string> commandLine;
    for(int i=1;i<argc;++i) commandLine.push_back(argv[i]);

    // initialize the viewer.
    osgGLUT::Viewer viewer;

    // configure the viewer from the commandline arguments, and eat any
    // parameters that have been matched.
    viewer.readCommandLine(commandLine);

    // configure the plugin registry from the commandline arguments, and
    // eat any parameters that have been matched.
    osgDB::readCommandLine(commandLine);

    // load the nodes from the commandline arguments.
    osg::Node* loadedModel = osgDB::readNodeFiles(commandLine);
    if (!loadedModel)
    {
        write_usage(osg::notify(osg::NOTICE),argv[0]);
        return 1;
    }

    // to do scribe mode we create a top most group to contain the
    // original model, and then a second group contains the same model
    // but overrides various state attributes, so that the second instance
    // is rendered as wireframe.

    osg::Group* rootnode = new osg::Group;

    osg::Group* decorator = new osg::Group;

    rootnode->addChild(loadedModel);

    rootnode->addChild(decorator);

    decorator->addChild(loadedModel);

    // set up the state so that the underlying color is not seen through
    // and that the drawing mode is changed to wireframe, and a polygon offset
    // is added to ensure that we see the wireframe itself, and turn off
    // so texturing too.
    osg::StateSet* stateset = new osg::StateSet;
    osg::Material* material = new osg::Material;
    osg::PolygonOffset* polyoffset = new osg::PolygonOffset;
    polyoffset->setFactor(-1.0f);
    polyoffset->setUnits(-1.0f);
    osg::PolygonMode* polymode = new osg::PolygonMode;
    polymode->setMode(osg::PolygonMode::FRONT_AND_BACK,osg::PolygonMode::LINE);
    stateset->setAttributeAndModes(material,osg::StateAttribute::OVERRIDE_ON);
    stateset->setAttributeAndModes(polyoffset,osg::StateAttribute::OVERRIDE_ON);
    stateset->setAttributeAndModes(polymode,osg::StateAttribute::OVERRIDE_ON);
    stateset->setMode(GL_TEXTURE_2D,osg::StateAttribute::OVERRIDE_OFF);
    decorator->setStateSet(stateset);

    // run optimization over the scene graph
    osgUtil::Optimizer optimzer;
// turn off temporarily since the above single child decorator group gets
// removed as the optimizer assumes its redundent.  Will fix next. Robert.
//    optimzer.optimize(rootnode);

    // add a viewport to the viewer and attach the scene graph.
    viewer.addViewport( rootnode );

    // register trackball, flight and drive.
    viewer.registerCameraManipulator(new osgUtil::TrackballManipulator);
    viewer.registerCameraManipulator(new osgUtil::FlightManipulator);
    viewer.registerCameraManipulator(new osgUtil::DriveManipulator);

    // open the viewer window.
    viewer.open();

    // fire up the event loop.
    viewer.run();

    return 0;
}
<commit_msg>Added stateset->setMode(GL_LIGHTING,osg::StateAttribute::OVERRIDE_ON); to scribbed subgraph so that lighting is always on, this is needed since glMaterial is only active when lighting is enabled.<commit_after>#include <osg/Transform>
#include <osg/Billboard>
#include <osg/Geode>
#include <osg/Group>
#include <osg/Notify>
#include <osg/Material>
#include <osg/PolygonOffset>
#include <osg/PolygonMode>

#include <osgDB/Registry>
#include <osgDB/ReadFile>

#include <osgUtil/TrackballManipulator>
#include <osgUtil/FlightManipulator>
#include <osgUtil/DriveManipulator>

#include <osgGLUT/glut>
#include <osgGLUT/Viewer>

#include <osgUtil/Optimizer>

void write_usage(std::ostream& out,const std::string& name)
{
    out << std::endl;
    out <<"usage:"<< std::endl;
    out <<"    "<<name<<" [options] infile1 [infile2 ...]"<< std::endl;
    out << std::endl;
    out <<"options:"<< std::endl;
    out <<"    -l libraryName      - load plugin of name libraryName"<< std::endl;
    out <<"                          i.e. -l osgdb_pfb"<< std::endl;
    out <<"                          Useful for loading reader/writers which can load"<< std::endl;
    out <<"                          other file formats in addition to its extension."<< std::endl;
    out <<"    -e extensionName    - load reader/wrter plugin for file extension"<< std::endl;
    out <<"                          i.e. -e pfb"<< std::endl;
    out <<"                          Useful short hand for specifying full library name as"<< std::endl;
    out <<"                          done with -l above, as it automatically expands to"<< std::endl;
    out <<"                          the full library name appropriate for each platform."<< std::endl;
    out <<std::endl;
    out <<"    -stereo             - switch on stereo rendering, using the default of,"<< std::endl;
    out <<"                          ANAGLYPHIC or the value set in the OSG_STEREO_MODE "<< std::endl;
    out <<"                          environmental variable. See doc/stereo.html for "<< std::endl;
    out <<"                          further details on setting up accurate stereo "<< std::endl;
    out <<"                          for your system. "<< std::endl;
    out <<"    -stereo ANAGLYPHIC  - switch on anaglyphic(red/cyan) stereo rendering."<< std::endl;
    out <<"    -stereo QUAD_BUFFER - switch on quad buffered stereo rendering."<< std::endl;
    out <<std::endl;
    out <<"    -stencil            - use a visual with stencil buffer enabled, this "<< std::endl;
    out <<"                          also allows the depth complexity statistics mode"<< std::endl;
    out <<"                          to be used (press 'p' three times to cycle to it)."<< std::endl;
    out << std::endl;
}

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

    // initialize the GLUT
    glutInit( &argc, argv );

    if (argc<2)
    {
        write_usage(osg::notify(osg::NOTICE),argv[0]);
        return 0;
    }

    // create the commandline args.
    std::vector<std::string> commandLine;
    for(int i=1;i<argc;++i) commandLine.push_back(argv[i]);

    // initialize the viewer.
    osgGLUT::Viewer viewer;

    // configure the viewer from the commandline arguments, and eat any
    // parameters that have been matched.
    viewer.readCommandLine(commandLine);

    // configure the plugin registry from the commandline arguments, and
    // eat any parameters that have been matched.
    osgDB::readCommandLine(commandLine);

    // load the nodes from the commandline arguments.
    osg::Node* loadedModel = osgDB::readNodeFiles(commandLine);
    if (!loadedModel)
    {
        write_usage(osg::notify(osg::NOTICE),argv[0]);
        return 1;
    }

    // to do scribe mode we create a top most group to contain the
    // original model, and then a second group contains the same model
    // but overrides various state attributes, so that the second instance
    // is rendered as wireframe.

    osg::Group* rootnode = new osg::Group;

    osg::Group* decorator = new osg::Group;

    rootnode->addChild(loadedModel);

    rootnode->addChild(decorator);

    decorator->addChild(loadedModel);

    // set up the state so that the underlying color is not seen through
    // and that the drawing mode is changed to wireframe, and a polygon offset
    // is added to ensure that we see the wireframe itself, and turn off
    // so texturing too.
    osg::StateSet* stateset = new osg::StateSet;
    osg::Material* material = new osg::Material;
    osg::PolygonOffset* polyoffset = new osg::PolygonOffset;
    polyoffset->setFactor(-1.0f);
    polyoffset->setUnits(-1.0f);
    osg::PolygonMode* polymode = new osg::PolygonMode;
    polymode->setMode(osg::PolygonMode::FRONT_AND_BACK,osg::PolygonMode::LINE);
    stateset->setAttributeAndModes(material,osg::StateAttribute::OVERRIDE_ON);
    stateset->setAttributeAndModes(polyoffset,osg::StateAttribute::OVERRIDE_ON);
    stateset->setAttributeAndModes(polymode,osg::StateAttribute::OVERRIDE_ON);
    stateset->setMode(GL_TEXTURE_2D,osg::StateAttribute::OVERRIDE_OFF);
    stateset->setMode(GL_LIGHTING,osg::StateAttribute::OVERRIDE_ON);
    decorator->setStateSet(stateset);

    // run optimization over the scene graph
    osgUtil::Optimizer optimzer;
// turn off temporarily since the above single child decorator group gets
// removed as the optimizer assumes its redundent.  Will fix next. Robert.
//    optimzer.optimize(rootnode);

    // add a viewport to the viewer and attach the scene graph.
    viewer.addViewport( rootnode );

    // register trackball, flight and drive.
    viewer.registerCameraManipulator(new osgUtil::TrackballManipulator);
    viewer.registerCameraManipulator(new osgUtil::FlightManipulator);
    viewer.registerCameraManipulator(new osgUtil::DriveManipulator);

    // open the viewer window.
    viewer.open();

    // fire up the event loop.
    viewer.run();

    return 0;
}
<|endoftext|>


<commit_before>/*
@file remove_noexcept

@Copyright Barrett Adair 2015-2017
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)

*/

#ifndef BOOST_CLBL_TRTS_REMOVE_NOEXCEPT_HPP
#define BOOST_CLBL_TRTS_REMOVE_NOEXCEPT_HPP

#include <boost/callable_traits/detail/core.hpp>

namespace boost { namespace callable_traits {

BOOST_CLBL_TRTS_DEFINE_SFINAE_ERROR_ORIGIN(remove_noexcept)
BOOST_CLBL_TRTS_SFINAE_MSG(remove_noexcept, cannot_remove_noexcept_from_this_type)

//[ remove_noexcept_hpp
/*`
[section:ref_remove_noexcept remove_noexcept]
[heading Header]
``#include <boost/callable_traits/remove_noexcept.hpp>``
[heading Definition]
*/

template<typename T>
using remove_noexcept_t = //see below
//<-
    detail::try_but_fail_if_invalid<
        typename detail::traits<T>::remove_noexcept,
        cannot_remove_noexcept_from_this_type>;

namespace detail {

    template<typename T, typename = std::false_type>
    struct remove_noexcept_impl {};

    template<typename T>
    struct remove_noexcept_impl <T, typename std::is_same<
        remove_noexcept_t<T>, detail::dummy>::type>
    {
        using type = remove_noexcept_t<T>;
    };
}

//->

template<typename T>
struct remove_noexcept : detail::remove_noexcept_impl<T> {};

//<-
}} // namespace boost::callable_traits
//->

/*`

[heading Constraints]
* `T` must be one of the following:
  * function type
  * function pointer type
  * function reference type
  * member function pointer type
* If `T` is a pointer, it may not be cv/ref qualified

[heading Behavior]
* A substitution failure occurs if the constraints are violated.
* Removes the `noexcept` specifier from `T`, if present.

[heading Input/Output Examples]
[table
    [[`T`]                              [`remove_noexcept_t<T>`]]
    [[`int() const noexcept`]           [`int() const`]]
    [[`int(*)() noexcept`]              [`int(*)()`]]
    [[`int(&)() noexcept`]              [`int(&)()`]]
    [[`int(foo::*)() noexcept`]         [`int(foo::*)()`]]
    [[`int() const`]                    [`int() const`]]
    [[`int(*)()`]                       [`int(*)()`]]
    [[`int(&)()`]                       [`int(&)()`]]
    [[`int`]                            [(substitution failure)]]
    [[`int foo::*`]                     [(substitution failure)]]
    [[`int (foo::* const)()`]           [(substitution failure)]]
]

[heading Example Program]
[import ../example/remove_noexcept.cpp]
[remove_noexcept]
[endsect]
*/
//]

#endif // #ifndef BOOST_CLBL_TRTS_REMOVE_NOEXCEPT_HPP
<commit_msg>Delete remove_noexcept.hpp<commit_after><|endoftext|>


<commit_before>
AliAnalysisTaskCaloTrackCorrelation *AddTaskPi0EMCALPbPb(
                                                         const TString data          = "AOD",
                                                         const TString calorimeter   = "EMCAL",
                                                         const Bool_t  printSettings = kFALSE,
                                                         const Bool_t  simulation    = kFALSE,
                                                         const Bool_t  outputAOD     = kFALSE,
                                                         const TString outputfile    = "",
                                                         const Int_t   year          = 2011,
                                                         const TString col           = "PbPb",
                                                         const TString trig          = "",
                                                         const TString clustersArray = ""
                                                        )
{
  // Creates a PartCorr task, configures it and adds it to the analysis manager.

  // Get the pointer to the existing analysis manager via the static access method.

  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    ::Error("AddTask", "No analysis manager to connect to.");
    return NULL;
  }

  // Check the analysis type using the event handlers connected to the analysis manager.

  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTask", "This task requires an input event handler");
    return NULL;
  }
  Bool_t kInputDataType = "AOD";
  if(!data.Contains("delta"))
    kInputDataType = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"

  Bool_t kUseKinematics = kFALSE;
  if(simulation) {
    kUseKinematics = (mgr->GetMCtruthEventHandler())?kTRUE:kFALSE;
    if (!kUseKinematics && data=="AOD" && kInputDataType != "ESD") kUseKinematics = kTRUE; //AOD primary should be available ...
  }

  //cout<<"********* ACCESS KINE? "<<kUseKinematics<<endl;

  // #### Configure analysis ####

  AliAnaPartCorrMaker * maker = new AliAnaPartCorrMaker();

  // General frame setting and configuration
  maker->SetReader   (ConfigureReader(data,kInputDataType,calorimeter,clustersArray,col,outputAOD,kUseKinematics,printSettings)   );
  maker->SetCaloUtils(ConfigureCaloUtils(year,col,clustersArray, simulation, printSettings));

  // Analysis tasks setting and configuration
  Int_t n = 0;//Analysis number, order is important
  maker->AddAnalysis(ConfigurePhotonAnalysis(data,calorimeter,year,col,clustersArray,simulation,"",printSettings), n++); // Photon cluster selection
  maker->AddAnalysis(ConfigurePi0Analysis   (data,calorimeter,year,col,clustersArray,simulation,"",printSettings), n++); // Pi0 invariant mass analysis

  maker->SetAnaDebug(-1)  ;
  maker->SwitchOnHistogramsMaker()  ;
  if(data.Contains("delta")) maker->SwitchOffAODsMaker() ;
  else                       maker->SwitchOnAODsMaker()  ;

  if(printSettings) maker->Print("");

  //printf("<< End Configuration of %d analysis for calorimeter %s >>\n",n, calorimeter.Data());

  // Create task

  AliAnalysisTaskCaloTrackCorrelation * task = new AliAnalysisTaskCaloTrackCorrelation (Form("PartCorr%s_Trig%s_Cl%s",calorimeter.Data(),trig.Data(),clustersArray.Data()));
  task->SetConfigFileName(""); //Don't configure the analysis via configuration file.
  //task->SetDebugLevel(-1);
  task->SetBranches("ESD:AliESDRun.,AliESDHeader"); //just a trick to get Constantin's analysis to work
  task->SetAnalysisMaker(maker);
  mgr->AddTask(task);

  //Create containers

  if(outputfile.Length()==0)outputfile = AliAnalysisManager::GetCommonFileName();
  TString name(Form("%s_Trig%s_Cl%s",calorimeter.Data(),trig.Data(),clustersArray.Data()));
  AliAnalysisDataContainer *cout_pc   = mgr->CreateContainer(name.Data(), TList::Class(),
                                                             AliAnalysisManager::kOutputContainer,
                                                             Form("%s:%s",outputfile.Data(),name.Data()));

  AliAnalysisDataContainer *cout_cuts = mgr->CreateContainer(Form("%sCuts",name.Data()), TList::Class(),
                                                             AliAnalysisManager::kParamContainer,
                                                             Form("%s:%sCuts",outputfile.Data(),name.Data()));

  // Create ONLY the output containers for the data produced by the task.
  // Get and connect other common input/output containers via the manager as below
  //==============================================================================
  mgr->ConnectInput  (task, 0, mgr->GetCommonInputContainer());
  // AOD output slot will be used in a different way in future
  if(!data.Contains("delta")   && outputAOD) mgr->ConnectOutput (task, 0, mgr->GetCommonOutputContainer());
  mgr->ConnectOutput (task, 1, cout_pc);
  mgr->ConnectOutput (task, 2, cout_cuts);

  return task;
}

//____________________________________
AliCaloTrackReader * ConfigureReader(TString kData,TString kInputDataType, TString kCalorimeter,
                                     TString kClusterArray, TString kCollisions,
                                     Bool_t kOutputAOD, Bool_t kUseKinematics, Bool_t kPrint)
{

  AliCaloTrackReader * reader = 0;
  if     (kData.Contains("AOD"))   reader = new AliCaloTrackAODReader();
  else if(kData=="ESD")            reader = new AliCaloTrackESDReader();
  else if(kData=="MC" &&
          kInputDataType == "ESD") reader = new AliCaloTrackMCReader();

  reader->SetDebug(-1);//10 for lots of messages

  //Delta AOD?
  //reader->SetDeltaAODFileName("");
  if(kOutputAOD) reader->SwitchOnWriteDeltaAOD()  ;

  // MC settings
  if(kUseKinematics){
    if(kInputDataType == "ESD"){
      reader->SwitchOnStack();
      reader->SwitchOffAODMCParticles();
    }
    else if(kInputDataType == "AOD"){
      reader->SwitchOffStack();
      reader->SwitchOnAODMCParticles();
    }
  }

  //------------------------
  // Detector input filling
  //------------------------

  //Min cluster/track E
  reader->SetEMCALEMin(0.5);
  reader->SetEMCALEMax(1000);
  reader->SetPHOSEMin(0.3);
  reader->SetPHOSEMax(1000);
  reader->SetCTSPtMin(0.1);
  reader->SetCTSPtMax(1000);

  reader->SwitchOffFiducialCut();

  // Tracks
  reader->SwitchOffCTS();

  // Calorimeter

  reader->SetEMCALClusterListName(kClusterArray);
  if(kClusterArray == "") {
    //printf("**************** Normal analysis **************** \n");
    reader->SwitchOnClusterRecalculation(); // Bad map removal
  }
  else {
    printf("**************** Input for analysis is Clusterizer %s **************** \n", kClusterArray.Data());
    reader->SwitchOffClusterRecalculation();
  }

  if(kCalorimeter == "EMCAL") {
    reader->SwitchOnEMCALCells();
    reader->SwitchOnEMCAL();
  }
  if(kCalorimeter == "PHOS") {
    reader->SwitchOnPHOSCells();
    reader->SwitchOnPHOS();
  }

  // for case data="deltaAOD", no need to fill the EMCAL/PHOS cluster lists
  if(kData.Contains("delta")){
    reader->SwitchOffEMCAL();
    reader->SwitchOffPHOS();
    reader->SwitchOffEMCALCells();
    reader->SwitchOffPHOSCells();
  }

  //-----------------
  // Event selection
  //-----------------

  //if(!kUseKinematics) reader->SetFiredTriggerClassName("CEMC7EGA-B-NOPF-CENTNOTRD"); // L1 Gamma

  if     (kCollisions=="pp"  ) {
    reader->SwitchOffPileUpEventRejection();   // remove pileup by default
    reader->SwitchOffV0ANDSelection() ;        // and besides v0 AND
    reader->SwitchOffPrimaryVertexSelection(); // and besides primary vertex
    reader->SetZvertexCut(50.);                // Open cut
  }
  else if(kCollisions=="PbPb") {
    reader->SwitchOffPileUpEventRejection();   // remove pileup by default
    reader->SwitchOffV0ANDSelection() ;        // and besides v0 AND
    reader->SwitchOffPrimaryVertexSelection(); // and besides primary vertex
    reader->SetZvertexCut(10.);                // Centrality defined in this range.

    // Centrality
    reader->SetCentralityClass("V0M");
    reader->SetCentralityOpt(10);  // 10 centrality bins
    reader->SetCentralityBin(-1,-1); // Accept all events, if not select range

    // Event plane (only used in AliAnaPi0 for the moment)
    reader->SetEventPlaneMethod("Q");
  }

  if(kPrint) reader->Print("");

  return reader;

}

//_______________________________________
AliCalorimeterUtils* ConfigureCaloUtils(Int_t kYears, TString kCollisions, TString kClusterArray,
                                        Bool_t kSimulation, Bool_t kPrint)
{

  AliCalorimeterUtils *cu = new AliCalorimeterUtils;
  cu->SetDebug(-1);

  if(kYears==2010) cu->SetEMCALGeometryName("EMCAL_FIRSTYEARV1");
  else             cu->SetEMCALGeometryName("EMCAL_COMPLETEV1");

  // Remove clusters close to borders, at least max energy cell is 1 cell away
  cu->SetNumberOfCellsFromEMCALBorder(1);
  cu->SetNumberOfCellsFromPHOSBorder(2);

  //if(kClusterArray == "")
  //  cu->SwitchOffRecalculateClusterTrackMatching(); // Done in clusterization
  //else
  //  cu->SwitchOnRecalculateClusterTrackMatching();

  //EMCAL only settings
  AliEMCALRecoUtils * recou = cu->GetEMCALRecoUtils();

  if(kCollisions=="pp"  ) { // Do only for pp for the moment
    cu->SwitchOnCorrectClusterLinearity();
    if(!kSimulation) recou->SetNonLinearityFunction(AliEMCALRecoUtils::kBeamTestCorrected);
    else             recou->SetNonLinearityFunction(AliEMCALRecoUtils::kPi0MC);
  }

  recou->SwitchOnRejectExoticCell();
  if(kClusterArray == "") recou->SwitchOnRejectExoticCluster();
  else                    recou->SwitchOffRejectExoticCluster();

  if(kCalorimeter=="PHOS")
  {
    if (kYears <  2014) cu->SetNumberOfSuperModulesUsed(3);
    else                cu->SetNumberOfSuperModulesUsed(4);
  }
  else
  {
    if      (kYears == 2010) cu->SetNumberOfSuperModulesUsed(4); //EMCAL first year
    else if (kYears <  2014) cu->SetNumberOfSuperModulesUsed(10);
    else                     cu->SetNumberOfSuperModulesUsed(20);
  }

  if(kPrint) cu->Print("");

  return cu;

}

//_____________________________________
AliAnaPhoton* ConfigurePhotonAnalysis(TString kData, TString kCalorimeter, Int_t kYears, TString kCollisions, TString kClusterArray,
                                      Bool_t kSimulation, TString kTrig = "", Bool_t kPrint)
{

  AliAnaPhoton *anaphoton = new AliAnaPhoton();
  anaphoton->SetDebug(-1); //10 for lots of messages

  // cluster selection cuts

  anaphoton->SwitchOffFiducialCut();

  anaphoton->SetCalorimeter(kCalorimeter);

  if(kCalorimeter == "PHOS"){
    anaphoton->SetNCellCut(2);// At least 2 cells
    anaphoton->SetMinPt(0.3);
    anaphoton->SetMinDistanceToBadChannel(2, 4, 5);
  }
  else {//EMCAL
    anaphoton->SetNCellCut(1);// At least 2 cells
    anaphoton->SetMinPt(0.5); // avoid mip peak at E = 260 MeV
    anaphoton->SetMaxPt(1000);
    anaphoton->SetTimeCut(-1000,1000); // open cut, usual time window of [425-825] ns if time recalibration is off
    anaphoton->SetMinDistanceToBadChannel(1, 2, 3); // For filtered AODs, new releases.
  }

  anaphoton->SwitchOnTrackMatchRejection() ;

  //PID cuts (shower shape)
  anaphoton->SwitchOnCaloPID(); // do PID selection, unless specified in GetCaloPID, selection not based on bayesian
  AliCaloPID* caloPID = anaphoton->GetCaloPID();
  //Not used in bayesian

  //EMCAL
  caloPID->SetEMCALLambda0CutMax(0.30);
  caloPID->SetEMCALLambda0CutMin(0.10);

  caloPID->SetEMCALDEtaCut(0.025);
  caloPID->SetEMCALDPhiCut(0.05);
  // In case of official AODs when dX and dZ was not stored, open the cuts
  // and rely on having a match recorded. In case of reclusterization, try.
  if(kData=="AOD" && kClusterArray==""){
    caloPID->SetEMCALDEtaCut(2000);
    caloPID->SetEMCALDPhiCut(2000);
  }

  //PHOS
  caloPID->SetPHOSDispersionCut(2.5);
  caloPID->SetPHOSRCut(2.);
  if(kData=="AOD") caloPID->SetPHOSRCut(2000.); // Open cut since dX, dZ not stored

  if(kCalorimeter=="PHOS"){
    caloPID->SetHistoDEtaRangeAndNBins(-200, 200, 200); // dZ
    caloPID->SetHistoDPhiRangeAndNBins(-200, 200, 200); // dX
  }

  //caloPID->SetTOFCut(10000000); // Not used, only to set PID bits

  anaphoton->SwitchOffFillShowerShapeHistograms();  // Filled before photon shower shape selection

  // Input / output delta AOD settings

  if(!kData.Contains("delta")) {
    anaphoton->SetOutputAODName(Form("Photon%s_Trig%s_Cl%s",kCalorimeter.Data(), kTrig.Data(),kClusterArray.Data()));
    anaphoton->SetOutputAODClassName("AliAODPWG4ParticleCorrelation");
    //anaphoton->SetOutputAODClassName("AliAODPWG4Particle"); // use if no correlation done
  }
  else anaphoton->SetInputAODName(Form("Photon%s_Trig%s_Cl%s",kCalorimeter.Data(), kTrig.Data(),kClusterArray.Data()));

  //Set Histograms name tag, bins and ranges

  anaphoton->AddToHistogramsName("AnaPhoton_");
  SetHistoRangeAndNBins(anaphoton); // see method below

  // Number of particle type MC histograms
  anaphoton->FillNOriginHistograms(8);
  anaphoton->FillNPrimaryHistograms(4);

  if(kPrint) anaphoton->Print("");

  return anaphoton;

}

//_______________________________
AliAnaPi0* ConfigurePi0Analysis(TString kData, TString kCalorimeter, Int_t kYears, TString kCollisions, TString kClusterArray,
                                Bool_t kSimulation, TString kTrig = "", Bool_t kPrint)
{

  AliAnaPi0 *anapi0 = new AliAnaPi0();

  anapi0->SetDebug(-1);//10 for lots of messages
  if(kPrint) anapi0->Print("");

  // Input delta AOD settings
  anapi0->SetInputAODName(Form("Photon%s_Trig%s_Cl%s",kCalorimeter.Data(), kTrig.Data(),kClusterArray.Data()));

  // Calorimeter settings
  anapi0->SetCalorimeter(kCalorimeter);

  //settings for pp collision mixing
  anapi0->SwitchOnOwnMix(); //Off when mixing done with general mixing frame

  // Cuts
  if(kCalorimeter=="EMCAL") anapi0->SetPairTimeCut(70);

  if     (kCollisions=="pp"  ) {
    printf("****** Configure Pi0 for pp analysis\n");
    anapi0->SetNCentrBin(1);
    anapi0->SetNZvertBin(10);
    anapi0->SetNRPBin(1);
    anapi0->SetNMaxEvMix(100);
  }
  else if(kCollisions=="PbPb") {
    printf("****** Configure Pi0 for PbPb analysis\n");
    anapi0->SetNCentrBin(5);
    anapi0->SetNZvertBin(3);
    anapi0->SetNRPBin(1);
    anapi0->SetNMaxEvMix(5);
  }

  anapi0->SwitchOffMultipleCutAnalysis();
  anapi0->SwitchOffSMCombinations();

  //Set Histograms name tag, bins and ranges

  anapi0->AddToHistogramsName("AnaPi0_");
  SetHistoRangeAndNBins(anapi0, kCalorimeter, kYears, kCollisions, kSimulation); // see method below

  return anapi0;

}

//________________________________________________________
void SetHistoRangeAndNBins (AliAnaPartCorrBaseClass* ana, TString kCalorimeter,
                            Int_t kYears, TString kCollisions, Bool_t kSimulation)
{
  // Set common bins for all analysis and MC histograms filling

  if(kSimulation) ana->SwitchOnDataMC() ;//Access MC stack and fill more histograms, AOD MC not implemented yet.
  else            ana->SwitchOffDataMC() ;

  ana->SetHistoPtRangeAndNBins(0, 100, 250) ; // Energy and pt histograms

  if(kCalorimeter=="EMCAL"){
    if(kYears==2010){
      ana->SetHistoPhiRangeAndNBins(78*TMath::DegToRad(), 122*TMath::DegToRad(), 78) ;
      ana->SetHistoXRangeAndNBins(-230,90,120); // QA
      ana->SetHistoYRangeAndNBins(370,450,40);  // QA
    }
    else {
      ana->SetHistoPhiRangeAndNBins(78*TMath::DegToRad(), 182*TMath::DegToRad(), 108) ;
      ana->SetHistoXRangeAndNBins(-600,90,200); // QA
      ana->SetHistoYRangeAndNBins(100,450,100); // QA
    }

    ana->SetHistoEtaRangeAndNBins(-0.72, 0.72, 144) ;
  }
  else{
    ana->SetHistoPhiRangeAndNBins(260*TMath::DegToRad(), 320*TMath::DegToRad(), 60) ;
    ana->SetHistoEtaRangeAndNBins(-0.13, 0.13, 130) ;

  }

  ana->SetHistoShowerShapeRangeAndNBins(0, 3, 300);

  // Invariant mass analysis
  ana->SetHistoMassRangeAndNBins(0., 1., 200) ;
  ana->SetHistoAsymmetryRangeAndNBins(0., 1. , 100) ;

  // check if time calibration is on
  ana->SetHistoTimeRangeAndNBins(-1000.,1000,1000);
  ana->SetHistoDiffTimeRangeAndNBins(-200, 200, 800);

  // QA, electron, charged
  ana->SetHistoPOverERangeAndNBins(0,10.,100);
  ana->SetHistodEdxRangeAndNBins(0.,200.,200);

  // QA
  ana->SetHistoFinePtRangeAndNBins(0, 10, 200) ; // bining for fhAmpId
  ana->SetHistodRRangeAndNBins(0.,TMath::Pi(),150);
  ana->SetHistoRatioRangeAndNBins(0.,2.,100);
  ana->SetHistoVertexDistRangeAndNBins(0.,500.,500);
  ana->SetHistoNClusterCellRangeAndNBins(0,500,500);
  ana->SetHistoZRangeAndNBins(-400,400,200);
  ana->SetHistoRRangeAndNBins(400,450,25);
  ana->SetHistoV0SignalRangeAndNBins(0,5000,500);
  ana->SetHistoV0MultiplicityRangeAndNBins(0,5000,500);
  ana->SetHistoTrackMultiplicityRangeAndNBins(0,5000,500);

}

<commit_msg>remove unused<commit_after><|endoftext|>


<commit_before>/*
 * Super Entity Game Server Project
 * http://segs.sf.net/
 * Copyright (c) 2006 Super Entity Game Server Team (see Authors.txt)
 * This software is licensed! (See License.txt for details)
 *
 * $Id$
 */
#define _USE_MATH_DEFINES
#include <cmath>
#include "types.h"
#include "Events/InputState.h"
#include "Entity.h"
void InputState::serializeto(BitStream &) const
{
    assert(!"Not implemented");
}

void InputState::partial_2(BitStream &bs)
{
    uint8_t control_id;
    //uint16_t v6;
    uint16_t time_since_prev;
    int v;
    do
    {
        if(bs.GetBits(1))
            control_id=8;
        else
            control_id=bs.GetBits(4);

        if(bs.GetBits(1)) //
            time_since_prev=bs.GetBits(2)+32;
        else
            time_since_prev=bs.GetBits(m_csc_deltabits);
        switch(control_id)
        {
            case 0: case 1: case 2:
            case 3: case 4: case 5:
                // field_38 bits , control_id is the number of the bit
                fprintf(stderr,"CtrlId %d  : %d - ",control_id,time_since_prev);
                v = bs.GetBits(1);
                fprintf(stderr,"P2[%d]:%d\n",control_id,v);
                break;
            case 6:
            case 7:
            {
                v = bs.GetBits(11);
                // v = (x+pi)*(2048/2pi)
                // x = (v*(pi/1024))-pi
                float recovered = (float(v)/2048.0f)*(2*M_PI) - M_PI;
                fprintf(stderr,"Pyr %f : %f \n",camera_pyr.x,camera_pyr.y);
                if(control_id==6) //TODO: use camera_pyr.v[] here ?
                    camera_pyr.x = recovered;
                else
                    camera_pyr.y = recovered;
                break;
            }
            case 8:
                v = bs.GetBits(1);
//                fprintf(stderr,"\tCTRL_8[%d] ",v);
                if ( m_send_deltas )
                {
                    m_t1=bs.GetPackedBits(8);
                    m_t2=bs.GetPackedBits(8);
                }
                else
                {
                    m_send_deltas = true;
                    m_t1=bs.GetBits(32);
                    m_t2=bs.GetPackedBits(10);
                }
//                fprintf(stderr,"[%d, ",t1);
//                fprintf(stderr,",%d] ",t2);
                if(bs.GetBits(1))
                {
                    v=bs.GetBits(8);
//                    fprintf(stderr,"CTRL_8C[%d] ",v);
//                    fprintf(stderr,"P2_8_opt : %d\n",v);
                }
                break;
            case 9:
                 //a2->timerel_18
                //fprintf(stderr,"CtrlId %d  : %d - ",control_id,time_since_prev);
                fprintf(stderr,"%d\n",bs.GetBits(8));
                break;
            case 10:
                fprintf(stderr,"CtrlId %d  : %d - ",control_id,time_since_prev);
                fprintf(stderr,"%d\n",bs.GetBits(1)); //a2->timerel_18 & 1
                break;
            default:
                assert(!"Unknown control_id");
        }

    } while(bs.GetBits(1));
}

void InputState::extended_input(BitStream &bs)
{
    if(bs.GetBits(1)) // list of partial_2 follows
    {
        m_csc_deltabits=bs.GetBits(5) + 1; // number of bits in max_time_diff_ms
        someOtherbits = bs.GetBits(16);//ControlStateChange::field_8 or OptRel::field_19A8
        current_state_P = 0;
#ifdef DEBUG_INPUT
        fprintf(stderr,"CSC_DELTA[%x-%x] : ",m_csc_deltabits,someOtherbits);
#endif
        partial_2(bs);

    }
    controlBits = 0;
    for(int idx=0; idx<6; ++idx)
        controlBits |= (bs.GetBits(1))<<idx;
#ifdef DEBUG_INPUT
    fprintf(stderr,"E input %x : ",controlBits);
#endif
    if(bs.GetBits(1))//if ( abs(s_prevTime - ms_time) < 1000 )
    {
        m_A_ang11_propably = bs.GetBits(11);//pak->SendBits(11, control_state.field_1C[0]);
        m_B_ang11_propably = bs.GetBits(11);//pak->SendBits(11, control_state.field_1C[1]);
#ifdef DEBUG_INPUT
        fprintf(stderr,"%x : %x",v1,v2);
#endif
    }
}
struct ControlState
{
    int field0;
    int time_res;
    float timestep;
    float time_rel1C;
    uint64_t m_perf_cntr_diff;
    uint64_t m_perf_freq_diff;
    // recover actual ControlState from network data and previous entry
    void serializefrom_delta(BitStream &bs,const ControlState &prev)
    {
        field0   = bs.GetPackedBits(1); // field_0 diff next-current
        time_res = bs.GetPackedBits(1); // time to next state ?
        timestep = bs.GetFloat(); // next state's timestep

        time_rel1C = timestep;
        if(bs.GetBits(1)) //timestep!=time_rel1C
            time_rel1C = bs.GetFloat();

        m_perf_cntr_diff = bs.Get64Bits(); //next_state->ticks - current_state->ticks
        if(bs.GetBits(1))
        {
            // perf freq changed between current and next
            m_perf_freq_diff = bs.Get64Bits();
        }
    }
    void serializefrom_base(BitStream &bs)
    {
        field0   = bs.GetBits(32); //field_0
        time_res = bs.GetBits(32); // get_time_resl
        timestep = bs.GetFloat(); //v7->timestep

        time_rel1C = timestep;
        if(bs.GetBits(1)) //timestep!=time_rel1C
            time_rel1C = bs.GetFloat();

        m_perf_cntr_diff = bs.Get64Bits(); //next_state->ticks - current_state->ticks
        m_perf_cntr_diff = bs.Get64Bits(); //v7->perf_cntr1
    }
    void dump()
    {
#ifdef DEBUG_INPUT
        fprintf(stderr,"CSC: %d,%d, [%f,%f]",field0,time_res,timestep,time_rel1C);
        fprintf(stderr, "(%lld %lld)",m_perf_cntr_diff,m_perf_freq_diff);
#endif
    }
};
void InputState::serializefrom(BitStream &bs)
{
    m_send_deltas=false;
#ifdef DEBUG_INPUT
    fprintf(stderr,"I:");
#endif
    if(bs.GetBits(1))
        extended_input(bs);

    bool has_targeted_entity = bs.GetBits(1);
    int tgt_idx=bs.GetPackedBits(14); // targeted entity server index
    int ctrl_idx=0;
#ifdef DEBUG_INPUT
    fprintf(stderr,"T:[%d]",has_targeted_entity);
    fprintf(stderr,"TI:[%d]",tgt_idx);
#endif
    ControlState prev_fld;
    while(bs.GetBits(1)) // receive control state array entries ?
    {
        ControlState fld;
        if(ctrl_idx)
        {
            fld.serializefrom_delta(bs,prev_fld);
        }
        else // initial values
        {
            fld.serializefrom_base(bs);
        }
        fld.dump();
        prev_fld = fld;
        ctrl_idx++;
    }
    recv_client_opts(bs); // g_pak contents will follow
#ifdef DEBUG_INPUT
    fprintf(stderr,"\n");
#endif
}
//TODO: use generic ReadableStructures here ?
void InputState::recv_client_opts(BitStream &bs)
{
    ClientOptions opts;
    ClientOption *entry;
    int opt_idx=0;
    int some_idx = bs.GetPackedBits(1);
    entry=opts.get(opt_idx);
    Vector3 vec;
    while(some_idx!=0)
    {
        for(size_t i=0; i<entry->m_args.size(); i++)
        {
            ClientOption::Arg &arg=entry->m_args[i];
            switch ( arg.type )
            {
                case ClientOption::t_int:
                {
                    *((int32_t *)arg.tgt) = bs.GetPackedBits(1);
                    break;
                }
                case ClientOption::t_float:
                {
                    *((float *)arg.tgt)=bs.GetFloat();
                    break;
                }
                case 5:
                {
                    printf("Quant:%d\n",bs.GetBits(14)); //quantized angle
                    break;
                }
                case ClientOption::t_string:
                case 4:
                {
                    std::string v;
                    bs.GetString(v);
                    break;
                }
                case 7:
                {
                    for (int j = 0; j < 3; ++j )
                    {
                        vec.v[j] = bs.GetFloat();
                    }
                    break;
                }
                default:
                    continue;
            }
        }
        some_idx = bs.GetPackedBits(1);
        opt_idx++;
        entry=opts.get(opt_idx);
    }
}

<commit_msg>Added correct dumping of received control events<commit_after>/*
 * Super Entity Game Server Project
 * http://segs.sf.net/
 * Copyright (c) 2006 Super Entity Game Server Team (see Authors.txt)
 * This software is licensed! (See License.txt for details)
 *
 * $Id$
 */
#define _USE_MATH_DEFINES
#include <cmath>
#include "types.h"
#include "Events/InputState.h"
#include "Entity.h"
void InputState::serializeto(BitStream &) const
{
    assert(!"Not implemented");
}

void InputState::partial_2(BitStream &bs)
{
    uint8_t control_id;
    //uint16_t v6;
    uint16_t time_since_prev;
    int v;
    static char *control_name[] = {"FORWARD",
                                   "BACK",
                                   "LEFT",
                                   "RIGHT",
                                   "UP",
                                   "DOWN"};
    do
    {
        if(bs.GetBits(1))
            control_id = 8;
        else
            control_id = bs.GetBits(4);

        if(bs.GetBits(1)) //
            time_since_prev=bs.GetBits(2)+32;
        else
            time_since_prev=bs.GetBits(m_csc_deltabits);
        switch(control_id)
        {
            case 0: case 1: case 2:
            case 3: case 4: case 5:
                // field_38 bits , control_id is the number of the bit
                fprintf(stderr,"%s  : %d - ",control_name[control_id],time_since_prev);
                v = bs.GetBits(1); // press release
                fprintf(stderr,"%d\n",v);
                break;
            case 6:
            case 7:
            {
                v = bs.GetBits(11);
                // v = (x+pi)*(2048/2pi)
                // x = (v*(pi/1024))-pi
                float recovered = (float(v)/2048.0f)*(2*M_PI) - M_PI;
                fprintf(stderr,"Pyr %f : %f \n",camera_pyr.x,camera_pyr.y);
                if(control_id==6) //TODO: use camera_pyr.v[] here ?
                    camera_pyr.x = recovered;
                else
                    camera_pyr.y = recovered;
                break;
            }
            case 8:
                v = bs.GetBits(1);
//                fprintf(stderr,"\tCTRL_8[%d] ",v);
                if ( m_send_deltas )
                {
                    m_t1=bs.GetPackedBits(8);
                    m_t2=bs.GetPackedBits(8);
                }
                else
                {
                    m_send_deltas = true;
                    m_t1=bs.GetBits(32);
                    m_t2=bs.GetPackedBits(10);
                }
//                fprintf(stderr,"[%d, ",t1);
//                fprintf(stderr,",%d] ",t2);
                if(bs.GetBits(1))
                {
                    v=bs.GetBits(8);
//                    fprintf(stderr,"CTRL_8C[%d] ",v);
//                    fprintf(stderr,"P2_8_opt : %d\n",v);
                }
                break;
            case 9:
                 //a2->timerel_18
                //fprintf(stderr,"CtrlId %d  : %d - ",control_id,time_since_prev);
                fprintf(stderr,"%d\n",bs.GetBits(8));
                break;
            case 10:
                fprintf(stderr,"CtrlId %d  : %d - ",control_id,time_since_prev);
                fprintf(stderr,"%d\n",bs.GetBits(1)); //a2->timerel_18 & 1
                break;
            default:
                assert(!"Unknown control_id");
        }

    } while(bs.GetBits(1));
}

void InputState::extended_input(BitStream &bs)
{
    if(bs.GetBits(1)) // list of partial_2 follows
    {
        m_csc_deltabits=bs.GetBits(5) + 1; // number of bits in max_time_diff_ms
        someOtherbits = bs.GetBits(16);//ControlStateChange::field_8 or OptRel::field_19A8
        current_state_P = 0;
#ifdef DEBUG_INPUT
        fprintf(stderr,"CSC_DELTA[%x-%x] : ",m_csc_deltabits,someOtherbits);
#endif
        partial_2(bs);

    }
    controlBits = 0;
    for(int idx=0; idx<6; ++idx)
        controlBits |= (bs.GetBits(1))<<idx;
#ifdef DEBUG_INPUT
    fprintf(stderr,"E input %x : ",controlBits);
#endif
    if(bs.GetBits(1))//if ( abs(s_prevTime - ms_time) < 1000 )
    {
        m_A_ang11_propably = bs.GetBits(11);//pak->SendBits(11, control_state.field_1C[0]);
        m_B_ang11_propably = bs.GetBits(11);//pak->SendBits(11, control_state.field_1C[1]);
#ifdef DEBUG_INPUT
        fprintf(stderr,"%x : %x",v1,v2);
#endif
    }
}
struct ControlState
{
    int field0;
    int time_res;
    float timestep;
    float time_rel1C;
    uint64_t m_perf_cntr_diff;
    uint64_t m_perf_freq_diff;
    // recover actual ControlState from network data and previous entry
    void serializefrom_delta(BitStream &bs,const ControlState &prev)
    {
        field0   = bs.GetPackedBits(1); // field_0 diff next-current
        time_res = bs.GetPackedBits(1); // time to next state ?
        timestep = bs.GetFloat(); // next state's timestep

        time_rel1C = timestep;
        if(bs.GetBits(1)) //timestep!=time_rel1C
            time_rel1C = bs.GetFloat();

        m_perf_cntr_diff = bs.Get64Bits(); //next_state->ticks - current_state->ticks
        if(bs.GetBits(1))
        {
            // perf freq changed between current and next
            m_perf_freq_diff = bs.Get64Bits();
        }
    }
    void serializefrom_base(BitStream &bs)
    {
        field0   = bs.GetBits(32); //field_0
        time_res = bs.GetBits(32); // get_time_resl
        timestep = bs.GetFloat(); //v7->timestep

        time_rel1C = timestep;
        if(bs.GetBits(1)) //timestep!=time_rel1C
            time_rel1C = bs.GetFloat();

        m_perf_cntr_diff = bs.Get64Bits(); //next_state->ticks - current_state->ticks
        m_perf_cntr_diff = bs.Get64Bits(); //v7->perf_cntr1
    }
    void dump()
    {
#ifdef DEBUG_INPUT
        fprintf(stderr,"CSC: %d,%d, [%f,%f]",field0,time_res,timestep,time_rel1C);
        fprintf(stderr, "(%lld %lld)",m_perf_cntr_diff,m_perf_freq_diff);
#endif
    }
};
void InputState::serializefrom(BitStream &bs)
{
    m_send_deltas=false;
#ifdef DEBUG_INPUT
    fprintf(stderr,"I:");
#endif
    if(bs.GetBits(1))
        extended_input(bs);

    bool has_targeted_entity = bs.GetBits(1);
    int tgt_idx=bs.GetPackedBits(14); // targeted entity server index
    int ctrl_idx=0;
#ifdef DEBUG_INPUT
    fprintf(stderr,"T:[%d]",has_targeted_entity);
    fprintf(stderr,"TI:[%d]",tgt_idx);
#endif
    ControlState prev_fld;
    while(bs.GetBits(1)) // receive control state array entries ?
    {
        ControlState fld;
        if(ctrl_idx)
        {
            fld.serializefrom_delta(bs,prev_fld);
        }
        else // initial values
        {
            fld.serializefrom_base(bs);
        }
        fld.dump();
        prev_fld = fld;
        ctrl_idx++;
    }
    recv_client_opts(bs); // g_pak contents will follow
#ifdef DEBUG_INPUT
    fprintf(stderr,"\n");
#endif
}
//TODO: use generic ReadableStructures here ?
void InputState::recv_client_opts(BitStream &bs)
{
    ClientOptions opts;
    ClientOption *entry;
    int opt_idx=0;
    int some_idx = bs.GetPackedBits(1);
    entry=opts.get(opt_idx);
    Vector3 vec;
    while(some_idx!=0)
    {
        for(size_t i=0; i<entry->m_args.size(); i++)
        {
            ClientOption::Arg &arg=entry->m_args[i];
            switch ( arg.type )
            {
                case ClientOption::t_int:
                {
                    *((int32_t *)arg.tgt) = bs.GetPackedBits(1);
                    break;
                }
                case ClientOption::t_float:
                {
                    *((float *)arg.tgt)=bs.GetFloat();
                    break;
                }
                case 5:
                {
                    printf("Quant:%d\n",bs.GetBits(14)); //quantized angle
                    break;
                }
                case ClientOption::t_string:
                case 4:
                {
                    std::string v;
                    bs.GetString(v);
                    break;
                }
                case 7:
                {
                    for (int j = 0; j < 3; ++j )
                    {
                        vec.v[j] = bs.GetFloat();
                    }
                    break;
                }
                default:
                    continue;
            }
        }
        some_idx = bs.GetPackedBits(1);
        opt_idx++;
        entry=opts.get(opt_idx);
    }
}

<|endoftext|>


<commit_before>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/process.h"
#include "base/logging.h"
#include "base/process_util.h"

namespace base {

void Process::Close() {
  process_ = 0;
  // if the process wasn't termiated (so we waited) or the state
  // wasn't already collected w/ a wait from process_utils, we're gonna
  // end up w/ a zombie when it does finally exit.
}

void Process::Terminate(int result_code) {
  // result_code isn't supportable.
  if (!process_)
    return;
  // Wait so we clean up the zombie
  KillProcess(process_, result_code, true);
}

bool Process::IsProcessBackgrounded() const {
  return false;
}

bool Process::SetProcessBackgrounded(bool value) {
  NOTIMPLEMENTED();
  return false;
}

bool Process::ReduceWorkingSet() {
  NOTIMPLEMENTED();
  return false;
}

bool Process::UnReduceWorkingSet() {
  NOTIMPLEMENTED();
  return false;
}

bool Process::EmptyWorkingSet() {
  NOTIMPLEMENTED();
  return false;
}

int32 Process::pid() const {
  if (process_ == 0)
    return 0;

  return GetProcId(process_);
}

bool Process::is_current() const {
  return process_ == GetCurrentProcessHandle();
}

// static
Process Process::Current() {
  return Process(GetCurrentProcessHandle());
}

}  // namspace base
<commit_msg>Lie on the priority change and saw we did it w/ a comment about why we won't   be able to, but w/ the current api and higher layers, it's much more work to   fully clean that up. Review URL: http://codereview.chromium.org/28029<commit_after>// Copyright (c) 2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/process.h"
#include "base/logging.h"
#include "base/process_util.h"

namespace base {

void Process::Close() {
  process_ = 0;
  // if the process wasn't termiated (so we waited) or the state
  // wasn't already collected w/ a wait from process_utils, we're gonna
  // end up w/ a zombie when it does finally exit.
}

void Process::Terminate(int result_code) {
  // result_code isn't supportable.
  if (!process_)
    return;
  // Wait so we clean up the zombie
  KillProcess(process_, result_code, true);
}

bool Process::IsProcessBackgrounded() const {
  return false;
}

bool Process::SetProcessBackgrounded(bool value) {
  NOTIMPLEMENTED();
  // Just say we did it to keep renderer happy at the moment.  Need to finish
  // cleaning this up w/in higher layers since windows is probably the only
  // one that can raise priorities w/o privileges.
  return true;
}

bool Process::ReduceWorkingSet() {
  NOTIMPLEMENTED();
  return false;
}

bool Process::UnReduceWorkingSet() {
  NOTIMPLEMENTED();
  return false;
}

bool Process::EmptyWorkingSet() {
  NOTIMPLEMENTED();
  return false;
}

int32 Process::pid() const {
  if (process_ == 0)
    return 0;

  return GetProcId(process_);
}

bool Process::is_current() const {
  return process_ == GetCurrentProcessHandle();
}

// static
Process Process::Current() {
  return Process(GetCurrentProcessHandle());
}

}  // namspace base
<|endoftext|>