<commit_before>/*!
 * Copyright (c) 2015 by Contributors
 */
#include <unistd.h>
#include <dmlc/logging.h>
#include <cstdio>
#include <thread>
#include <chrono>
#include <vector>

#include "mxnet/engine.h"

void Foo(mxnet::RunContext, int i) { printf("The fox says %d\n", i); }

int main() {
  auto&& engine = mxnet::Engine::Get();
  auto&& var = engine->NewVariable();
  std::vector<mxnet::Engine::OprHandle> oprs;

  // Test #1
  printf("============= Test #1 ==============\n");
  for (int i = 0; i < 10; ++i) {
    oprs.push_back(engine->NewOperator(
        [i](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
          Foo(ctx, i);
          std::this_thread::sleep_for(std::chrono::seconds{1});
          cb();
        },
        {var}, {}));
    engine->Push(oprs.at(i), mxnet::Context{});
  }
  engine->WaitForAll();
  printf("Going to push delete\n");
  // std::this_thread::sleep_for(std::chrono::seconds{1});
  for (auto&& i : oprs) {
    engine->DeleteOperator(i);
  }
  engine->PushDelete([](mxnet::RunContext) {}, mxnet::Context{}, var);
  engine->WaitForAll();

  printf("============= Test #2 ==============\n");
  var = engine->NewVariable();
  oprs.clear();
  for (int i = 0; i < 10; ++i) {
    oprs.push_back(engine->NewOperator(
        [i](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
          Foo(ctx, i);
          std::this_thread::sleep_for(std::chrono::milliseconds{500});
          cb();
        },
        {}, {var}));
    engine->Push(oprs.at(i), mxnet::Context{});
  }
  // std::this_thread::sleep_for(std::chrono::seconds{1});
  engine->WaitForAll();
  for (auto&& i : oprs) {
    engine->DeleteOperator(i);
  }
  engine->PushDelete([](mxnet::RunContext) {}, mxnet::Context{}, var);

  printf("============= Test #3 ==============\n");
  var = engine->NewVariable();
  oprs.clear();
  engine->WaitForVar(var);
  engine->PushDelete([](mxnet::RunContext) {}, mxnet::Context{}, var);
  engine->WaitForAll();

  printf("============= Test #4 ==============\n");
  var = engine->NewVariable();
  oprs.clear();
  oprs.push_back(engine->NewOperator(
      [](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
        std::this_thread::sleep_for(std::chrono::seconds{2});
        Foo(ctx, 42);
        cb();
      },
      {}, {var}));
  engine->Push(oprs.at(0), mxnet::Context{});
  LOG(INFO) << "Operator pushed, should wait for 2 seconds.";
  engine->WaitForVar(var);
  LOG(INFO) << "OK, here I am.";
  for (auto&& i : oprs) {
    engine->DeleteOperator(i);
  }
  engine->PushDelete([](mxnet::RunContext) {}, mxnet::Context{}, var);
  engine->WaitForAll();

  printf("============= Test #5 ==============\n");
  var = engine->NewVariable();
  oprs.clear();
  oprs.push_back(engine->NewOperator(
      [](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
        Foo(ctx, 42);
        std::this_thread::sleep_for(std::chrono::seconds{2});
        cb();
      },
      {var}, {}));
  engine->Push(oprs.at(0), mxnet::Context{});
  LOG(INFO) << "Operator pushed, should not wait.";
  engine->WaitForVar(var);
  LOG(INFO) << "OK, here I am.";
  engine->WaitForAll();
  LOG(INFO) << "That was 2 seconds.";
  for (auto&& i : oprs) {
    engine->DeleteOperator(i);
  }
  engine->PushDelete([](mxnet::RunContext) {}, mxnet::Context{}, var);
  engine->WaitForAll();
  var = nullptr;
  oprs.clear();

  return 0;
}
<commit_msg>[engine-refactor] rename in test file<commit_after>/*!
 * Copyright (c) 2015 by Contributors
 */
#include <unistd.h>
#include <dmlc/logging.h>
#include <cstdio>
#include <thread>
#include <chrono>
#include <vector>

#include "mxnet/engine.h"

void Foo(mxnet::RunContext, int i) { printf("The fox says %d\n", i); }

int main() {
  auto&& engine = mxnet::Engine::Get();
  auto&& var = engine->NewVariable();
  std::vector<mxnet::Engine::OprHandle> oprs;

  // Test #1
  printf("============= Test #1 ==============\n");
  for (int i = 0; i < 10; ++i) {
    oprs.push_back(engine->NewOperator(
        [i](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
          Foo(ctx, i);
          std::this_thread::sleep_for(std::chrono::seconds{1});
          cb();
        },
        {var}, {}));
    engine->Push(oprs.at(i), mxnet::Context{});
  }
  engine->WaitForAll();
  printf("Going to push delete\n");
  // std::this_thread::sleep_for(std::chrono::seconds{1});
  for (auto&& i : oprs) {
    engine->DeleteOperator(i);
  }
  engine->DeleteVariable([](mxnet::RunContext) {}, mxnet::Context{}, var);
  engine->WaitForAll();

  printf("============= Test #2 ==============\n");
  var = engine->NewVariable();
  oprs.clear();
  for (int i = 0; i < 10; ++i) {
    oprs.push_back(engine->NewOperator(
        [i](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
          Foo(ctx, i);
          std::this_thread::sleep_for(std::chrono::milliseconds{500});
          cb();
        },
        {}, {var}));
    engine->Push(oprs.at(i), mxnet::Context{});
  }
  // std::this_thread::sleep_for(std::chrono::seconds{1});
  engine->WaitForAll();
  for (auto&& i : oprs) {
    engine->DeleteOperator(i);
  }
  engine->DeleteVariable([](mxnet::RunContext) {}, mxnet::Context{}, var);

  printf("============= Test #3 ==============\n");
  var = engine->NewVariable();
  oprs.clear();
  engine->WaitForVar(var);
  engine->DeleteVariable([](mxnet::RunContext) {}, mxnet::Context{}, var);
  engine->WaitForAll();

  printf("============= Test #4 ==============\n");
  var = engine->NewVariable();
  oprs.clear();
  oprs.push_back(engine->NewOperator(
      [](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
        std::this_thread::sleep_for(std::chrono::seconds{2});
        Foo(ctx, 42);
        cb();
      },
      {}, {var}));
  engine->Push(oprs.at(0), mxnet::Context{});
  LOG(INFO) << "Operator pushed, should wait for 2 seconds.";
  engine->WaitForVar(var);
  LOG(INFO) << "OK, here I am.";
  for (auto&& i : oprs) {
    engine->DeleteOperator(i);
  }
  engine->DeleteVariable([](mxnet::RunContext) {}, mxnet::Context{}, var);
  engine->WaitForAll();

  printf("============= Test #5 ==============\n");
  var = engine->NewVariable();
  oprs.clear();
  oprs.push_back(engine->NewOperator(
      [](mxnet::RunContext ctx, mxnet::Engine::Callback cb) {
        Foo(ctx, 42);
        std::this_thread::sleep_for(std::chrono::seconds{2});
        cb();
      },
      {var}, {}));
  engine->Push(oprs.at(0), mxnet::Context{});
  LOG(INFO) << "Operator pushed, should not wait.";
  engine->WaitForVar(var);
  LOG(INFO) << "OK, here I am.";
  engine->WaitForAll();
  LOG(INFO) << "That was 2 seconds.";
  for (auto&& i : oprs) {
    engine->DeleteOperator(i);
  }
  engine->DeleteVariable([](mxnet::RunContext) {}, mxnet::Context{}, var);
  engine->WaitForAll();
  var = nullptr;
  oprs.clear();

  return 0;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/hwpf/hwp/establish_system_smp/establish_system_smp.C $ */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2012,2013              */
/*                                                                        */
/* p1                                                                     */
/*                                                                        */
/* Object Code Only (OCO) source materials                                */
/* Licensed Internal Code Source Materials                                */
/* IBM HostBoot Licensed Internal Code                                    */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* Origin: 30                                                             */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 *  @file establish_system_smp.C
 *
 *  Support file for IStep: establish_system_smp
 *   Establish System SMP
 *
 *  *****************************************************************
 *  THIS FILE WAS GENERATED ON 2012-04-11:1611
 *  *****************************************************************
 *
 *  HWP_IGNORE_VERSION_CHECK
 *
 */

/******************************************************************************/
// Includes
/******************************************************************************/
#include    <stdint.h>

#include    <trace/interface.H>
#include    <initservice/taskargs.H>
#include    <errl/errlentry.H>

#include    <initservice/isteps_trace.H>

#include    <hwpisteperror.H>

#include    <istep_mbox_msgs.H>

//  targeting support
#include    <targeting/common/commontargeting.H>
#include    <smp_unfencing_inter_enclosure_abus_links.H>
#include    <targeting/common/attributes.H>

//  fapi support
#include    <fapi.H>
#include    <fapiPlatHwpInvoker.H>

#include    "establish_system_smp.H"

//  Uncomment these files as they become available:
// #include    "host_coalesce_host/host_coalesce_host.H"

namespace   ESTABLISH_SYSTEM_SMP
{

using   namespace   ISTEP;
using   namespace   ISTEP_ERROR;
using   namespace   TARGETING;
using   namespace   fapi;
using   namespace   EDI_EI_INITIALIZATION;

//
//  Wrapper function to call host_coalesce_host
//
void*    call_host_coalesce_host( void    *io_pArgs )
{
    errlHndl_t  l_errl  =   NULL;

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
               "call_host_coalesce_host entry" );

#if 0
    // @@@@@    CUSTOM BLOCK:   @@@@@
    //  figure out what targets we need
    //  customize any other inputs
    //  set up loops to go through all targets (if parallel, spin off a task)

    //  write HUID of target
    TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                "target HUID %.8X", TARGETING::get_huid(l));

    // cast OUR type of target to a FAPI type of target.
    const fapi::Target l_fapi_@targetN_target( TARGET_TYPE_MEMBUF_CHIP,
                        (const_cast<TARGETING::Target*>(l_@targetN_target)) );

    //  call the HWP with each fapi::Target
    FAPI_INVOKE_HWP( l_errl, host_coalesce_host, _args_...);
    if ( l_errl )
    {
        TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                  "ERROR : .........." );
        errlCommit( l_errl, HWPF_COMP_ID );
    }
    else
    {
        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                   "SUCCESS : .........." );
    }
    // @@@@@    END CUSTOM BLOCK:   @@@@@
#endif

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
               "call_host_coalesce_host exit" );

    // end task, returning any errorlogs to IStepDisp
    return l_errl;
}

//******************************************************************************
// host_sys_fab_iovalid_processing function
//******************************************************************************
void host_sys_fab_iovalid_processing( msg_t* io_pMsg )
{
    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
            "host_sys_fab_iovalid_processing entry" );

    iovalid_msg * drawerData = NULL;

    uint16_t count = 0;

    std::vector<TARGETING::EntityPath> present_drawers;

    errlHndl_t l_errl = NULL;

    // if there is extra data, start processing it
    // else send back a msg to indicate invalid msg
    if(io_pMsg->extra_data)
    {
        drawerData = (iovalid_msg *)io_pMsg->extra_data;

        // setup a pointer to the first drawer entry in our data
        TARGETING::EntityPath * ptr = drawerData->drawers;

        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,"Master node %s "
                                                      "List size = %d bytes "
                                                      "Drawer count = %d",
                ptr->toString(), drawerData->size, drawerData->count);

        count = drawerData->count;

        // get FABRIC_TO_PHYSICAL_NODE_MAP
        TARGETING::Target * sys = NULL;
        TARGETING::targetService().getTopLevelTarget( sys );
        assert(sys != NULL);

        uint8_t node_map[8];

        bool rc =
        sys->tryGetAttr<TARGETING::ATTR_FABRIC_TO_PHYSICAL_NODE_MAP>(node_map);
        assert(rc == true);

        TARGETING::ATTR_HB_EXISTING_IMAGE_type hb_existing_image = 0;

        // create a vector with the present drawers
        for(uint8_t i = 0; i < count; i++)
        {
            TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                    "list entry[%d] - %s", i, ptr->toString());

            present_drawers.push_back(*ptr);

            TARGETING::EntityPath::PathElement pe =
                ptr->pathElementOfType(TARGETING::TYPE_NODE);

            // pe.instance is the drawer number - convert to logical node
            uint8_t logical_node = node_map[pe.instance];

            // set mask to msb of bitmap
            TARGETING::ATTR_HB_EXISTING_IMAGE_type mask = 0x1 <<
                ((sizeof(TARGETING::ATTR_HB_EXISTING_IMAGE_type) * 8) -1);

            // set bit for this logical node.
            hb_existing_image |= (mask >> logical_node);

            ptr++;
        }

        sys->setAttr<TARGETING::ATTR_HB_EXISTING_IMAGE>(hb_existing_image);

        // $TODO RTC:63128 - exchange between present drawers to agree
        // on valid endpoints
        TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                  "$TODO RTC:63128 - hb instances exchange and agree on cfg");

        // after agreement, open abuses as required
        l_errl = smp_unfencing_inter_enclosure_abus_links();

        // release the storage from the message
        free(io_pMsg->extra_data);
        io_pMsg->extra_data = NULL;

        io_pMsg->data[0] = INITSERVICE::HWSVR_MSG_SUCCESS;
    }
    else
    {
        // message needs to have at least one entry
        // in the drawer list, else we will say invalid msg
        io_pMsg->data[0] = INITSERVICE::HWSVR_INVALID_MESSAGE;
    }

    io_pMsg->data[1] = 0;

    // if there is an error log add the ID to
    // data 0
    if(l_errl)
    {
        io_pMsg->data[0] = l_errl->eid();
        errlCommit(l_errl, HWPF_COMP_ID);
    }

    // response will be sent by calling routine
    // IStepDispatcher::handleMoreWorkNeededMsg()
    // which will also execute the procedure to winkle all cores

    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
            "host_sys_fab_iovalid_processing exit" );
}

};   // end namespace
<commit_msg>Load edi_ei_initialization module in establish_system_smp step<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/usr/hwpf/hwp/establish_system_smp/establish_system_smp.C $ */
/*                                                                        */
/* IBM CONFIDENTIAL                                                       */
/*                                                                        */
/* COPYRIGHT International Business Machines Corp. 2012,2013              */
/*                                                                        */
/* p1                                                                     */
/*                                                                        */
/* Object Code Only (OCO) source materials                                */
/* Licensed Internal Code Source Materials                                */
/* IBM HostBoot Licensed Internal Code                                    */
/*                                                                        */
/* The source code for this program is not published or otherwise         */
/* divested of its trade secrets, irrespective of what has been           */
/* deposited with the U.S. Copyright Office.                              */
/*                                                                        */
/* Origin: 30                                                             */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 *  @file establish_system_smp.C
 *
 *  Support file for IStep: establish_system_smp
 *   Establish System SMP
 *
 *  *****************************************************************
 *  THIS FILE WAS GENERATED ON 2012-04-11:1611
 *  *****************************************************************
 *
 *  HWP_IGNORE_VERSION_CHECK
 *
 */

/******************************************************************************/
// Includes
/******************************************************************************/
#include    <stdint.h>

#include    <trace/interface.H>
#include    <initservice/taskargs.H>
#include    <errl/errlentry.H>

#include    <initservice/isteps_trace.H>

#include    <hwpisteperror.H>

#include    <istep_mbox_msgs.H>
#include    <vfs/vfs.H>

//  targeting support
#include    <targeting/common/commontargeting.H>
#include    <smp_unfencing_inter_enclosure_abus_links.H>
#include    <targeting/common/attributes.H>

//  fapi support
#include    <fapi.H>
#include    <fapiPlatHwpInvoker.H>

#include    "establish_system_smp.H"

//  Uncomment these files as they become available:
// #include    "host_coalesce_host/host_coalesce_host.H"

namespace   ESTABLISH_SYSTEM_SMP
{

using   namespace   ISTEP;
using   namespace   ISTEP_ERROR;
using   namespace   TARGETING;
using   namespace   fapi;
using   namespace   EDI_EI_INITIALIZATION;

//
//  Wrapper function to call host_coalesce_host
//
void*    call_host_coalesce_host( void    *io_pArgs )
{
    errlHndl_t  l_errl  =   NULL;

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
               "call_host_coalesce_host entry" );

#if 0
    // @@@@@    CUSTOM BLOCK:   @@@@@
    //  figure out what targets we need
    //  customize any other inputs
    //  set up loops to go through all targets (if parallel, spin off a task)

    //  write HUID of target
    TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                "target HUID %.8X", TARGETING::get_huid(l));

    // cast OUR type of target to a FAPI type of target.
    const fapi::Target l_fapi_@targetN_target( TARGET_TYPE_MEMBUF_CHIP,
                        (const_cast<TARGETING::Target*>(l_@targetN_target)) );

    //  call the HWP with each fapi::Target
    FAPI_INVOKE_HWP( l_errl, host_coalesce_host, _args_...);
    if ( l_errl )
    {
        TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                  "ERROR : .........." );
        errlCommit( l_errl, HWPF_COMP_ID );
    }
    else
    {
        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                   "SUCCESS : .........." );
    }
    // @@@@@    END CUSTOM BLOCK:   @@@@@
#endif

    TRACDCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
               "call_host_coalesce_host exit" );

    // end task, returning any errorlogs to IStepDisp
    return l_errl;
}

//******************************************************************************
// host_sys_fab_iovalid_processing function
//******************************************************************************
void host_sys_fab_iovalid_processing( msg_t* io_pMsg )
{
    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
            "host_sys_fab_iovalid_processing entry" );

    iovalid_msg * drawerData = NULL;

    uint16_t count = 0;

    std::vector<TARGETING::EntityPath> present_drawers;

    errlHndl_t l_errl = NULL;

    // if there is extra data, start processing it
    // else send back a msg to indicate invalid msg
    if(io_pMsg->extra_data)
    {
        drawerData = (iovalid_msg *)io_pMsg->extra_data;

        // setup a pointer to the first drawer entry in our data
        TARGETING::EntityPath * ptr = drawerData->drawers;

        TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,"Master node %s "
                                                      "List size = %d bytes "
                                                      "Drawer count = %d",
                ptr->toString(), drawerData->size, drawerData->count);

        count = drawerData->count;

        // get FABRIC_TO_PHYSICAL_NODE_MAP
        TARGETING::Target * sys = NULL;
        TARGETING::targetService().getTopLevelTarget( sys );
        assert(sys != NULL);

        uint8_t node_map[8];

        bool rc =
        sys->tryGetAttr<TARGETING::ATTR_FABRIC_TO_PHYSICAL_NODE_MAP>(node_map);
        assert(rc == true);

        TARGETING::ATTR_HB_EXISTING_IMAGE_type hb_existing_image = 0;

        // create a vector with the present drawers
        for(uint8_t i = 0; i < count; i++)
        {
            TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
                    "list entry[%d] - %s", i, ptr->toString());

            present_drawers.push_back(*ptr);

            TARGETING::EntityPath::PathElement pe =
                ptr->pathElementOfType(TARGETING::TYPE_NODE);

            // pe.instance is the drawer number - convert to logical node
            uint8_t logical_node = node_map[pe.instance];

            // set mask to msb of bitmap
            TARGETING::ATTR_HB_EXISTING_IMAGE_type mask = 0x1 <<
                ((sizeof(TARGETING::ATTR_HB_EXISTING_IMAGE_type) * 8) -1);

            // set bit for this logical node.
            hb_existing_image |= (mask >> logical_node);

            ptr++;
        }

        sys->setAttr<TARGETING::ATTR_HB_EXISTING_IMAGE>(hb_existing_image);

        // $TODO RTC:63128 - exchange between present drawers to agree
        // on valid endpoints
        TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace,
                  "$TODO RTC:63128 - hb instances exchange and agree on cfg");

        bool l_libloaded = false;
        if ( !VFS::module_is_loaded( "libedi_ei_initialization.so" ) )
        {
            l_errl = VFS::module_load( "libedi_ei_initialization.so" );
            if ( l_errl )
            {
                TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK
                          "Could not load libedi_ei_initialization.so");
            }
            else
            {
                l_libloaded = true;
            }
        }

        if(!l_errl)
        {
            // after agreement, open abuses as required
            l_errl = smp_unfencing_inter_enclosure_abus_links();
        }

        if(l_libloaded) // loaded locally
        {
            l_errl = VFS::module_unload( "libedi_ei_initialization.so" );
            if(l_errl)
            {
                TRACFCOMP(ISTEPS_TRACE::g_trac_isteps_trace, ERR_MRK
                          "Could not un-load libedi_ei_initialization.so");
            }
        }

        // release the storage from the message
        free(io_pMsg->extra_data);
        io_pMsg->extra_data = NULL;

        io_pMsg->data[0] = INITSERVICE::HWSVR_MSG_SUCCESS;
    }
    else
    {
        // message needs to have at least one entry
        // in the drawer list, else we will say invalid msg
        io_pMsg->data[0] = INITSERVICE::HWSVR_INVALID_MESSAGE;
    }

    io_pMsg->data[1] = 0;

    // if there is an error log add the ID to
    // data 0
    if(l_errl)
    {
        io_pMsg->data[0] = l_errl->eid();
        errlCommit(l_errl, HWPF_COMP_ID);
    }

    // response will be sent by calling routine
    // IStepDispatcher::handleMoreWorkNeededMsg()
    // which will also execute the procedure to winkle all cores

    TRACFCOMP( ISTEPS_TRACE::g_trac_isteps_trace,
            "host_sys_fab_iovalid_processing exit" );
}

};   // end namespace
<|endoftext|>


<commit_before>#include <exception>
#include <utility>

#include <QMessageBox>

#include "tronwidget.h"
#include "clamp.h"

TronWidget::TronWidget(QWidget *parent) :
    QWidget(parent)
{
    QObject::connect(&ticker, SIGNAL(timeout()),
                     this, SLOT(step()));
    // TODO: Let user modify this interval?
    ticker.setInterval(DEFAULT_TICK_INTERVAL);
}

TronWidget::~TronWidget()
{
    tron.reset(nullptr);
}

void TronWidget::start()
{
    tron.reset(new Tron(mapSize, playerCount, playerNames, playerColors));
    resizeMap();
    setFocus(Qt::OtherFocusReason);
    ticker.start();
    emit gameInProgress(true);
}

void TronWidget::stop()
{
    ticker.stop();
    emit gameInProgress(false);
}

void TronWidget::step()
{
    if (tron) {
        if (tron->step()) {
            repaint(rect());
        } else {
            stop();
            repaint(rect());
            auto winner = tron->getWinner();
            QString winnerString;
            QString colorString;
            if (winner == tron->getPlayers().end()) {
                winnerString = "Tie Game";
                colorString = "black";
            } else {
                winnerString = QString{"%1 won!"}.arg(winner->getName());
                colorString = winner->getColor().name();
            }
            QMessageBox gameOverDialog{QMessageBox::Information, "Game Over", winnerString, QMessageBox::Ok, this};
            gameOverDialog.setStyleSheet(QString("color: %1").arg(colorString));
            gameOverDialog.exec();
        }
    }
}

void TronWidget::setPlayerCount(int playerCount)
{
    this->playerCount = clamp(playerCount,
                              Tron::MIN_PLAYER_COUNT,
                              Tron::MAX_PLAYER_COUNT);
}

void TronWidget::setPlayerName(int player, QString name)
{
    this->playerNames[player] = name;
}

auto TronWidget::getPlayerName(int player) const -> QString
{
    return this->playerNames[player];
}

void TronWidget::setPlayerColor(int player, QColor color)
{
    this->playerColors[player] = color;
}

auto TronWidget::getPlayerColor(int player) const -> QColor
{
    return this->playerColors[player];
}

void TronWidget::setMapWidth(int width)
{
    this->mapSize.setWidth(clamp(width,
                                 Tron::MIN_MAP_WIDTH,
                                 Tron::MAX_MAP_WIDTH));
}

void TronWidget::setMapHeight(int height)
{
    this->mapSize.setHeight(clamp(height,
                                  Tron::MIN_MAP_HEIGHT,
                                  Tron::MAX_MAP_HEIGHT));
}

void TronWidget::resizeMap()
{
    if (tron) {
        // We need to keep the map on-screen no matter
        // how the window is resized, so we choose the
        // smallest dimension and divide it evenly.
        int tileWidth = rect().width() / tron->getMapSize().width();
        int tileHeight = rect().height() / tron->getMapSize().height();
        tileSize = std::min(tileWidth, tileHeight);
    } else {
        tileSize = DEFAULT_TILE_SIZE;
    }
}

void TronWidget::resizeEvent(QResizeEvent *)
{
    resizeMap();
}

void TronWidget::paintEvent(QPaintEvent *)
{
    if (tron) {
        QPainter painter{this};

        // Paint playing board
        painter.setBrush(Qt::black);
        painter.setPen(QPen(QBrush(Qt::white), 1));
        painter.drawRect(rect().x(), rect().y(),
                         tron->getMapSize().width()*tileSize,
                         tron->getMapSize().height()*tileSize);

        // Draw each player and its trail
        painter.setPen(QPen(QBrush(Qt::white), 1));
        for(int i = 0; i < tron->getPlayerCount(); ++i) {
            auto player = tron->getPlayer(i);
            painter.setBrush(player.getColor());
            if (player.getIsPlaying()) {
                QPoint p = player.getPosition();
                painter.drawRect(p.x() * tileSize, p.y() * tileSize,
                                 tileSize, tileSize);
            }
            for (QPoint pt : player.getTrail()) {
                painter.drawRect(pt.x() * tileSize, pt.y() * tileSize,
                                 tileSize, tileSize);
            }
        }
    }
}

void TronWidget::keyPressEvent(QKeyEvent *event)
{
    if (tron) {
        if (keybindings.count(event->key()) > 0) {
            // This key press is a game control
            auto binding = keybindings.at(event->key());
            // Check if this binding applies to an active player
            if (binding.first < tron->getPlayerCount()) {
                // Make the turn
                tron->getPlayer(binding.first).turn(binding.second);
            }
        } else {
            // This key press doesn't concern our game directly
            // Pass it on to the default Qt implementation
            QWidget::keyPressEvent(event);
        }
    }
}

std::map<int, std::pair<int, Player::Direction>>
TronWidget::keybindings
{
    // Player One
    {Qt::Key_Up, {0, Player::Direction::Up}},
    {Qt::Key_Down, {0, Player::Direction::Down}},
    {Qt::Key_Left, {0, Player::Direction::Left}},
    {Qt::Key_Right, {0, Player::Direction::Right}},
    // Player Two
    {Qt::Key_W, {1, Player::Direction::Up}},
    {Qt::Key_S, {1, Player::Direction::Down}},
    {Qt::Key_A, {1, Player::Direction::Left}},
    {Qt::Key_D, {1, Player::Direction::Right}},
    // Player Three
    {Qt::Key_I, {2, Player::Direction::Up}},
    {Qt::Key_K, {2, Player::Direction::Down}},
    {Qt::Key_J, {2, Player::Direction::Left}},
    {Qt::Key_L, {2, Player::Direction::Right}},
    // Player Four
    {Qt::Key_T, {3, Player::Direction::Up}},
    {Qt::Key_G, {3, Player::Direction::Down}},
    {Qt::Key_F, {3, Player::Direction::Left}},
    {Qt::Key_H, {3, Player::Direction::Right}},
};

const int TronWidget::DEFAULT_TILE_SIZE{20};
const int TronWidget::DEFAULT_TICK_INTERVAL{100};

<commit_msg>Hastened default tick interval.<commit_after>#include <exception>
#include <utility>

#include <QMessageBox>

#include "tronwidget.h"
#include "clamp.h"

TronWidget::TronWidget(QWidget *parent) :
    QWidget(parent)
{
    QObject::connect(&ticker, SIGNAL(timeout()),
                     this, SLOT(step()));
    // TODO: Let user modify this interval?
    ticker.setInterval(DEFAULT_TICK_INTERVAL);
}

TronWidget::~TronWidget()
{
    tron.reset(nullptr);
}

void TronWidget::start()
{
    tron.reset(new Tron(mapSize, playerCount, playerNames, playerColors));
    resizeMap();
    setFocus(Qt::OtherFocusReason);
    ticker.start();
    emit gameInProgress(true);
}

void TronWidget::stop()
{
    ticker.stop();
    emit gameInProgress(false);
}

void TronWidget::step()
{
    if (tron) {
        if (tron->step()) {
            repaint(rect());
        } else {
            stop();
            repaint(rect());
            auto winner = tron->getWinner();
            QString winnerString;
            QString colorString;
            if (winner == tron->getPlayers().end()) {
                winnerString = "Tie Game";
                colorString = "black";
            } else {
                winnerString = QString{"%1 won!"}.arg(winner->getName());
                colorString = winner->getColor().name();
            }
            QMessageBox gameOverDialog{QMessageBox::Information, "Game Over", winnerString, QMessageBox::Ok, this};
            gameOverDialog.setStyleSheet(QString("color: %1").arg(colorString));
            gameOverDialog.exec();
        }
    }
}

void TronWidget::setPlayerCount(int playerCount)
{
    this->playerCount = clamp(playerCount,
                              Tron::MIN_PLAYER_COUNT,
                              Tron::MAX_PLAYER_COUNT);
}

void TronWidget::setPlayerName(int player, QString name)
{
    this->playerNames[player] = name;
}

auto TronWidget::getPlayerName(int player) const -> QString
{
    return this->playerNames[player];
}

void TronWidget::setPlayerColor(int player, QColor color)
{
    this->playerColors[player] = color;
}

auto TronWidget::getPlayerColor(int player) const -> QColor
{
    return this->playerColors[player];
}

void TronWidget::setMapWidth(int width)
{
    this->mapSize.setWidth(clamp(width,
                                 Tron::MIN_MAP_WIDTH,
                                 Tron::MAX_MAP_WIDTH));
}

void TronWidget::setMapHeight(int height)
{
    this->mapSize.setHeight(clamp(height,
                                  Tron::MIN_MAP_HEIGHT,
                                  Tron::MAX_MAP_HEIGHT));
}

void TronWidget::resizeMap()
{
    if (tron) {
        // We need to keep the map on-screen no matter
        // how the window is resized, so we choose the
        // smallest dimension and divide it evenly.
        int tileWidth = rect().width() / tron->getMapSize().width();
        int tileHeight = rect().height() / tron->getMapSize().height();
        tileSize = std::min(tileWidth, tileHeight);
    } else {
        tileSize = DEFAULT_TILE_SIZE;
    }
}

void TronWidget::resizeEvent(QResizeEvent *)
{
    resizeMap();
}

void TronWidget::paintEvent(QPaintEvent *)
{
    if (tron) {
        QPainter painter{this};

        // Paint playing board
        painter.setBrush(Qt::black);
        painter.setPen(QPen(QBrush(Qt::white), 1));
        painter.drawRect(rect().x(), rect().y(),
                         tron->getMapSize().width()*tileSize,
                         tron->getMapSize().height()*tileSize);

        // Draw each player and its trail
        painter.setPen(QPen(QBrush(Qt::white), 1));
        for(int i = 0; i < tron->getPlayerCount(); ++i) {
            auto player = tron->getPlayer(i);
            painter.setBrush(player.getColor());
            if (player.getIsPlaying()) {
                QPoint p = player.getPosition();
                painter.drawRect(p.x() * tileSize, p.y() * tileSize,
                                 tileSize, tileSize);
            }
            for (QPoint pt : player.getTrail()) {
                painter.drawRect(pt.x() * tileSize, pt.y() * tileSize,
                                 tileSize, tileSize);
            }
        }
    }
}

void TronWidget::keyPressEvent(QKeyEvent *event)
{
    if (tron) {
        if (keybindings.count(event->key()) > 0) {
            // This key press is a game control
            auto binding = keybindings.at(event->key());
            // Check if this binding applies to an active player
            if (binding.first < tron->getPlayerCount()) {
                // Make the turn
                tron->getPlayer(binding.first).turn(binding.second);
            }
        } else {
            // This key press doesn't concern our game directly
            // Pass it on to the default Qt implementation
            QWidget::keyPressEvent(event);
        }
    }
}

std::map<int, std::pair<int, Player::Direction>>
TronWidget::keybindings
{
    // Player One
    {Qt::Key_Up, {0, Player::Direction::Up}},
    {Qt::Key_Down, {0, Player::Direction::Down}},
    {Qt::Key_Left, {0, Player::Direction::Left}},
    {Qt::Key_Right, {0, Player::Direction::Right}},
    // Player Two
    {Qt::Key_W, {1, Player::Direction::Up}},
    {Qt::Key_S, {1, Player::Direction::Down}},
    {Qt::Key_A, {1, Player::Direction::Left}},
    {Qt::Key_D, {1, Player::Direction::Right}},
    // Player Three
    {Qt::Key_I, {2, Player::Direction::Up}},
    {Qt::Key_K, {2, Player::Direction::Down}},
    {Qt::Key_J, {2, Player::Direction::Left}},
    {Qt::Key_L, {2, Player::Direction::Right}},
    // Player Four
    {Qt::Key_T, {3, Player::Direction::Up}},
    {Qt::Key_G, {3, Player::Direction::Down}},
    {Qt::Key_F, {3, Player::Direction::Left}},
    {Qt::Key_H, {3, Player::Direction::Right}},
};

const int TronWidget::DEFAULT_TILE_SIZE{20};
const int TronWidget::DEFAULT_TICK_INTERVAL{80};

<|endoftext|>


<commit_before>
#include <tree.hpp>
#include <catch.hpp>

SCENARIO("null")
{
	Tree<int> a;
	REQUIRE(a.tree_one()==NULL);
}
SCENARIO("find")
{
	Tree<int> a;
	a.add(5);
	bool b=a.find(5);
	REQUIRE(b == 1);
}
<commit_msg>Update init.cpp<commit_after>
#include <tree.hpp>
#include <catch.hpp>

SCENARIO("null")
{
	Tree<int> a;
	REQUIRE(a.tree_one()==NULL);
}
SCENARIO("find")
{
	Tree<int> a;
	REQUIRE(a.find(0) == 0);
}

<|endoftext|>


<commit_before>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>

int main(int argc, char *argv[])
{
  return Catch::Session().run(argc, argv);
}
<commit_msg>Add testcases for sphere<commit_after>#define CATCH_CONFIG_RUNNER
#include <catch.hpp>
#include <sphere.cpp>
#include <glm/vec3.hpp>

TEST_CASE("get volume of sphere", "[volume]") {
	Sphere sphere;
	REQUIRE(sphere.volume() == Approx(4.1888));
}

TEST_CASE("get area of sphere", "[area]") {
	Sphere sphere;
	REQUIRE(sphere.area() == Approx(12.5664));
}

TEST_CASE("get radius of sphere", "[radius]") {
	Sphere sphere;
	REQUIRE(sphere.radius() == 1);
}

TEST_CASE("get center of sphere", "[center]") {
	Sphere sphere;
	glm::vec3 tmp{0,0,0};
	REQUIRE(sphere.center() == tmp);
}

TEST_CASE("constructors of sphere", "[constructors]") {
	Sphere s1;
	Sphere s2{{0,0,0},1};
	REQUIRE(s1.center() == s2.center());
	REQUIRE(s1.radius() == s2.radius());
	REQUIRE(s1.area() == s2.area());
	REQUIRE(s1.volume() == s2.volume());
}

int main(int argc, char *argv[]) {
  return Catch::Session().run(argc, argv);
}
<|endoftext|>


<commit_before>
#include <cstdlib>
#include <iostream>
#include "gtest/gtest.h"

#include "gl-batch-context/Context.hpp"

int main(int argc, char** argv)
{
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

<commit_msg>Small comment regarding PNG library that should be used.<commit_after>
#include <cstdlib>
#include <iostream>
#include "gtest/gtest.h"

#include "gl-batch-context/Context.hpp"

/// \todo Use lodepng to write png files. It's small and we can easily
///       create a CPM external for it.
int main(int argc, char** argv)
{
  ::testing::InitGoogleTest(&argc, argv);
  return RUN_ALL_TESTS();
}

<|endoftext|>


<commit_before>/*  This file is part of the Vc library.

    Copyright (C) 2009 Matthias Kretz <kretz@kde.org>

    Vc is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Vc is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with Vc.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <Vc/Vc>
#include "unittest.h"
#include <iostream>
#include "vectormemoryhelper.h"
#include <cmath>

using namespace Vc;

template<typename Vec> void testInc()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i);
            data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 1 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        Vec aa(a);
        COMPARE(aa(m)++, a);
        COMPARE(aa, b);
        COMPARE(++a(m), b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testDec()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i + 1);
            data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 1 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        Vec aa(a);
        COMPARE(aa(m)--, a);
        COMPARE(--a(m), b);
        COMPARE(a, b);
        COMPARE(aa, b);
    }
}

template<typename Vec> void testPlusEq()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i + 1);
            data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) += static_cast<T>(2), b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testMinusEq()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i + 2);
            data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 2 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) -= static_cast<T>(2), b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testTimesEq()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i);
            data[i + Vec::Size] = data[i] * static_cast<T>(data[i] < border ? 2 : 1);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) *= static_cast<T>(2), b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testDivEq()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(5 * i);
            data[i + Vec::Size] = data[i] / static_cast<T>(data[i] < border ? 3 : 1);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) /= static_cast<T>(3), b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testAssign()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i);
            data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) = b, b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testZero()
{
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    typedef typename Vec::IndexType I;

    for (int cut = 0; cut < Vec::Size; ++cut) {
        const Mask mask(I(Vc::IndexesFromZero) < cut);
        //std::cout << mask << std::endl;

        const T aa = 4;
        Vec a(aa);
        Vec b(Vc::Zero);

        b(!mask) = a;
        a.makeZero(mask);

        COMPARE(a, b);
    }
}

template<typename Vec> void testCount()
{
    typedef typename Vec::EntryType T;
    typedef typename Vec::IndexType I;
    typedef typename Vec::Mask M;

    for (int cut = 0; cut <= Vec::Size; ++cut) {
        const M mask(I(Vc::IndexesFromZero) < cut);
        //std::cout << mask << std::endl;

        COMPARE(mask.count(), cut);
    }
}

template<typename Vec> void testFirstOne()
{
    typedef typename Vec::EntryType T;
    typedef typename Vec::IndexType I;
    typedef typename Vec::Mask M;

    for (int i = 0; i < Vec::Size; ++i) {
        const M mask(I(Vc::IndexesFromZero) == i);
        COMPARE(mask.firstOne(), i);
    }
}

int main()
{
    runTest(testInc<int_v>);
    runTest(testInc<uint_v>);
    runTest(testInc<float_v>);
    runTest(testInc<double_v>);
    runTest(testInc<short_v>);
    runTest(testInc<ushort_v>);
    runTest(testInc<sfloat_v>);

    runTest(testDec<int_v>);
    runTest(testDec<uint_v>);
    runTest(testDec<float_v>);
    runTest(testDec<double_v>);
    runTest(testDec<short_v>);
    runTest(testDec<ushort_v>);
    runTest(testDec<sfloat_v>);

    runTest(testPlusEq<int_v>);
    runTest(testPlusEq<uint_v>);
    runTest(testPlusEq<float_v>);
    runTest(testPlusEq<double_v>);
    runTest(testPlusEq<short_v>);
    runTest(testPlusEq<ushort_v>);
    runTest(testPlusEq<sfloat_v>);

    runTest(testMinusEq<int_v>);
    runTest(testMinusEq<uint_v>);
    runTest(testMinusEq<float_v>);
    runTest(testMinusEq<double_v>);
    runTest(testMinusEq<short_v>);
    runTest(testMinusEq<ushort_v>);
    runTest(testMinusEq<sfloat_v>);

    runTest(testTimesEq<int_v>);
    runTest(testTimesEq<uint_v>);
    runTest(testTimesEq<float_v>);
    runTest(testTimesEq<double_v>);
    runTest(testTimesEq<short_v>);
    runTest(testTimesEq<ushort_v>);
    runTest(testTimesEq<sfloat_v>);

    runTest(testDivEq<int_v>);
    runTest(testDivEq<uint_v>);
    runTest(testDivEq<float_v>);
    runTest(testDivEq<double_v>);
    runTest(testDivEq<short_v>);
    runTest(testDivEq<ushort_v>);
    runTest(testDivEq<sfloat_v>);

    runTest(testAssign<int_v>);
    runTest(testAssign<uint_v>);
    runTest(testAssign<float_v>);
    runTest(testAssign<double_v>);
    runTest(testAssign<short_v>);
    runTest(testAssign<ushort_v>);
    runTest(testAssign<sfloat_v>);

    runTest(testZero<int_v>);
    runTest(testZero<uint_v>);
    runTest(testZero<float_v>);
    runTest(testZero<double_v>);
    runTest(testZero<short_v>);
    runTest(testZero<ushort_v>);
    runTest(testZero<sfloat_v>);

    runTest(testCount<int_v>);
    runTest(testCount<uint_v>);
    runTest(testCount<float_v>);
    runTest(testCount<double_v>);
    runTest(testCount<short_v>);
    runTest(testCount<ushort_v>);
    runTest(testCount<sfloat_v>);

    runTest(testFirstOne<int_v>);
    runTest(testFirstOne<uint_v>);
    runTest(testFirstOne<float_v>);
    runTest(testFirstOne<double_v>);
    runTest(testFirstOne<short_v>);
    runTest(testFirstOne<ushort_v>);
    runTest(testFirstOne<sfloat_v>);

    return 0;
}
<commit_msg>test Float8GatherMask<commit_after>/*  This file is part of the Vc library.

    Copyright (C) 2009 Matthias Kretz <kretz@kde.org>

    Vc is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser General Public License as
    published by the Free Software Foundation, either version 3 of
    the License, or (at your option) any later version.

    Vc is distributed in the hope that it will be useful, but
    WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with Vc.  If not, see <http://www.gnu.org/licenses/>.

*/

#include <Vc/Vc>
#include "unittest.h"
#include <iostream>
#include "vectormemoryhelper.h"
#include <cmath>

using namespace Vc;

template<typename Vec> void testInc()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i);
            data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 1 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        Vec aa(a);
        COMPARE(aa(m)++, a);
        COMPARE(aa, b);
        COMPARE(++a(m), b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testDec()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i + 1);
            data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 1 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        Vec aa(a);
        COMPARE(aa(m)--, a);
        COMPARE(--a(m), b);
        COMPARE(a, b);
        COMPARE(aa, b);
    }
}

template<typename Vec> void testPlusEq()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i + 1);
            data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) += static_cast<T>(2), b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testMinusEq()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i + 2);
            data[i + Vec::Size] = data[i] - static_cast<T>(data[i] < border ? 2 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) -= static_cast<T>(2), b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testTimesEq()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i);
            data[i + Vec::Size] = data[i] * static_cast<T>(data[i] < border ? 2 : 1);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) *= static_cast<T>(2), b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testDivEq()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(5 * i);
            data[i + Vec::Size] = data[i] / static_cast<T>(data[i] < border ? 3 : 1);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) /= static_cast<T>(3), b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testAssign()
{
    VectorMemoryHelper<Vec> mem(2);
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    T *data = mem;
    for (int borderI = 0; borderI < Vec::Size; ++borderI) {
        const T border = static_cast<T>(borderI);
        for (int i = 0; i < Vec::Size; ++i) {
            data[i] = static_cast<T>(i);
            data[i + Vec::Size] = data[i] + static_cast<T>(data[i] < border ? 2 : 0);
        }
        Vec a(&data[0]);
        Vec b(&data[Vec::Size]);
        Mask m = a < border;
        COMPARE(a(m) = b, b);
        COMPARE(a, b);
    }
}

template<typename Vec> void testZero()
{
    typedef typename Vec::EntryType T;
    typedef typename Vec::Mask Mask;
    typedef typename Vec::IndexType I;

    for (int cut = 0; cut < Vec::Size; ++cut) {
        const Mask mask(I(Vc::IndexesFromZero) < cut);
        //std::cout << mask << std::endl;

        const T aa = 4;
        Vec a(aa);
        Vec b(Vc::Zero);

        b(!mask) = a;
        a.makeZero(mask);

        COMPARE(a, b);
    }
}

template<typename Vec> void testCount()
{
    typedef typename Vec::EntryType T;
    typedef typename Vec::IndexType I;
    typedef typename Vec::Mask M;

    for (int cut = 0; cut <= Vec::Size; ++cut) {
        const M mask(I(Vc::IndexesFromZero) < cut);
        //std::cout << mask << std::endl;

        COMPARE(mask.count(), cut);
    }
}

template<typename Vec> void testFirstOne()
{
    typedef typename Vec::EntryType T;
    typedef typename Vec::IndexType I;
    typedef typename Vec::Mask M;

    for (int i = 0; i < Vec::Size; ++i) {
        const M mask(I(Vc::IndexesFromZero) == i);
        COMPARE(mask.firstOne(), i);
    }
}

#ifdef VC_IMPL_SSE
void testFloat8GatherMask()
{
    Memory<short_v, short_v::Size * 256> data;
    short_v::Memory andMemory;
    for (int i = 0; i < short_v::Size; ++i) {
        andMemory[i] = 1 << i;
    }
    const short_v andMask(andMemory);

    for (unsigned int i = 0; i < data.vectorsCount(); ++i) {
        data.vector(i) = andMask & i;
    }

    for (unsigned int i = 0; i < data.vectorsCount(); ++i) {
        const short_m mask = data.vector(i) == short_v::Zero();

        SSE::Float8GatherMask
            gatherMaskA(mask),
            gatherMaskB(static_cast<sfloat_m>(mask));
        COMPARE(gatherMaskA.toInt(), gatherMaskB.toInt());
    }
}
#endif

int main()
{
    runTest(testInc<int_v>);
    runTest(testInc<uint_v>);
    runTest(testInc<float_v>);
    runTest(testInc<double_v>);
    runTest(testInc<short_v>);
    runTest(testInc<ushort_v>);
    runTest(testInc<sfloat_v>);

    runTest(testDec<int_v>);
    runTest(testDec<uint_v>);
    runTest(testDec<float_v>);
    runTest(testDec<double_v>);
    runTest(testDec<short_v>);
    runTest(testDec<ushort_v>);
    runTest(testDec<sfloat_v>);

    runTest(testPlusEq<int_v>);
    runTest(testPlusEq<uint_v>);
    runTest(testPlusEq<float_v>);
    runTest(testPlusEq<double_v>);
    runTest(testPlusEq<short_v>);
    runTest(testPlusEq<ushort_v>);
    runTest(testPlusEq<sfloat_v>);

    runTest(testMinusEq<int_v>);
    runTest(testMinusEq<uint_v>);
    runTest(testMinusEq<float_v>);
    runTest(testMinusEq<double_v>);
    runTest(testMinusEq<short_v>);
    runTest(testMinusEq<ushort_v>);
    runTest(testMinusEq<sfloat_v>);

    runTest(testTimesEq<int_v>);
    runTest(testTimesEq<uint_v>);
    runTest(testTimesEq<float_v>);
    runTest(testTimesEq<double_v>);
    runTest(testTimesEq<short_v>);
    runTest(testTimesEq<ushort_v>);
    runTest(testTimesEq<sfloat_v>);

    runTest(testDivEq<int_v>);
    runTest(testDivEq<uint_v>);
    runTest(testDivEq<float_v>);
    runTest(testDivEq<double_v>);
    runTest(testDivEq<short_v>);
    runTest(testDivEq<ushort_v>);
    runTest(testDivEq<sfloat_v>);

    runTest(testAssign<int_v>);
    runTest(testAssign<uint_v>);
    runTest(testAssign<float_v>);
    runTest(testAssign<double_v>);
    runTest(testAssign<short_v>);
    runTest(testAssign<ushort_v>);
    runTest(testAssign<sfloat_v>);

    runTest(testZero<int_v>);
    runTest(testZero<uint_v>);
    runTest(testZero<float_v>);
    runTest(testZero<double_v>);
    runTest(testZero<short_v>);
    runTest(testZero<ushort_v>);
    runTest(testZero<sfloat_v>);

    runTest(testCount<int_v>);
    runTest(testCount<uint_v>);
    runTest(testCount<float_v>);
    runTest(testCount<double_v>);
    runTest(testCount<short_v>);
    runTest(testCount<ushort_v>);
    runTest(testCount<sfloat_v>);

    runTest(testFirstOne<int_v>);
    runTest(testFirstOne<uint_v>);
    runTest(testFirstOne<float_v>);
    runTest(testFirstOne<double_v>);
    runTest(testFirstOne<short_v>);
    runTest(testFirstOne<ushort_v>);
    runTest(testFirstOne<sfloat_v>);

#ifdef VC_IMPL_SSE
    runTest(testFloat8GatherMask);
#endif

    return 0;
}
<|endoftext|>


<commit_before>/*
 * SimpleClusterView.cpp
 *
 * Copyright (C) 2010 by VISUS (Universitaet Stuttgart).
 * Alle Rechte vorbehalten.
 */

#include "stdafx.h"
#include "cluster/SimpleClusterView.h"
#include "cluster/SimpleClusterClientViewRegistration.h"
#include "cluster/SimpleClusterClient.h"
#include "cluster/SimpleClusterCommUtil.h"
#include "param/IntParam.h"
#include "param/StringParam.h"
#include "AbstractNamedObject.h"
#include "CoreInstance.h"
#include <GL/gl.h>
#include "vislib/assert.h"
#include "vislib/DNS.h"
#include "vislib/IPHostEntry.h"
#include "vislib/NetworkInformation.h"
#include "vislib/Thread.h"
#include <climits>

using namespace megamol::core;

/*
 * cluster::SimpleClusterView::SimpleClusterView
 */
cluster::SimpleClusterView::SimpleClusterView(void) : view::AbstractTileView(),
        firstFrame(false), frozen(false), frozenTime(0.0), frozenCam(NULL),
        registerSlot("register", "The slot registering this view"), client(NULL), initMsg(NULL),
        heartBeatPortSlot("heartbeat::port", "The port the heartbeat server communicates on"),
        heartBeatServerSlot("heartbeat::server", "The machine the heartbeat server runs on") {

    this->registerSlot.SetCompatibleCall<SimpleClusterClientViewRegistrationDescription>();
    this->MakeSlotAvailable(&this->registerSlot);

    this->heartBeatPortSlot << new param::IntParam(0, 0, USHRT_MAX);
    this->MakeSlotAvailable(&this->heartBeatPortSlot);

    this->heartBeatServerSlot << new param::StringParam("");
    this->MakeSlotAvailable(&this->heartBeatServerSlot);
    this->heartBeatServerSlot.ForceSetDirty();

}

/*
 * cluster::SimpleClusterView::~SimpleClusterView
 */
cluster::SimpleClusterView::~SimpleClusterView(void) {
    this->Release();
    this->frozenCam = NULL; // DO NOT DELETE
    ASSERT(this->client == NULL);
}

namespace intern {

    /**
     * Selects adapters which match this predicate
     */
    bool iamSelectAdapterCallback(const vislib::net::NetworkInformation::Adapter& adapter, void *userContext) {
        vislib::net::TIPHostEntry *he = static_cast<vislib::net::TIPHostEntry*>(userContext);
        vislib::Array<vislib::net::IPAgnosticAddress> a1 = he->GetAddresses();
        vislib::net::NetworkInformation::UnicastAddressList a2 = adapter.GetUnicastAddresses();
        for (SIZE_T i2 = 0; i2 < a2.Count(); i2++) {
            if (a1.Contains(a2[i2].GetAddress())) {
                return true;
            }
        }
        return false;
    }

}

/*
 * cluster::SimpleClusterView::Render
 */
void cluster::SimpleClusterView::Render(float time, double instTime) {
    if (this->firstFrame) {
        this->firstFrame = false;
        this->initTileViewParameters();
        AbstractNamedObject *ano = this;
        while (ano != NULL) {
            if (this->loadConfiguration(ano->Name())) break;
            ano = ano->Parent();
        }
        if (this->GetCoreInstance()->Configuration().IsConfigValueSet("scv-heartbeat-port")) {
            try {
                this->heartBeatPortSlot.Param<param::IntParam>()->SetValue(
                    vislib::CharTraitsW::ParseInt(
                        this->GetCoreInstance()->Configuration().ConfigValue("scv-heartbeat-port")));
            } catch(vislib::Exception e) {
                vislib::sys::Log::DefaultLog.WriteError(
                    "Failed to load heartbeat port configuration: %s [%s, %d]\n",
                    e.GetMsgA(), e.GetFile(), e.GetLine());
            } catch(...) {
                vislib::sys::Log::DefaultLog.WriteError(
                    "Failed to load heartbeat port configuration: Unknown exception\n");
            }
        }
        if (this->GetCoreInstance()->Configuration().IsConfigValueSet("scv-heartbeat-server")) {
            this->heartBeatServerSlot.Param<param::StringParam>()->SetValue(
                this->GetCoreInstance()->Configuration().ConfigValue("scv-heartbeat-server"));
        }
    }

    if (this->initMsg != NULL) {
        if (this->initMsg->GetHeader().GetMessageID() == MSG_MODULGRAPH) {
            this->GetCoreInstance()->SetupGraphFromNetwork(this->initMsg);
            this->client->ContinueSetup();
        } else if (this->initMsg->GetHeader().GetMessageID() == MSG_CAMERAUPDATE) {
            this->client->ContinueSetup(2);
        }
        SAFE_DELETE(this->initMsg);
    }

    if (this->client == NULL) {
        SimpleClusterClientViewRegistration *sccvr
            = this->registerSlot.CallAs<SimpleClusterClientViewRegistration>();
        if (sccvr != NULL) {
            sccvr->SetView(this);
            if ((*sccvr)()) {
                this->client = sccvr->GetClient();
            }
        }
    }

    if (this->heartBeatPortSlot.IsDirty() || this->heartBeatServerSlot.IsDirty()) {
        try {
            vislib::net::TIPHostEntry he;
            vislib::net::DNS::GetHostEntry(he, this->heartBeatServerSlot.Param<param::StringParam>()->Value());
            vislib::net::NetworkInformation::AdapterList adapters;
            vislib::net::NetworkInformation::GetAdaptersForPredicate(adapters,
                intern::iamSelectAdapterCallback,
                static_cast<void*>(&he));
            if (!adapters.IsEmpty()) {
                // TODO: Implement Server
            }
            // TODO: Implement Client
        } catch(vislib::Exception e) {
            vislib::sys::Log::DefaultLog.WriteError(
                "Failed to configure heartbeat: %s [%s, %d]\n",
                e.GetMsgA(), e.GetFile(), e.GetLine());
        } catch(...) {
            vislib::sys::Log::DefaultLog.WriteError(
                "Failed to configure heartbeat: Unknown exception\n");
        }
    }

    view::CallRenderView *crv = this->getCallRenderView();
    this->checkParameters();

    if (!this->frozen) {
        this->frozenTime = instTime;
    }

    if (crv != NULL) {
        crv->ResetAll();
        crv->SetTime(time);
        crv->SetInstanceTime(instTime);
        crv->SetProjection(this->getProjType(), this->getEye());
        if ((this->getVirtWidth() != 0) && (this->getVirtHeight() != 0)
                && (this->getTileW() != 0) && (this->getTileH() != 0)) {
            crv->SetTile(this->getVirtWidth(), this->getVirtHeight(),
                this->getTileX(), this->getTileY(), this->getTileW(), this->getTileH());
        }
        crv->SetOutputBuffer(GL_BACK, this->getViewportWidth(), this->getViewportHeight());

        //if ((this->netVSyncBarrier != NULL) && (this->netVSyncBarrier->GetDataSize() > 0)) {
        //    //printf("Barrier with %u bytes data\n", this->netVSyncBarrier->GetDataSize());
        //    vislib::RawStorageSerialiser camera(
        //        this->netVSyncBarrier->GetData() + 4,
        //        this->netVSyncBarrier->GetDataSize() - 4);
        //}
        view::AbstractView *view = NULL;
        if (crv->PeekCalleeSlot() != NULL) view = dynamic_cast<view::AbstractView*>(
                const_cast<AbstractNamedObject*>(crv->PeekCalleeSlot()->Parent()));
        if (view != NULL){
            if (this->frozenCam != NULL) view->DeserialiseCamera(*this->frozenCam);
            /* this forces to use this time */
            //view->SetFrameTime(static_cast<float>(this->frozenTime));
        }

        if (!(*crv)(view::CallRenderView::CALL_RENDER)) {
            this->renderFallbackView();
        }

    } else {
        this->renderFallbackView();

    }

    ::glFlush();
}

/*
 * cluster::SimpleClusterView::Unregister
 */
void cluster::SimpleClusterView::Unregister(cluster::SimpleClusterClient *client) {
    if (this->client == client) {
        if (this->client != NULL) {
            this->client->Unregister(this);
        }
        this->client = NULL;
    }
}

/*
 * cluster::SimpleClusterView::DisconnectViewCall
 */
void cluster::SimpleClusterView::DisconnectViewCall(void) {
    this->disconnectOutgoingRenderCall();
}

/*
 * cluster::SimpleClusterView::SetSetupMessage
 */
void cluster::SimpleClusterView::SetSetupMessage(const vislib::net::AbstractSimpleMessage& msg) {
    if (this->initMsg != NULL) {
        SAFE_DELETE(this->initMsg);
    }
    this->initMsg = new vislib::net::SimpleMessage(msg);
}

/*
 * cluster::SimpleClusterView::SetCamIniMessage
 */
void cluster::SimpleClusterView::SetCamIniMessage(void) {
    if (this->initMsg != NULL) {
        SAFE_DELETE(this->initMsg);
    }
    vislib::net::SimpleMessage *m = new vislib::net::SimpleMessage();
    m->GetHeader().SetMessageID(MSG_CAMERAUPDATE);
    this->initMsg = m;
}

/*
 * cluster::SimpleClusterView::ConnectView
 */
void cluster::SimpleClusterView::ConnectView(const vislib::StringA toName) {
    this->GetCoreInstance()->InstantiateCall(this->FullName() + "::renderView", toName,
        CallDescriptionManager::Instance()->Find("CallRenderView"));
}

/*
 * cluster::SimpleClusterView::create
 */
bool cluster::SimpleClusterView::create(void) {
    this->firstFrame = true;
    return true;
}

/*
 * cluster::SimpleClusterView::release
 */
void cluster::SimpleClusterView::release(void) {
    this->frozenCam = NULL; // DO NOT DELETE
    if (this->client != NULL) {
        this->client->Unregister(this);
        this->client = NULL;
    }
    if (this->initMsg != NULL) {
        SAFE_DELETE(this->initMsg);
    }
}

/*
 * cluster::SimpleClusterView::renderFallbackView
 */
void cluster::SimpleClusterView::renderFallbackView(void) {
    ::glClearColor(0.1f, 0.1f, 0.2f, 1.0f);
    ::glClear(GL_COLOR_BUFFER_BIT);
    ::glMatrixMode(GL_PROJECTION);
    ::glLoadIdentity();
    ::glMatrixMode(GL_MODELVIEW);
    ::glLoadIdentity();
    ::glRotated(this->frozenTime * 36.0, 0.0, 0.0, 1.0);
    ::glColor3ub(200, 200, 255);
    ::glBegin(GL_LINES);
    ::glVertex2i(0, 0);
    ::glVertex2i(1, 0);
    ::glEnd();
}

/*
 * cluster::SimpleClusterView::UpdateFreeze
 */
void cluster::SimpleClusterView::UpdateFreeze(bool freeze) {
    this->frozen = freeze;
    this->frozenTime = this->instance()->GetCoreInstanceTime(); // HAZARD
}

/*
 * cluster::SimpleClusterView::loadConfiguration
 */
bool cluster::SimpleClusterView::loadConfiguration(const vislib::StringA& name) {
    vislib::StringA vname(name);
    vname.Append("-tvtile");
    if (this->instance()->Configuration().IsConfigValueSet(vname)) {
        return this->setTile(this->instance()->Configuration().ConfigValue(vname));
    }
    return false;
}
<commit_msg>Resetting dirty flag for heart beat settings (removed unused code)<commit_after>/*
 * SimpleClusterView.cpp
 *
 * Copyright (C) 2010 by VISUS (Universitaet Stuttgart).
 * Alle Rechte vorbehalten.
 */

#include "stdafx.h"
#include "cluster/SimpleClusterView.h"
#include "cluster/SimpleClusterClientViewRegistration.h"
#include "cluster/SimpleClusterClient.h"
#include "cluster/SimpleClusterCommUtil.h"
#include "param/IntParam.h"
#include "param/StringParam.h"
#include "AbstractNamedObject.h"
#include "CoreInstance.h"
#include <GL/gl.h>
#include "vislib/assert.h"
#include "vislib/DNS.h"
#include "vislib/IPHostEntry.h"
#include "vislib/NetworkInformation.h"
#include "vislib/Thread.h"
#include <climits>

using namespace megamol::core;

/*
 * cluster::SimpleClusterView::SimpleClusterView
 */
cluster::SimpleClusterView::SimpleClusterView(void) : view::AbstractTileView(),
        firstFrame(false), frozen(false), frozenTime(0.0), frozenCam(NULL),
        registerSlot("register", "The slot registering this view"), client(NULL), initMsg(NULL),
        heartBeatPortSlot("heartbeat::port", "The port the heartbeat server communicates on"),
        heartBeatServerSlot("heartbeat::server", "The machine the heartbeat server runs on") {

    this->registerSlot.SetCompatibleCall<SimpleClusterClientViewRegistrationDescription>();
    this->MakeSlotAvailable(&this->registerSlot);

    this->heartBeatPortSlot << new param::IntParam(0, 0, USHRT_MAX);
    this->MakeSlotAvailable(&this->heartBeatPortSlot);

    this->heartBeatServerSlot << new param::StringParam("");
    this->MakeSlotAvailable(&this->heartBeatServerSlot);
    this->heartBeatServerSlot.ForceSetDirty();

}

/*
 * cluster::SimpleClusterView::~SimpleClusterView
 */
cluster::SimpleClusterView::~SimpleClusterView(void) {
    this->Release();
    this->frozenCam = NULL; // DO NOT DELETE
    ASSERT(this->client == NULL);
}

namespace intern {

    /**
     * Selects adapters which match this predicate
     */
    bool iamSelectAdapterCallback(const vislib::net::NetworkInformation::Adapter& adapter, void *userContext) {
        vislib::net::TIPHostEntry *he = static_cast<vislib::net::TIPHostEntry*>(userContext);
        vislib::Array<vislib::net::IPAgnosticAddress> a1 = he->GetAddresses();
        vislib::net::NetworkInformation::UnicastAddressList a2 = adapter.GetUnicastAddresses();
        for (SIZE_T i2 = 0; i2 < a2.Count(); i2++) {
            if (a1.Contains(a2[i2].GetAddress())) {
                return true;
            }
        }
        return false;
    }

}

/*
 * cluster::SimpleClusterView::Render
 */
void cluster::SimpleClusterView::Render(float time, double instTime) {
    if (this->firstFrame) {
        this->firstFrame = false;
        this->initTileViewParameters();
        AbstractNamedObject *ano = this;
        while (ano != NULL) {
            if (this->loadConfiguration(ano->Name())) break;
            ano = ano->Parent();
        }
        if (this->GetCoreInstance()->Configuration().IsConfigValueSet("scv-heartbeat-port")) {
            try {
                this->heartBeatPortSlot.Param<param::IntParam>()->SetValue(
                    vislib::CharTraitsW::ParseInt(
                        this->GetCoreInstance()->Configuration().ConfigValue("scv-heartbeat-port")));
            } catch(vislib::Exception e) {
                vislib::sys::Log::DefaultLog.WriteError(
                    "Failed to load heartbeat port configuration: %s [%s, %d]\n",
                    e.GetMsgA(), e.GetFile(), e.GetLine());
            } catch(...) {
                vislib::sys::Log::DefaultLog.WriteError(
                    "Failed to load heartbeat port configuration: Unknown exception\n");
            }
        }
        if (this->GetCoreInstance()->Configuration().IsConfigValueSet("scv-heartbeat-server")) {
            this->heartBeatServerSlot.Param<param::StringParam>()->SetValue(
                this->GetCoreInstance()->Configuration().ConfigValue("scv-heartbeat-server"));
        }
    }

    if (this->initMsg != NULL) {
        if (this->initMsg->GetHeader().GetMessageID() == MSG_MODULGRAPH) {
            this->GetCoreInstance()->SetupGraphFromNetwork(this->initMsg);
            this->client->ContinueSetup();
        } else if (this->initMsg->GetHeader().GetMessageID() == MSG_CAMERAUPDATE) {
            this->client->ContinueSetup(2);
        }
        SAFE_DELETE(this->initMsg);
    }

    if (this->client == NULL) {
        SimpleClusterClientViewRegistration *sccvr
            = this->registerSlot.CallAs<SimpleClusterClientViewRegistration>();
        if (sccvr != NULL) {
            sccvr->SetView(this);
            if ((*sccvr)()) {
                this->client = sccvr->GetClient();
            }
        }
    }

    if (this->heartBeatPortSlot.IsDirty() || this->heartBeatServerSlot.IsDirty()) {
        this->heartBeatPortSlot.ResetDirty();
        this->heartBeatServerSlot.ResetDirty();

        try {

            //vislib::net::TIPHostEntry he;
            //vislib::net::DNS::GetHostEntry(he, this->heartBeatServerSlot.Param<param::StringParam>()->Value());
            //vislib::net::NetworkInformation::AdapterList adapters;
            //vislib::net::NetworkInformation::GetAdaptersForPredicate(adapters,
            //    intern::iamSelectAdapterCallback,
            //    static_cast<void*>(&he));

            //if (!adapters.IsEmpty()) {
            //    // TODO: Implement Server
            //}
            //// TODO: Implement Client

        } catch(vislib::Exception e) {
            vislib::sys::Log::DefaultLog.WriteError(
                "Failed to configure heartbeat: %s [%s, %d]\n",
                e.GetMsgA(), e.GetFile(), e.GetLine());
        } catch(...) {
            vislib::sys::Log::DefaultLog.WriteError(
                "Failed to configure heartbeat: Unknown exception\n");
        }
    }

    view::CallRenderView *crv = this->getCallRenderView();
    this->checkParameters();

    if (!this->frozen) {
        this->frozenTime = instTime;
    }

    if (crv != NULL) {
        crv->ResetAll();
        crv->SetTime(time);
        crv->SetInstanceTime(instTime);
        crv->SetProjection(this->getProjType(), this->getEye());
        if ((this->getVirtWidth() != 0) && (this->getVirtHeight() != 0)
                && (this->getTileW() != 0) && (this->getTileH() != 0)) {
            crv->SetTile(this->getVirtWidth(), this->getVirtHeight(),
                this->getTileX(), this->getTileY(), this->getTileW(), this->getTileH());
        }
        crv->SetOutputBuffer(GL_BACK, this->getViewportWidth(), this->getViewportHeight());

        //if ((this->netVSyncBarrier != NULL) && (this->netVSyncBarrier->GetDataSize() > 0)) {
        //    //printf("Barrier with %u bytes data\n", this->netVSyncBarrier->GetDataSize());
        //    vislib::RawStorageSerialiser camera(
        //        this->netVSyncBarrier->GetData() + 4,
        //        this->netVSyncBarrier->GetDataSize() - 4);
        //}
        view::AbstractView *view = NULL;
        if (crv->PeekCalleeSlot() != NULL) view = dynamic_cast<view::AbstractView*>(
                const_cast<AbstractNamedObject*>(crv->PeekCalleeSlot()->Parent()));
        if (view != NULL){
            if (this->frozenCam != NULL) view->DeserialiseCamera(*this->frozenCam);
            /* this forces to use this time */
            //view->SetFrameTime(static_cast<float>(this->frozenTime));
        }

        if (!(*crv)(view::CallRenderView::CALL_RENDER)) {
            this->renderFallbackView();
        }

    } else {
        this->renderFallbackView();

    }

    ::glFlush();
}

/*
 * cluster::SimpleClusterView::Unregister
 */
void cluster::SimpleClusterView::Unregister(cluster::SimpleClusterClient *client) {
    if (this->client == client) {
        if (this->client != NULL) {
            this->client->Unregister(this);
        }
        this->client = NULL;
    }
}

/*
 * cluster::SimpleClusterView::DisconnectViewCall
 */
void cluster::SimpleClusterView::DisconnectViewCall(void) {
    this->disconnectOutgoingRenderCall();
}

/*
 * cluster::SimpleClusterView::SetSetupMessage
 */
void cluster::SimpleClusterView::SetSetupMessage(const vislib::net::AbstractSimpleMessage& msg) {
    if (this->initMsg != NULL) {
        SAFE_DELETE(this->initMsg);
    }
    this->initMsg = new vislib::net::SimpleMessage(msg);
}

/*
 * cluster::SimpleClusterView::SetCamIniMessage
 */
void cluster::SimpleClusterView::SetCamIniMessage(void) {
    if (this->initMsg != NULL) {
        SAFE_DELETE(this->initMsg);
    }
    vislib::net::SimpleMessage *m = new vislib::net::SimpleMessage();
    m->GetHeader().SetMessageID(MSG_CAMERAUPDATE);
    this->initMsg = m;
}

/*
 * cluster::SimpleClusterView::ConnectView
 */
void cluster::SimpleClusterView::ConnectView(const vislib::StringA toName) {
    this->GetCoreInstance()->InstantiateCall(this->FullName() + "::renderView", toName,
        CallDescriptionManager::Instance()->Find("CallRenderView"));
}

/*
 * cluster::SimpleClusterView::create
 */
bool cluster::SimpleClusterView::create(void) {
    this->firstFrame = true;
    return true;
}

/*
 * cluster::SimpleClusterView::release
 */
void cluster::SimpleClusterView::release(void) {
    this->frozenCam = NULL; // DO NOT DELETE
    if (this->client != NULL) {
        this->client->Unregister(this);
        this->client = NULL;
    }
    if (this->initMsg != NULL) {
        SAFE_DELETE(this->initMsg);
    }
}

/*
 * cluster::SimpleClusterView::renderFallbackView
 */
void cluster::SimpleClusterView::renderFallbackView(void) {
    ::glClearColor(0.1f, 0.1f, 0.2f, 1.0f);
    ::glClear(GL_COLOR_BUFFER_BIT);
    ::glMatrixMode(GL_PROJECTION);
    ::glLoadIdentity();
    ::glMatrixMode(GL_MODELVIEW);
    ::glLoadIdentity();
    ::glRotated(this->frozenTime * 36.0, 0.0, 0.0, 1.0);
    ::glColor3ub(200, 200, 255);
    ::glBegin(GL_LINES);
    ::glVertex2i(0, 0);
    ::glVertex2i(1, 0);
    ::glEnd();
}

/*
 * cluster::SimpleClusterView::UpdateFreeze
 */
void cluster::SimpleClusterView::UpdateFreeze(bool freeze) {
    this->frozen = freeze;
    this->frozenTime = this->instance()->GetCoreInstanceTime(); // HAZARD
}

/*
 * cluster::SimpleClusterView::loadConfiguration
 */
bool cluster::SimpleClusterView::loadConfiguration(const vislib::StringA& name) {
    vislib::StringA vname(name);
    vname.Append("-tvtile");
    if (this->instance()->Configuration().IsConfigValueSet(vname)) {
        return this->setTile(this->instance()->Configuration().ConfigValue(vname));
    }
    return false;
}
<|endoftext|>