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

#include "platform/platform.h"
#include "console/console.h"
#include "debug/telnetDebugger.h"
#include "platform/event.h"

#include "console/ast.h"
#include "collection/findIterator.h"
#include "io/resource/resourceManager.h"

#include "string/findMatch.h"
#include "console/consoleInternal.h"
#include "io/fileStream.h"
#include "console/compiler.h"

#include "sim/simBase.h"

namespace Compiler
{

   F64 consoleStringToNumber(const char *str, StringTableEntry file, U32 line)
   {
      F64 val = dAtof(str);
      if(val != 0)
         return val;
      else if(!dStricmp(str, "true"))
         return 1;
      else if(!dStricmp(str, "false"))
         return 0;
      else if(file)
      {
         Con::warnf(ConsoleLogEntry::General, "%s (%d): string always evaluates to 0.", file, line);
         return 0;
      }
      return 0;
   }

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

   CompilerStringTable *gCurrentStringTable, gGlobalStringTable, gFunctionStringTable;
   CompilerFloatTable  *gCurrentFloatTable,  gGlobalFloatTable,  gFunctionFloatTable;
   DataChunker          gConsoleAllocator;
   CompilerIdentTable   gIdentTable;
   CodeBlock           *gCurBreakBlock;

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

   CodeBlock *getBreakCodeBlock()         { return gCurBreakBlock; }
   void setBreakCodeBlock(CodeBlock *cb)  { gCurBreakBlock = cb;   }

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

   U32 evalSTEtoU32(StringTableEntry ste, U32)
   {
      return *((U32 *) &ste);
   }

   U32 compileSTEtoU32(StringTableEntry ste, U32 ip)
   {
      if(ste)
         getIdentTable().add(ste, ip);
      return 0;
   }

   U32 (*STEtoU32)(StringTableEntry ste, U32 ip) = evalSTEtoU32;

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

   bool gSyntaxError = false;

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

   CompilerStringTable *getCurrentStringTable()  { return gCurrentStringTable;  }
   CompilerStringTable &getGlobalStringTable()   { return gGlobalStringTable;   }
   CompilerStringTable &getFunctionStringTable() { return gFunctionStringTable; }

   void setCurrentStringTable (CompilerStringTable* cst) { gCurrentStringTable  = cst; }

   CompilerFloatTable *getCurrentFloatTable()    { return gCurrentFloatTable;   }
   CompilerFloatTable &getGlobalFloatTable()     { return gGlobalFloatTable;    }
   CompilerFloatTable &getFunctionFloatTable()   { return gFunctionFloatTable; }

   void setCurrentFloatTable (CompilerFloatTable* cst) { gCurrentFloatTable  = cst; }

   CompilerIdentTable &getIdentTable() { return gIdentTable; }

   void precompileIdent(StringTableEntry ident)
   {
      if(ident)
         gGlobalStringTable.add(ident);
   }

   void resetTables()
   {
      setCurrentStringTable(&gGlobalStringTable);
      setCurrentFloatTable(&gGlobalFloatTable);
      getGlobalFloatTable().reset();
      getGlobalStringTable().reset();
      getFunctionFloatTable().reset();
      getFunctionStringTable().reset();
      getIdentTable().reset();
   }

   void *consoleAlloc(U32 size) { return gConsoleAllocator.alloc(size);  }
   void consoleAllocReset()     { gConsoleAllocator.freeBlocks(); }

}

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

using namespace Compiler;

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

U32 CompilerStringTable::add(const char *str, bool caseSens, bool tag)
{
   // Is it already in?
   Entry **walk;
   for(walk = &list; *walk; walk = &((*walk)->next))
   {
      if((*walk)->tag != tag)
         continue;

      if(caseSens)
      {
         if(!dStrcmp((*walk)->string, str))
            return (*walk)->start;
      }
      else
      {
         if(!dStricmp((*walk)->string, str))
            return (*walk)->start;
      }
   }

   // Write it out.
   Entry *newStr = (Entry *) consoleAlloc(sizeof(Entry));
   *walk = newStr;
   newStr->next = NULL;
   newStr->start = totalLen;
   U32 len = dStrlen(str) + 1;
   if(tag && len < 7) // alloc space for the numeric tag 1 for tag, 5 for # and 1 for nul
      len = 7;
   totalLen += len;
   newStr->string = (char *) consoleAlloc(len);
   newStr->len = len;
   newStr->tag = tag;
   dStrcpy(newStr->string, str);

#ifdef EMSCRIPTEN
   consoleAlloc(2);
   Con::printf("CompilerStringTable::add(%s) %s %s @ %u:%u", str, caseSens ? "CASE" : "NOCASE", tag ? "TAG" : "NOTAG", newStr->string, len);
#endif

   return newStr->start;
}

U32 CompilerStringTable::addIntString(U32 value)
{
   dSprintf(buf, sizeof(buf), "%d", value);
   return add(buf);
}

U32 CompilerStringTable::addFloatString(F64 value)
{
   dSprintf(buf, sizeof(buf), "%.9g", value);
   return add(buf);
}
void CompilerStringTable::reset()
{
   list = NULL;
   totalLen = 0;
}
char *CompilerStringTable::build()
{
   char *ret = new char[totalLen];
   for(Entry *walk = list; walk; walk = walk->next)
      dStrcpy(ret + walk->start, walk->string);
   return ret;
}

void CompilerStringTable::write(Stream &st)
{
   st.write(totalLen);
   for(Entry *walk = list; walk; walk = walk->next)
      st.write(walk->len, walk->string);
}

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

U32 CompilerFloatTable::add(F64 value)
{
   Entry **walk;
   U32 i = 0;
   for(walk = &list; *walk; walk = &((*walk)->next), i++)
      if(value == (*walk)->val)
         return i;
   Entry *newFloat = (Entry *) consoleAlloc(sizeof(Entry));
   newFloat->val = value;
   newFloat->next = NULL;
   count++;
   *walk = newFloat;
   return count-1;
}
void CompilerFloatTable::reset()
{
   list = NULL;
   count = 0;
}
F64 *CompilerFloatTable::build()
{
   F64 *ret = new F64[count];
   U32 i = 0;
   for(Entry *walk = list; walk; walk = walk->next, i++)
      ret[i] = walk->val;
   return ret;
}

void CompilerFloatTable::write(Stream &st)
{
   st.write(count);
   for(Entry *walk = list; walk; walk = walk->next)
      st.write(walk->val);
}

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

void CompilerIdentTable::reset()
{
   list = NULL;
}

void CompilerIdentTable::add(StringTableEntry ste, U32 ip)
{
   U32 index = gGlobalStringTable.add(ste, false);
   Entry *newEntry = (Entry *) consoleAlloc(sizeof(Entry));
   newEntry->offset = index;
   newEntry->ip = ip;
   for(Entry *walk = list; walk; walk = walk->next)
   {
      if(walk->offset == index)
      {
         newEntry->nextIdent = walk->nextIdent;
         walk->nextIdent = newEntry;
         return;
      }
   }
   newEntry->next = list;
   list = newEntry;
   newEntry->nextIdent = NULL;
}

void CompilerIdentTable::write(Stream &st)
{
   U32 count = 0;
   Entry * walk;
   for(walk = list; walk; walk = walk->next)
      count++;
   st.write(count);
   for(walk = list; walk; walk = walk->next)
   {
      U32 ec = 0;
      Entry * el;
      for(el = walk; el; el = el->nextIdent)
         ec++;
      st.write(walk->offset);
      st.write(ec);
      for(el = walk; el; el = el->nextIdent)
         st.write(el->ip);
   }
}
<commit_msg>Don't dump string table in emscripten build<commit_after>//-----------------------------------------------------------------------------
// Copyright (c) 2013 GarageGames, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
//-----------------------------------------------------------------------------

#include "platform/platform.h"
#include "console/console.h"
#include "debug/telnetDebugger.h"
#include "platform/event.h"

#include "console/ast.h"
#include "collection/findIterator.h"
#include "io/resource/resourceManager.h"

#include "string/findMatch.h"
#include "console/consoleInternal.h"
#include "io/fileStream.h"
#include "console/compiler.h"

#include "sim/simBase.h"

namespace Compiler
{

   F64 consoleStringToNumber(const char *str, StringTableEntry file, U32 line)
   {
      F64 val = dAtof(str);
      if(val != 0)
         return val;
      else if(!dStricmp(str, "true"))
         return 1;
      else if(!dStricmp(str, "false"))
         return 0;
      else if(file)
      {
         Con::warnf(ConsoleLogEntry::General, "%s (%d): string always evaluates to 0.", file, line);
         return 0;
      }
      return 0;
   }

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

   CompilerStringTable *gCurrentStringTable, gGlobalStringTable, gFunctionStringTable;
   CompilerFloatTable  *gCurrentFloatTable,  gGlobalFloatTable,  gFunctionFloatTable;
   DataChunker          gConsoleAllocator;
   CompilerIdentTable   gIdentTable;
   CodeBlock           *gCurBreakBlock;

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

   CodeBlock *getBreakCodeBlock()         { return gCurBreakBlock; }
   void setBreakCodeBlock(CodeBlock *cb)  { gCurBreakBlock = cb;   }

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

   U32 evalSTEtoU32(StringTableEntry ste, U32)
   {
      return *((U32 *) &ste);
   }

   U32 compileSTEtoU32(StringTableEntry ste, U32 ip)
   {
      if(ste)
         getIdentTable().add(ste, ip);
      return 0;
   }

   U32 (*STEtoU32)(StringTableEntry ste, U32 ip) = evalSTEtoU32;

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

   bool gSyntaxError = false;

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

   CompilerStringTable *getCurrentStringTable()  { return gCurrentStringTable;  }
   CompilerStringTable &getGlobalStringTable()   { return gGlobalStringTable;   }
   CompilerStringTable &getFunctionStringTable() { return gFunctionStringTable; }

   void setCurrentStringTable (CompilerStringTable* cst) { gCurrentStringTable  = cst; }

   CompilerFloatTable *getCurrentFloatTable()    { return gCurrentFloatTable;   }
   CompilerFloatTable &getGlobalFloatTable()     { return gGlobalFloatTable;    }
   CompilerFloatTable &getFunctionFloatTable()   { return gFunctionFloatTable; }

   void setCurrentFloatTable (CompilerFloatTable* cst) { gCurrentFloatTable  = cst; }

   CompilerIdentTable &getIdentTable() { return gIdentTable; }

   void precompileIdent(StringTableEntry ident)
   {
      if(ident)
         gGlobalStringTable.add(ident);
   }

   void resetTables()
   {
      setCurrentStringTable(&gGlobalStringTable);
      setCurrentFloatTable(&gGlobalFloatTable);
      getGlobalFloatTable().reset();
      getGlobalStringTable().reset();
      getFunctionFloatTable().reset();
      getFunctionStringTable().reset();
      getIdentTable().reset();
   }

   void *consoleAlloc(U32 size) { return gConsoleAllocator.alloc(size);  }
   void consoleAllocReset()     { gConsoleAllocator.freeBlocks(); }

}

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

using namespace Compiler;

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

U32 CompilerStringTable::add(const char *str, bool caseSens, bool tag)
{
   // Is it already in?
   Entry **walk;
   for(walk = &list; *walk; walk = &((*walk)->next))
   {
      if((*walk)->tag != tag)
         continue;

      if(caseSens)
      {
         if(!dStrcmp((*walk)->string, str))
            return (*walk)->start;
      }
      else
      {
         if(!dStricmp((*walk)->string, str))
            return (*walk)->start;
      }
   }

   // Write it out.
   Entry *newStr = (Entry *) consoleAlloc(sizeof(Entry));
   *walk = newStr;
   newStr->next = NULL;
   newStr->start = totalLen;
   U32 len = dStrlen(str) + 1;
   if(tag && len < 7) // alloc space for the numeric tag 1 for tag, 5 for # and 1 for nul
      len = 7;
   totalLen += len;
   newStr->string = (char *) consoleAlloc(len);
   newStr->len = len;
   newStr->tag = tag;
   dStrcpy(newStr->string, str);

#ifdef EMSCRIPTEN
   consoleAlloc(2);
   //Con::printf("CompilerStringTable::add(%s) %s %s @ %u:%u", str, caseSens ? "CASE" : "NOCASE", tag ? "TAG" : "NOTAG", newStr->string, len);
#endif

   return newStr->start;
}

U32 CompilerStringTable::addIntString(U32 value)
{
   dSprintf(buf, sizeof(buf), "%d", value);
   return add(buf);
}

U32 CompilerStringTable::addFloatString(F64 value)
{
   dSprintf(buf, sizeof(buf), "%.9g", value);
   return add(buf);
}
void CompilerStringTable::reset()
{
   list = NULL;
   totalLen = 0;
}
char *CompilerStringTable::build()
{
   char *ret = new char[totalLen];
   for(Entry *walk = list; walk; walk = walk->next)
      dStrcpy(ret + walk->start, walk->string);
   return ret;
}

void CompilerStringTable::write(Stream &st)
{
   st.write(totalLen);
   for(Entry *walk = list; walk; walk = walk->next)
      st.write(walk->len, walk->string);
}

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

U32 CompilerFloatTable::add(F64 value)
{
   Entry **walk;
   U32 i = 0;
   for(walk = &list; *walk; walk = &((*walk)->next), i++)
      if(value == (*walk)->val)
         return i;
   Entry *newFloat = (Entry *) consoleAlloc(sizeof(Entry));
   newFloat->val = value;
   newFloat->next = NULL;
   count++;
   *walk = newFloat;
   return count-1;
}
void CompilerFloatTable::reset()
{
   list = NULL;
   count = 0;
}
F64 *CompilerFloatTable::build()
{
   F64 *ret = new F64[count];
   U32 i = 0;
   for(Entry *walk = list; walk; walk = walk->next, i++)
      ret[i] = walk->val;
   return ret;
}

void CompilerFloatTable::write(Stream &st)
{
   st.write(count);
   for(Entry *walk = list; walk; walk = walk->next)
      st.write(walk->val);
}

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

void CompilerIdentTable::reset()
{
   list = NULL;
}

void CompilerIdentTable::add(StringTableEntry ste, U32 ip)
{
   U32 index = gGlobalStringTable.add(ste, false);
   Entry *newEntry = (Entry *) consoleAlloc(sizeof(Entry));
   newEntry->offset = index;
   newEntry->ip = ip;
   for(Entry *walk = list; walk; walk = walk->next)
   {
      if(walk->offset == index)
      {
         newEntry->nextIdent = walk->nextIdent;
         walk->nextIdent = newEntry;
         return;
      }
   }
   newEntry->next = list;
   list = newEntry;
   newEntry->nextIdent = NULL;
}

void CompilerIdentTable::write(Stream &st)
{
   U32 count = 0;
   Entry * walk;
   for(walk = list; walk; walk = walk->next)
      count++;
   st.write(count);
   for(walk = list; walk; walk = walk->next)
   {
      U32 ec = 0;
      Entry * el;
      for(el = walk; el; el = el->nextIdent)
         ec++;
      st.write(walk->offset);
      st.write(ec);
      for(el = walk; el; el = el->nextIdent)
         st.write(el->ip);
   }
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_scrub.C $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_mss_scrub.C
/// @brief Begin background scrub
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <p9_mss_scrub.H>

#include <lib/dimm/rank.H>
#include <lib/mcbist/address.H>
#include <lib/mcbist/mcbist.H>
#include <lib/mcbist/patterns.H>
#include <lib/mcbist/memdiags.H>
#include <lib/mcbist/sim.H>
#include <lib/utils/count_dimm.H>

using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_SYSTEM;
using fapi2::FAPI2_RC_SUCCESS;

///
/// @brief Begin background scrub
/// @param[in] i_target MCBIST
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_scrub( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
    FAPI_INF("Start mss scrub");

    // If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
    // attributes for the PHY, etc.
    if (mss::count_dimm(i_target) == 0)
    {
        FAPI_INF("... skipping scrub for %s - no DIMM ...", mss::c_str(i_target));
        return fapi2::FAPI2_RC_SUCCESS;
    }

    // If we're running in the simulator, we want to only touch the addresses which training touched
    uint8_t is_sim = 0;
    bool l_poll_results = false;
    fapi2::buffer<uint64_t> l_status;

    // A small vector of addresses to poll during the polling loop
    static const std::vector<mss::poll_probe<fapi2::TARGET_TYPE_MCBIST>> l_probes =
    {
        {i_target, "mcbist current address", MCBIST_MCBMCATQ},
    };

    // We'll fill in the initial delay below
    mss::poll_parameters l_poll_parameters(0, 200, 100 * mss::DELAY_1MS, 200, 500);
    uint64_t l_memory_size = 0;

    FAPI_TRY( mss::eff_memory_size(i_target, l_memory_size) );
    l_poll_parameters.iv_initial_delay = mss::calculate_initial_delay(i_target, (l_memory_size * mss::BYTES_PER_GB));

    FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_IS_SIMULATION, fapi2::Target<TARGET_TYPE_SYSTEM>(), is_sim) );

    if (is_sim)
    {
        // Use some sort of pattern in sim in case the verification folks need to look for something
        // TK. Need a verification pattern. This is a not-good pattern for verification ... We don't really
        // have a good pattern for verification defined.
        FAPI_INF("running mss sim init in place of scrub");
        return mss::mcbist::sim::sf_init(i_target, mss::mcbist::PATTERN_0);
    }

    // In Cronus on hardware (which is how we got here - f/w doesn't call this) we want
    // to call sf_init (0's)
    // TK we need to check FIR given the way this is right now, we should adjust with better stop
    // conditions when we learn more about what we want to find in the lab
    FAPI_TRY( memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) );

    // Poll for completion.
    l_poll_results = mss::poll(i_target, MCBIST_MCBISTFIRQ, l_poll_parameters,
                               [&l_status](const size_t poll_remaining,
                                           const fapi2::buffer<uint64_t>& stat_reg) -> bool
    {
        FAPI_DBG("mcbist firq 0x%llx, remaining: %d", stat_reg, poll_remaining);
        l_status = stat_reg;
        return l_status.getBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() == true;
    },
    l_probes);

    FAPI_ASSERT( l_poll_results == true,
                 fapi2::MSS_MEMDIAGS_SUPERFAST_INIT_FAILED_TO_INIT().set_TARGET(i_target),
                 "p9_mss_scrub (init) timedout %s", mss::c_str(i_target) );

fapi_try_exit:
    return fapi2::current_err;
}
<commit_msg>Add more polling loops to mss_scrub<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_scrub.C $    */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */

///
/// @file p9_mss_scrub.C
/// @brief Begin background scrub
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 1
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <p9_mss_scrub.H>

#include <lib/dimm/rank.H>
#include <lib/mcbist/address.H>
#include <lib/mcbist/mcbist.H>
#include <lib/mcbist/patterns.H>
#include <lib/mcbist/memdiags.H>
#include <lib/mcbist/sim.H>
#include <lib/utils/count_dimm.H>

using fapi2::TARGET_TYPE_MCBIST;
using fapi2::TARGET_TYPE_MCA;
using fapi2::TARGET_TYPE_SYSTEM;
using fapi2::FAPI2_RC_SUCCESS;

///
/// @brief Begin background scrub
/// @param[in] i_target MCBIST
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode p9_mss_scrub( const fapi2::Target<TARGET_TYPE_MCBIST>& i_target )
{
    FAPI_INF("Start mss scrub");

    // If there are no DIMM we don't need to bother. In fact, we can't as we didn't setup
    // attributes for the PHY, etc.
    if (mss::count_dimm(i_target) == 0)
    {
        FAPI_INF("... skipping scrub for %s - no DIMM ...", mss::c_str(i_target));
        return fapi2::FAPI2_RC_SUCCESS;
    }

    // If we're running in the simulator, we want to only touch the addresses which training touched
    uint8_t is_sim = 0;
    bool l_poll_results = false;
    fapi2::buffer<uint64_t> l_status;

    // A small vector of addresses to poll during the polling loop
    static const std::vector<mss::poll_probe<fapi2::TARGET_TYPE_MCBIST>> l_probes =
    {
        {i_target, "mcbist current address", MCBIST_MCBMCATQ},
    };

    // We'll fill in the initial delay below
    mss::poll_parameters l_poll_parameters(0, 200, 100 * mss::DELAY_1MS, 200, 1000);
    uint64_t l_memory_size = 0;

    FAPI_TRY( mss::eff_memory_size(i_target, l_memory_size) );
    l_poll_parameters.iv_initial_delay = mss::calculate_initial_delay(i_target, (l_memory_size * mss::BYTES_PER_GB));

    FAPI_TRY( FAPI_ATTR_GET(fapi2::ATTR_IS_SIMULATION, fapi2::Target<TARGET_TYPE_SYSTEM>(), is_sim) );

    if (is_sim)
    {
        // Use some sort of pattern in sim in case the verification folks need to look for something
        // TK. Need a verification pattern. This is a not-good pattern for verification ... We don't really
        // have a good pattern for verification defined.
        FAPI_INF("running mss sim init in place of scrub");
        return mss::mcbist::sim::sf_init(i_target, mss::mcbist::PATTERN_0);
    }

    // In Cronus on hardware (which is how we got here - f/w doesn't call this) we want
    // to call sf_init (0's)
    // TK we need to check FIR given the way this is right now, we should adjust with better stop
    // conditions when we learn more about what we want to find in the lab
    FAPI_TRY( memdiags::sf_init(i_target, mss::mcbist::PATTERN_0) );

    // Poll for completion.
    l_poll_results = mss::poll(i_target, MCBIST_MCBISTFIRQ, l_poll_parameters,
                               [&l_status](const size_t poll_remaining,
                                           const fapi2::buffer<uint64_t>& stat_reg) -> bool
    {
        FAPI_DBG("mcbist firq 0x%llx, remaining: %d", stat_reg, poll_remaining);
        l_status = stat_reg;
        return l_status.getBit<MCBIST_MCBISTFIRQ_MCBIST_PROGRAM_COMPLETE>() == true;
    },
    l_probes);

    FAPI_ASSERT( l_poll_results == true,
                 fapi2::MSS_MEMDIAGS_SUPERFAST_INIT_FAILED_TO_INIT().set_TARGET(i_target),
                 "p9_mss_scrub (init) timedout %s", mss::c_str(i_target) );

fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <algorithm>
#include <vector>

#include "mlir/IR/Builders.h"  // from @llvm-project
#include "mlir/IR/BuiltinOps.h"  // from @llvm-project
#include "mlir/IR/UseDefLists.h"  // from @llvm-project
#include "mlir/Pass/Pass.h"  // from @llvm-project
#include "mlir/Support/LLVM.h"  // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model.h"

namespace mlir {
namespace tf_saved_model {
namespace {

// This pass will replace a func's bound inputs which are bound to
// tf.ReadVariable ops global tensors with tf.Const ops inside the func's body.
// If this pass runs successfully, the resultant IR will be guaranteed to:
//
// 1. Not contain any tf_saved_model.global_tensor ops
// 2. Not contain any  tf_saved_model.bound_input arg attrs on tf_saved_model
// exported functions
// Else, the pass fails.
//
// The reason this pass has this contract is so that once this succeeds, we know
// the IR is in correct form for inference backends (like lite) that do not
// support resources/variables . Further, this contract also ensures that this
// pass lowers from saved model to pure TF. Hence it fails, if it cannot lower.
struct FreezeGlobalTensorsPass
    : public PassWrapper<FreezeGlobalTensorsPass, OperationPass<ModuleOp>> {
  void runOnOperation() override;
};

void FreezeGlobalTensorsPass::runOnOperation() {
  auto module = getOperation();
  if (!tf_saved_model::HasTfSavedModelSemantics(module)) {
    return;
  }
  SymbolTable symbol_table(module);
  DenseSet<Operation*> frozen_global_tensors;

  for (auto func : module.getOps<FuncOp>()) {
    SmallVector<unsigned, 4> args_to_erase;
    OpBuilder builder(func.getBody());

    for (int i = 0, e = func.getNumArguments(); i < e; ++i) {
      SmallVector<TF::ReadVariableOp, 4> read_variable_ops_to_erase;
      auto global_tensor =
          LookupBoundInputOfType<GlobalTensorOp>(func, i, symbol_table);

      if (!global_tensor) continue;
      frozen_global_tensors.insert(global_tensor);

      // This pass assumes that all global tensors as immutable (e.g. by a
      // previous optimize global tensors pass). If not, this pass has to fail
      // since it cannot perform one of its goals.
      if (global_tensor.is_mutable()) {
        global_tensor.emitError() << "is not immutable, try running "
                                     "tf-saved-model-optimize-global-tensors "
                                     "to prove tensors are immutable";
        return signalPassFailure();
      }

      auto arg = func.getArgument(i);
      for (auto user : arg.getUsers()) {
        if (auto read_op = llvm::dyn_cast<TF::ReadVariableOp>(user)) {
          // Collect all read variable ops so that all its uses can be replaced
          // with the tf.constant corresponding to the global tensor op.
          read_variable_ops_to_erase.push_back(read_op);
        } else {
          // Current assumption is all users are tf.ReadVariableOp. Need to
          // expand this to handle control flow and call ops.
          user->emitError() << "could not rewrite use of immutable bound input";
          return signalPassFailure();
        }
      }

      // Replace the arg with a tf.Const op in the function body.
      builder.setInsertionPointToStart(&func.getBody().front());
      auto const_op = builder.create<TF::ConstOp>(global_tensor.getLoc(),
                                                  global_tensor.value());
      args_to_erase.push_back(i);
      for (auto read_op : read_variable_ops_to_erase) {
        read_op.getResult().replaceAllUsesWith(const_op.getResult());
        read_op.erase();
      }
    }
    func.eraseArguments(args_to_erase);
  }
  // Erase all global tensors that were frozen.
  for (auto global_tensor : frozen_global_tensors) {
    global_tensor->erase();
  }

  if (!module.getOps<GlobalTensorOp>().empty()) {
    module.emitError() << "could not freeze all global tensors in the module";
    return signalPassFailure();
  }
}

}  // namespace

// For "opt" to pick up this pass.
static PassRegistration<FreezeGlobalTensorsPass> pass(
    "tf-saved-model-freeze-global-tensors",
    "Freeze tf_saved_model.global_tensor's in func bodies.");

std::unique_ptr<OperationPass<ModuleOp>> CreateFreezeGlobalTensorsPass() {
  return std::make_unique<FreezeGlobalTensorsPass>();
}

}  // namespace tf_saved_model
}  // namespace mlir
<commit_msg>Refine an error message when MLIR converter encounters mutable variable cases<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/

#include <algorithm>
#include <vector>

#include "mlir/IR/Builders.h"  // from @llvm-project
#include "mlir/IR/BuiltinOps.h"  // from @llvm-project
#include "mlir/IR/UseDefLists.h"  // from @llvm-project
#include "mlir/Pass/Pass.h"  // from @llvm-project
#include "mlir/Support/LLVM.h"  // from @llvm-project
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_ops.h"
#include "tensorflow/compiler/mlir/tensorflow/ir/tf_saved_model.h"

namespace mlir {
namespace tf_saved_model {
namespace {

// This pass will replace a func's bound inputs which are bound to
// tf.ReadVariable ops global tensors with tf.Const ops inside the func's body.
// If this pass runs successfully, the resultant IR will be guaranteed to:
//
// 1. Not contain any tf_saved_model.global_tensor ops
// 2. Not contain any  tf_saved_model.bound_input arg attrs on tf_saved_model
// exported functions
// Else, the pass fails.
//
// The reason this pass has this contract is so that once this succeeds, we know
// the IR is in correct form for inference backends (like lite) that do not
// support resources/variables . Further, this contract also ensures that this
// pass lowers from saved model to pure TF. Hence it fails, if it cannot lower.
struct FreezeGlobalTensorsPass
    : public PassWrapper<FreezeGlobalTensorsPass, OperationPass<ModuleOp>> {
  void runOnOperation() override;
};

void FreezeGlobalTensorsPass::runOnOperation() {
  auto module = getOperation();
  if (!tf_saved_model::HasTfSavedModelSemantics(module)) {
    return;
  }
  SymbolTable symbol_table(module);
  DenseSet<Operation*> frozen_global_tensors;

  for (auto func : module.getOps<FuncOp>()) {
    SmallVector<unsigned, 4> args_to_erase;
    OpBuilder builder(func.getBody());

    for (int i = 0, e = func.getNumArguments(); i < e; ++i) {
      SmallVector<TF::ReadVariableOp, 4> read_variable_ops_to_erase;
      auto global_tensor =
          LookupBoundInputOfType<GlobalTensorOp>(func, i, symbol_table);

      if (!global_tensor) continue;
      frozen_global_tensors.insert(global_tensor);

      // This pass assumes that all global tensors as immutable (e.g. by a
      // previous optimize global tensors pass). If not, this pass has to fail
      // since it cannot perform one of its goals.
      if (global_tensor.is_mutable()) {
        global_tensor.emitError()
            << "is not immutable, try removing mutable variables in your model "
               "since mutable variables are currently not supported through "
               "this converter";
        return signalPassFailure();
      }

      auto arg = func.getArgument(i);
      for (auto user : arg.getUsers()) {
        if (auto read_op = llvm::dyn_cast<TF::ReadVariableOp>(user)) {
          // Collect all read variable ops so that all its uses can be replaced
          // with the tf.constant corresponding to the global tensor op.
          read_variable_ops_to_erase.push_back(read_op);
        } else {
          // Current assumption is all users are tf.ReadVariableOp. Need to
          // expand this to handle control flow and call ops.
          user->emitError() << "could not rewrite use of immutable bound input";
          return signalPassFailure();
        }
      }

      // Replace the arg with a tf.Const op in the function body.
      builder.setInsertionPointToStart(&func.getBody().front());
      auto const_op = builder.create<TF::ConstOp>(global_tensor.getLoc(),
                                                  global_tensor.value());
      args_to_erase.push_back(i);
      for (auto read_op : read_variable_ops_to_erase) {
        read_op.getResult().replaceAllUsesWith(const_op.getResult());
        read_op.erase();
      }
    }
    func.eraseArguments(args_to_erase);
  }
  // Erase all global tensors that were frozen.
  for (auto global_tensor : frozen_global_tensors) {
    global_tensor->erase();
  }

  if (!module.getOps<GlobalTensorOp>().empty()) {
    module.emitError() << "could not freeze all global tensors in the module";
    return signalPassFailure();
  }
}

}  // namespace

// For "opt" to pick up this pass.
static PassRegistration<FreezeGlobalTensorsPass> pass(
    "tf-saved-model-freeze-global-tensors",
    "Freeze tf_saved_model.global_tensor's in func bodies.");

std::unique_ptr<OperationPass<ModuleOp>> CreateFreezeGlobalTensorsPass() {
  return std::make_unique<FreezeGlobalTensorsPass>();
}

}  // namespace tf_saved_model
}  // namespace mlir
<|endoftext|>


<commit_before>#include "apps_starter.h"

std::vector<job> apps_vect;			// Определение вектора запущенных программ
struct termios hos_tmode;			// настройки терминала для hos

void sighandler(int signo)
{
	if (signo == SIGTSTP) {

	}

	if (signo == SIGINT) {

	}
}

// Спящего процесса возобновление
void fg_job(job &j)
{
	int status;
	std::vector<job>::iterator it;

	// Терминальной группы главной установка
	j.running = true;
	tcsetpgrp(STDIN_FILENO, j.pid);

	// Спящий процесс будим мы
	kill(-j.pid, SIGCONT);
	waitpid(j.pid, &status, WUNTRACED);

	if(WIFSTOPPED(status)) {
		j.running = false;
		tcsetpgrp(STDIN_FILENO, getpid());
		tcgetattr(STDIN_FILENO, &j.tmode);
		tcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);
	}

	// Если завершился процесс - удаляем из вектора процессов его
	if(WIFEXITED(status)) {
		tcsetpgrp(STDIN_FILENO, getpid());
		tcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);
		for(it = apps_vect.begin() ; it != apps_vect.end(); it++)
			if (it->pid == j.pid)
				apps_vect.erase(it);
	}
}

// Сигналов обработку определяем мы
void init_signals()
{
	signal(SIGINT, &sighandler);
	signal(SIGTSTP, &sighandler);
	signal(SIGTTIN, SIG_IGN);
	signal(SIGTTOU, SIG_IGN);
}

// Фоновых процессов список отображаем мы
void list_process() {
	timeout(-1);

	std::vector <std::string>	apps_names;

	DLGSTR						apps_dlg	= {};

	unsigned int				maxX,
								maxY;

	int							key_pressed;

	getmaxyx(stdscr, maxY, maxX);

	apps_dlg.title			= "Background applications";
	apps_dlg.style			= RED_WIN;
	apps_dlg.xpos			= maxX / 2 - llength(apps_dlg.title) / 2;
	apps_dlg.ypos			= maxY / 2;
	apps_dlg.ymax			= maxY / 2;
	apps_dlg.border_menu	= true;

	// Не делаем ничего, вектор если пуст
	if(!apps_vect.empty()) {
		for (unsigned int	i	= 0; i < apps_vect.size(); i++) {
			apps_names.push_back(apps_vect[i].name);
		}

		key_pressed	= 0;

		while (key_pressed != 27) {
			menu_win(apps_dlg, apps_names);
			key_pressed	= getch();					// пользователя ввод обрабатываем мы

			switch (key_pressed) {
				case KEY_UP:	if (apps_dlg.selected != 0)
									apps_dlg.selected--;
								break;

				case KEY_DOWN:	if (apps_dlg.selected != apps_names.size())
									apps_dlg.selected++;
								break;

				case '\n':		// процесс спящий мы будим
								endwin();
								fg_job(apps_vect[apps_dlg.selected - 1]);
								init_display();
								init_color();
								break;
			}
		}
	}
}

int app_start(int number_of_app, char** argv) {
	std::string name_app	= configurator(APPS_FILE, str(number_of_app) + "_app_launcher", "", false);
	std::string path_to_dir	= configurator(APPS_FILE, str(number_of_app) + "_app_path", "", false);
	erase();
	endwin();

	int		status;
	pid_t	chpid	= fork();

	job j = {
		.name = name_app,
		.pid = chpid
	};

	j.running = true;

	// В запущенных процессов список процесс помещаем мы
	apps_vect.insert(apps_vect.end(), j);

	if (chpid == 0) {
		signal(SIGTTIN, SIG_IGN);
		signal(SIGTTOU, SIG_IGN);
		tcsetpgrp(STDIN_FILENO, getpid());
		chdir(path_to_dir.c_str());
		setpgid(getpid(), getpid());			 	// Создаём группу процессов
		if (execl(name_app.c_str(), "", NULL) == -1) 	// parent process
			exit(0);
	} else {
		waitpid(chpid, &status,WUNTRACED);
		tcsetpgrp(STDIN_FILENO, getpid());
		tcgetattr(STDIN_FILENO, &j.tmode);
		tcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);

		if (WIFSTOPPED(status)) {	/* Если пользователем процесс был остановлен */
			apps_vect.back().running = false;
		}

		if(WIFEXITED(status)) {
			apps_vect.pop_back();
		}

		init_display();
		init_color();
	}
	return 0;
}<commit_msg>Исправлено непредсказуемое поведение итератора в цикле (str 42 in apps_starter.cpp)<commit_after>#include "apps_starter.h"

std::vector<job> apps_vect;			// Определение вектора запущенных программ
struct termios hos_tmode;			// настройки терминала для hos

void sighandler(int signo)
{
	if (signo == SIGTSTP) {

	}

	if (signo == SIGINT) {

	}
}

// Спящего процесса возобновление
void fg_job(job &j)
{
	int status;
	std::vector<job>::iterator it;

	// Терминальной группы главной установка
	j.running = true;
	tcsetpgrp(STDIN_FILENO, j.pid);

	// Спящий процесс будим мы
	kill(-j.pid, SIGCONT);
	waitpid(j.pid, &status, WUNTRACED);

	if(WIFSTOPPED(status)) {
		j.running = false;
		tcsetpgrp(STDIN_FILENO, getpid());
		tcgetattr(STDIN_FILENO, &j.tmode);
		tcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);
	}

	// Если завершился процесс - удаляем из вектора процессов его
	if(WIFEXITED(status)) {
		tcsetpgrp(STDIN_FILENO, getpid());
		tcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);
		for(it = apps_vect.begin() ; it < apps_vect.end(); ++it)
			if (it->pid == j.pid)
				apps_vect.erase(it);
	}
}

// Сигналов обработку определяем мы
void init_signals()
{
	signal(SIGINT, &sighandler);
	signal(SIGTSTP, &sighandler);
	signal(SIGTTIN, SIG_IGN);
	signal(SIGTTOU, SIG_IGN);
}

// Фоновых процессов список отображаем мы
void list_process() {
	timeout(-1);

	std::vector <std::string>	apps_names;

	DLGSTR						apps_dlg	= {};

	unsigned int				maxX,
								maxY;

	int							key_pressed;

	getmaxyx(stdscr, maxY, maxX);

	apps_dlg.title			= "Background applications";
	apps_dlg.style			= RED_WIN;
	apps_dlg.xpos			= maxX / 2 - llength(apps_dlg.title) / 2;
	apps_dlg.ypos			= maxY / 2;
	apps_dlg.ymax			= maxY / 2;
	apps_dlg.border_menu	= true;

	// Не делаем ничего, вектор если пуст
	if(!apps_vect.empty()) {
		for (unsigned int	i	= 0; i < apps_vect.size(); i++) {
			apps_names.push_back(apps_vect[i].name);
		}

		key_pressed	= 0;

		while (key_pressed != 27) {
			menu_win(apps_dlg, apps_names);
			key_pressed	= getch();					// пользователя ввод обрабатываем мы

			switch (key_pressed) {
				case KEY_UP:	if (apps_dlg.selected != 0)
									apps_dlg.selected--;
								break;

				case KEY_DOWN:	if (apps_dlg.selected != apps_names.size())
									apps_dlg.selected++;
								break;

				case '\n':		// процесс спящий мы будим
								endwin();
								fg_job(apps_vect[apps_dlg.selected - 1]);
								init_display();
								init_color();
								break;
			}
		}
	}
}

int app_start(int number_of_app, char** argv) {
	std::string name_app	= configurator(APPS_FILE, str(number_of_app) + "_app_launcher", "", false);
	std::string path_to_dir	= configurator(APPS_FILE, str(number_of_app) + "_app_path", "", false);
	erase();
	endwin();

	int		status;
	pid_t	chpid	= fork();

	job j = {
		.name = name_app,
		.pid = chpid
	};

	j.running = true;

	// В запущенных процессов список процесс помещаем мы
	apps_vect.insert(apps_vect.end(), j);

	if (chpid == 0) {
		signal(SIGTTIN, SIG_IGN);
		signal(SIGTTOU, SIG_IGN);
		tcsetpgrp(STDIN_FILENO, getpid());
		chdir(path_to_dir.c_str());
		setpgid(getpid(), getpid());			 	// Создаём группу процессов
		if (execl(name_app.c_str(), "", NULL) == -1) 	// parent process
			exit(0);
	} else {
		waitpid(chpid, &status,WUNTRACED);
		tcsetpgrp(STDIN_FILENO, getpid());
		tcgetattr(STDIN_FILENO, &j.tmode);
		tcsetattr(STDIN_FILENO, TCSADRAIN, &hos_tmode);

		if (WIFSTOPPED(status)) {	/* Если пользователем процесс был остановлен */
			apps_vect.back().running = false;
		}

		if(WIFEXITED(status)) {
			apps_vect.pop_back();
		}

		init_display();
		init_color();
	}
	return 0;
}<|endoftext|>


<commit_before>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                              SOFA :: Framework                              *
*                                                                             *
* Authors: The SOFA Team (see Authors.txt)                                    *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include <sofa/core/MultiMapping.inl>
#include <sofa/defaulttype/Vec3Types.h>
#include <sofa/defaulttype/RigidTypes.h>

namespace sofa
{

namespace core
{

using namespace sofa::defaulttype;
using namespace core::behavior;

#ifndef SOFA_FLOAT
template class MultiMapping< Vec1dTypes, Vec1dTypes >;
template class MultiMapping< Vec3dTypes, Vec3dTypes >;
template class MultiMapping< Rigid3dTypes, Vec3dTypes >;
#endif

#ifndef SOFA_DOUBLE
template class SOFA_CORE_API MultiMapping< Vec1fTypes, Vec1fTypes >;
template class SOFA_CORE_API MultiMapping< Vec3fTypes, Vec3fTypes >;
template class SOFA_CORE_API MultiMapping< Rigid3fTypes, Vec3fTypes >;
#endif

#ifndef SOFA_FLOAT
#ifndef SOFA_DOUBLE
template class MultiMapping< Vec1dTypes, Vec1fTypes >;
template class MultiMapping< Vec1fTypes, Vec1dTypes > ;
template class MultiMapping< Vec3dTypes, Vec3fTypes >;
template class MultiMapping< Vec3fTypes, Vec3dTypes > ;
template class MultiMapping< Rigid3dTypes, Vec3fTypes >;
template class MultiMapping< Rigid3fTypes, Vec3dTypes >;
#endif
#endif

} // namespace core

} // namespace sofa
<commit_msg>r10626/sofa : core : multiMapping.cpp add template class SOFA_CORE_API to be compatible with compliant under windows<commit_after>/******************************************************************************
*       SOFA, Simulation Open-Framework Architecture, version 1.0 RC 1        *
*                (c) 2006-2011 INRIA, USTL, UJF, CNRS, MGH                    *
*                                                                             *
* This library is free software; you can redistribute it and/or modify it     *
* under the terms of the GNU Lesser General Public License as published by    *
* the Free Software Foundation; either version 2.1 of the License, or (at     *
* your option) any later version.                                             *
*                                                                             *
* This library is distributed in the hope that it will be useful, but WITHOUT *
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or       *
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License *
* for more details.                                                           *
*                                                                             *
* You should have received a copy of the GNU Lesser General Public License    *
* along with this library; if not, write to the Free Software Foundation,     *
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301 USA.          *
*******************************************************************************
*                              SOFA :: Framework                              *
*                                                                             *
* Authors: The SOFA Team (see Authors.txt)                                    *
*                                                                             *
* Contact information: contact@sofa-framework.org                             *
******************************************************************************/

#include <sofa/core/MultiMapping.inl>
#include <sofa/defaulttype/Vec3Types.h>
#include <sofa/defaulttype/RigidTypes.h>

namespace sofa
{

namespace core
{

using namespace sofa::defaulttype;
using namespace core::behavior;

#ifndef SOFA_FLOAT
template class SOFA_CORE_API MultiMapping< Vec1dTypes, Vec1dTypes >;
template class SOFA_CORE_API MultiMapping< Vec3dTypes, Vec3dTypes >;
template class SOFA_CORE_API MultiMapping< Rigid3dTypes, Vec3dTypes >;
#endif

#ifndef SOFA_DOUBLE
template class SOFA_CORE_API MultiMapping< Vec1fTypes, Vec1fTypes >;
template class SOFA_CORE_API MultiMapping< Vec3fTypes, Vec3fTypes >;
template class SOFA_CORE_API MultiMapping< Rigid3fTypes, Vec3fTypes >;
#endif

#ifndef SOFA_FLOAT
#ifndef SOFA_DOUBLE
template class MultiMapping< Vec1dTypes, Vec1fTypes >;
template class MultiMapping< Vec1fTypes, Vec1dTypes > ;
template class MultiMapping< Vec3dTypes, Vec3fTypes >;
template class MultiMapping< Vec3fTypes, Vec3dTypes > ;
template class MultiMapping< Rigid3dTypes, Vec3fTypes >;
template class MultiMapping< Rigid3fTypes, Vec3dTypes >;
#endif
#endif

} // namespace core

} // namespace sofa
<|endoftext|>


<commit_before>// ***************************************************************************
//
//   Generated automatically by genwrapper.
//   Please DO NOT EDIT this file!
//
// ***************************************************************************

#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/StaticMethodInfo>
#include <osgIntrospection/Attributes>

#include <osg/CopyOp>
#include <osg/Object>
#include <osg/Stats>
#include <osgAnimation/Action>
#include <osgAnimation/ActionVisitor>
#include <osgAnimation/StatsVisitor>
#include <osgAnimation/Timeline>

// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif

BEGIN_ENUM_REFLECTOR(osgAnimation::Timeline::TimelineStatus)
	I_DeclaringFile("osgAnimation/Timeline");
	I_EnumLabel(osgAnimation::Timeline::Play);
	I_EnumLabel(osgAnimation::Timeline::Stop);
END_REFLECTOR

TYPE_NAME_ALIAS(std::vector< osgAnimation::FrameAction >, osgAnimation::Timeline::ActionList)

TYPE_NAME_ALIAS(std::map< int COMMA  osgAnimation::Timeline::ActionList >, osgAnimation::Timeline::ActionLayers)

BEGIN_OBJECT_REFLECTOR(osgAnimation::Timeline)
	I_DeclaringFile("osgAnimation/Timeline");
	I_BaseType(osgAnimation::Action);
	I_Constructor0(____Timeline,
	               "",
	               "");
	I_ConstructorWithDefaults2(IN, const osgAnimation::Timeline &, nc, , IN, const osg::CopyOp &, op, osg::CopyOp::SHALLOW_COPY,
	                           ____Timeline__C5_Timeline_R1__C5_osg_CopyOp_R1,
	                           "",
	                           "");
	I_Method0(osg::Object *, cloneType,
	          Properties::VIRTUAL,
	          __osg_Object_P1__cloneType,
	          "Clone the type of an object, with Object* return type. ",
	          "Must be defined by derived classes. ");
	I_Method1(osg::Object *, clone, IN, const osg::CopyOp &, x,
	          Properties::VIRTUAL,
	          __osg_Object_P1__clone__C5_osg_CopyOp_R1,
	          "Clone an object, with Object* return type. ",
	          "Must be defined by derived classes. ");
	I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj,
	          Properties::VIRTUAL,
	          __bool__isSameKindAs__C5_osg_Object_P1,
	          "",
	          "");
	I_Method0(const char *, className,
	          Properties::VIRTUAL,
	          __C5_char_P1__className,
	          "return the name of the object's class type. ",
	          "Must be defined by derived classes. ");
	I_Method0(const char *, libraryName,
	          Properties::VIRTUAL,
	          __C5_char_P1__libraryName,
	          "return the name of the object's library. ",
	          "Must be defined by derived classes. The OpenSceneGraph convention is that the namespace of a library is the same as the library name. ");
	I_Method1(void, accept, IN, osgAnimation::ActionVisitor &, nv,
	          Properties::VIRTUAL,
	          __void__accept__osgAnimation_ActionVisitor_R1,
	          "",
	          "");
	I_Method0(osgAnimation::Timeline::TimelineStatus, getStatus,
	          Properties::NON_VIRTUAL,
	          __TimelineStatus__getStatus,
	          "",
	          "");
	I_Method1(const osgAnimation::Timeline::ActionList &, getActionLayer, IN, int, i,
	          Properties::NON_VIRTUAL,
	          __C5_ActionList_R1__getActionLayer__int,
	          "",
	          "");
	I_Method0(unsigned int, getCurrentFrame,
	          Properties::NON_VIRTUAL,
	          __unsigned_int__getCurrentFrame,
	          "",
	          "");
	I_Method0(double, getCurrentTime,
	          Properties::NON_VIRTUAL,
	          __double__getCurrentTime,
	          "",
	          "");
	I_Method0(void, play,
	          Properties::NON_VIRTUAL,
	          __void__play,
	          "",
	          "");
	I_Method1(void, gotoFrame, IN, unsigned int, frame,
	          Properties::NON_VIRTUAL,
	          __void__gotoFrame__unsigned_int,
	          "",
	          "");
	I_Method0(void, stop,
	          Properties::NON_VIRTUAL,
	          __void__stop,
	          "",
	          "");
	I_Method0(bool, getEvaluating,
	          Properties::NON_VIRTUAL,
	          __bool__getEvaluating,
	          "",
	          "");
	I_Method1(bool, isActive, IN, osgAnimation::Action *, activeAction,
	          Properties::NON_VIRTUAL,
	          __bool__isActive__Action_P1,
	          "",
	          "");
	I_Method1(void, removeAction, IN, osgAnimation::Action *, action,
	          Properties::NON_VIRTUAL,
	          __void__removeAction__Action_P1,
	          "",
	          "");
	I_MethodWithDefaults3(void, addActionAt, IN, unsigned int, frame, , IN, osgAnimation::Action *, action, , IN, int, priority, 0,
	                      Properties::VIRTUAL,
	                      __void__addActionAt__unsigned_int__Action_P1__int,
	                      "",
	                      "");
	I_MethodWithDefaults3(void, addActionAt, IN, double, t, , IN, osgAnimation::Action *, action, , IN, int, priority, 0,
	                      Properties::VIRTUAL,
	                      __void__addActionAt__double__Action_P1__int,
	                      "",
	                      "");
	I_MethodWithDefaults2(void, addActionNow, IN, osgAnimation::Action *, action, , IN, int, priority, 0,
	                      Properties::NON_VIRTUAL,
	                      __void__addActionNow__Action_P1__int,
	                      "",
	                      "");
	I_Method0(void, clearActions,
	          Properties::NON_VIRTUAL,
	          __void__clearActions,
	          "",
	          "");
	I_Method1(void, update, IN, double, simulationTime,
	          Properties::VIRTUAL,
	          __void__update__double,
	          "",
	          "");
	I_Method1(void, setLastFrameEvaluated, IN, unsigned int, frame,
	          Properties::NON_VIRTUAL,
	          __void__setLastFrameEvaluated__unsigned_int,
	          "",
	          "");
	I_Method1(void, setEvaluating, IN, bool, state,
	          Properties::NON_VIRTUAL,
	          __void__setEvaluating__bool,
	          "",
	          "");
	I_Method1(void, traverse, IN, osgAnimation::ActionVisitor &, visitor,
	          Properties::VIRTUAL,
	          __void__traverse__ActionVisitor_R1,
	          "",
	          "");
	I_Method1(void, setStats, IN, osg::Stats *, stats,
	          Properties::NON_VIRTUAL,
	          __void__setStats__osg_Stats_P1,
	          "",
	          "");
	I_Method0(osg::Stats *, getStats,
	          Properties::NON_VIRTUAL,
	          __osg_Stats_P1__getStats,
	          "",
	          "");
	I_Method1(void, collectStats, IN, bool, state,
	          Properties::NON_VIRTUAL,
	          __void__collectStats__bool,
	          "",
	          "");
	I_Method0(osgAnimation::StatsActionVisitor *, getStatsVisitor,
	          Properties::NON_VIRTUAL,
	          __osgAnimation_StatsActionVisitor_P1__getStatsVisitor,
	          "",
	          "");
	I_Method0(const osgAnimation::Timeline::ActionLayers &, getActionLayers,
	          Properties::NON_VIRTUAL,
	          __C5_ActionLayers_R1__getActionLayers,
	          "",
	          "");
	I_Method0(void, processPendingOperation,
	          Properties::NON_VIRTUAL,
	          __void__processPendingOperation,
	          "",
	          "");
	I_ProtectedMethod1(void, internalRemoveAction, IN, osgAnimation::Action *, action,
	                   Properties::NON_VIRTUAL,
	                   Properties::NON_CONST,
	                   __void__internalRemoveAction__Action_P1,
	                   "",
	                   "");
	I_ProtectedMethod2(void, internalAddAction, IN, int, priority, IN, const osgAnimation::FrameAction &, ftl,
	                   Properties::NON_VIRTUAL,
	                   Properties::NON_CONST,
	                   __void__internalAddAction__int__C5_FrameAction_R1,
	                   "",
	                   "");
	I_SimpleProperty(const osgAnimation::Timeline::ActionLayers &, ActionLayers,
	                 __C5_ActionLayers_R1__getActionLayers,
	                 0);
	I_SimpleProperty(unsigned int, CurrentFrame,
	                 __unsigned_int__getCurrentFrame,
	                 0);
	I_SimpleProperty(double, CurrentTime,
	                 __double__getCurrentTime,
	                 0);
	I_SimpleProperty(bool, Evaluating,
	                 __bool__getEvaluating,
	                 __void__setEvaluating__bool);
	I_SimpleProperty(unsigned int, LastFrameEvaluated,
	                 0,
	                 __void__setLastFrameEvaluated__unsigned_int);
	I_SimpleProperty(osg::Stats *, Stats,
	                 __osg_Stats_P1__getStats,
	                 __void__setStats__osg_Stats_P1);
	I_SimpleProperty(osgAnimation::StatsActionVisitor *, StatsVisitor,
	                 __osgAnimation_StatsActionVisitor_P1__getStatsVisitor,
	                 0);
	I_SimpleProperty(osgAnimation::Timeline::TimelineStatus, Status,
	                 __TimelineStatus__getStatus,
	                 0);
END_REFLECTOR

STD_MAP_REFLECTOR(std::map< int COMMA  osgAnimation::Timeline::ActionList >)

<commit_msg>Updated wrappers<commit_after>// ***************************************************************************
//
//   Generated automatically by genwrapper.
//   Please DO NOT EDIT this file!
//
// ***************************************************************************

#include <osgIntrospection/ReflectionMacros>
#include <osgIntrospection/TypedMethodInfo>
#include <osgIntrospection/StaticMethodInfo>
#include <osgIntrospection/Attributes>

#include <osg/CopyOp>
#include <osg/Object>
#include <osg/Stats>
#include <osgAnimation/Action>
#include <osgAnimation/ActionVisitor>
#include <osgAnimation/AnimationManagerBase>
#include <osgAnimation/StatsVisitor>
#include <osgAnimation/Timeline>

// Must undefine IN and OUT macros defined in Windows headers
#ifdef IN
#undef IN
#endif
#ifdef OUT
#undef OUT
#endif

BEGIN_ENUM_REFLECTOR(osgAnimation::Timeline::TimelineStatus)
	I_DeclaringFile("osgAnimation/Timeline");
	I_EnumLabel(osgAnimation::Timeline::Play);
	I_EnumLabel(osgAnimation::Timeline::Stop);
END_REFLECTOR

TYPE_NAME_ALIAS(std::vector< osgAnimation::FrameAction >, osgAnimation::Timeline::ActionList)

TYPE_NAME_ALIAS(std::map< int COMMA  osgAnimation::Timeline::ActionList >, osgAnimation::Timeline::ActionLayers)

BEGIN_OBJECT_REFLECTOR(osgAnimation::Timeline)
	I_DeclaringFile("osgAnimation/Timeline");
	I_BaseType(osgAnimation::Action);
	I_Constructor0(____Timeline,
	               "",
	               "");
	I_ConstructorWithDefaults2(IN, const osgAnimation::Timeline &, nc, , IN, const osg::CopyOp &, op, osg::CopyOp::SHALLOW_COPY,
	                           ____Timeline__C5_Timeline_R1__C5_osg_CopyOp_R1,
	                           "",
	                           "");
	I_Method0(osg::Object *, cloneType,
	          Properties::VIRTUAL,
	          __osg_Object_P1__cloneType,
	          "Clone the type of an object, with Object* return type. ",
	          "Must be defined by derived classes. ");
	I_Method1(osg::Object *, clone, IN, const osg::CopyOp &, x,
	          Properties::VIRTUAL,
	          __osg_Object_P1__clone__C5_osg_CopyOp_R1,
	          "Clone an object, with Object* return type. ",
	          "Must be defined by derived classes. ");
	I_Method1(bool, isSameKindAs, IN, const osg::Object *, obj,
	          Properties::VIRTUAL,
	          __bool__isSameKindAs__C5_osg_Object_P1,
	          "",
	          "");
	I_Method0(const char *, className,
	          Properties::VIRTUAL,
	          __C5_char_P1__className,
	          "return the name of the object's class type. ",
	          "Must be defined by derived classes. ");
	I_Method0(const char *, libraryName,
	          Properties::VIRTUAL,
	          __C5_char_P1__libraryName,
	          "return the name of the object's library. ",
	          "Must be defined by derived classes. The OpenSceneGraph convention is that the namespace of a library is the same as the library name. ");
	I_Method1(void, accept, IN, osgAnimation::ActionVisitor &, nv,
	          Properties::VIRTUAL,
	          __void__accept__osgAnimation_ActionVisitor_R1,
	          "",
	          "");
	I_Method0(osgAnimation::Timeline::TimelineStatus, getStatus,
	          Properties::NON_VIRTUAL,
	          __TimelineStatus__getStatus,
	          "",
	          "");
	I_Method1(const osgAnimation::Timeline::ActionList &, getActionLayer, IN, int, i,
	          Properties::NON_VIRTUAL,
	          __C5_ActionList_R1__getActionLayer__int,
	          "",
	          "");
	I_Method0(unsigned int, getCurrentFrame,
	          Properties::NON_VIRTUAL,
	          __unsigned_int__getCurrentFrame,
	          "",
	          "");
	I_Method0(double, getCurrentTime,
	          Properties::NON_VIRTUAL,
	          __double__getCurrentTime,
	          "",
	          "");
	I_Method0(void, play,
	          Properties::NON_VIRTUAL,
	          __void__play,
	          "",
	          "");
	I_Method1(void, gotoFrame, IN, unsigned int, frame,
	          Properties::NON_VIRTUAL,
	          __void__gotoFrame__unsigned_int,
	          "",
	          "");
	I_Method0(void, stop,
	          Properties::NON_VIRTUAL,
	          __void__stop,
	          "",
	          "");
	I_Method0(bool, getEvaluating,
	          Properties::NON_VIRTUAL,
	          __bool__getEvaluating,
	          "",
	          "");
	I_Method1(bool, isActive, IN, osgAnimation::Action *, activeAction,
	          Properties::NON_VIRTUAL,
	          __bool__isActive__Action_P1,
	          "",
	          "");
	I_Method1(void, removeAction, IN, osgAnimation::Action *, action,
	          Properties::NON_VIRTUAL,
	          __void__removeAction__Action_P1,
	          "",
	          "");
	I_MethodWithDefaults3(void, addActionAt, IN, unsigned int, frame, , IN, osgAnimation::Action *, action, , IN, int, priority, 0,
	                      Properties::VIRTUAL,
	                      __void__addActionAt__unsigned_int__Action_P1__int,
	                      "",
	                      "");
	I_MethodWithDefaults3(void, addActionAt, IN, double, t, , IN, osgAnimation::Action *, action, , IN, int, priority, 0,
	                      Properties::VIRTUAL,
	                      __void__addActionAt__double__Action_P1__int,
	                      "",
	                      "");
	I_MethodWithDefaults2(void, addActionNow, IN, osgAnimation::Action *, action, , IN, int, priority, 0,
	                      Properties::NON_VIRTUAL,
	                      __void__addActionNow__Action_P1__int,
	                      "",
	                      "");
	I_Method0(void, clearActions,
	          Properties::NON_VIRTUAL,
	          __void__clearActions,
	          "",
	          "");
	I_Method1(void, update, IN, double, simulationTime,
	          Properties::VIRTUAL,
	          __void__update__double,
	          "",
	          "");
	I_Method1(void, setLastFrameEvaluated, IN, unsigned int, frame,
	          Properties::NON_VIRTUAL,
	          __void__setLastFrameEvaluated__unsigned_int,
	          "",
	          "");
	I_Method1(void, setEvaluating, IN, bool, state,
	          Properties::NON_VIRTUAL,
	          __void__setEvaluating__bool,
	          "",
	          "");
	I_Method1(void, traverse, IN, osgAnimation::ActionVisitor &, visitor,
	          Properties::VIRTUAL,
	          __void__traverse__ActionVisitor_R1,
	          "",
	          "");
	I_Method1(void, setStats, IN, osg::Stats *, stats,
	          Properties::NON_VIRTUAL,
	          __void__setStats__osg_Stats_P1,
	          "",
	          "");
	I_Method0(osg::Stats *, getStats,
	          Properties::NON_VIRTUAL,
	          __osg_Stats_P1__getStats,
	          "",
	          "");
	I_Method1(void, collectStats, IN, bool, state,
	          Properties::NON_VIRTUAL,
	          __void__collectStats__bool,
	          "",
	          "");
	I_Method0(osgAnimation::StatsActionVisitor *, getStatsVisitor,
	          Properties::NON_VIRTUAL,
	          __osgAnimation_StatsActionVisitor_P1__getStatsVisitor,
	          "",
	          "");
	I_Method0(const osgAnimation::Timeline::ActionLayers &, getActionLayers,
	          Properties::NON_VIRTUAL,
	          __C5_ActionLayers_R1__getActionLayers,
	          "",
	          "");
	I_Method0(void, processPendingOperation,
	          Properties::NON_VIRTUAL,
	          __void__processPendingOperation,
	          "",
	          "");
	I_Method1(void, setAnimationManager, IN, osgAnimation::AnimationManagerBase *, x,
	          Properties::NON_VIRTUAL,
	          __void__setAnimationManager__AnimationManagerBase_P1,
	          "",
	          "");
	I_ProtectedMethod1(void, internalRemoveAction, IN, osgAnimation::Action *, action,
	                   Properties::NON_VIRTUAL,
	                   Properties::NON_CONST,
	                   __void__internalRemoveAction__Action_P1,
	                   "",
	                   "");
	I_ProtectedMethod2(void, internalAddAction, IN, int, priority, IN, const osgAnimation::FrameAction &, ftl,
	                   Properties::NON_VIRTUAL,
	                   Properties::NON_CONST,
	                   __void__internalAddAction__int__C5_FrameAction_R1,
	                   "",
	                   "");
	I_SimpleProperty(const osgAnimation::Timeline::ActionLayers &, ActionLayers,
	                 __C5_ActionLayers_R1__getActionLayers,
	                 0);
	I_SimpleProperty(osgAnimation::AnimationManagerBase *, AnimationManager,
	                 0,
	                 __void__setAnimationManager__AnimationManagerBase_P1);
	I_SimpleProperty(unsigned int, CurrentFrame,
	                 __unsigned_int__getCurrentFrame,
	                 0);
	I_SimpleProperty(double, CurrentTime,
	                 __double__getCurrentTime,
	                 0);
	I_SimpleProperty(bool, Evaluating,
	                 __bool__getEvaluating,
	                 __void__setEvaluating__bool);
	I_SimpleProperty(unsigned int, LastFrameEvaluated,
	                 0,
	                 __void__setLastFrameEvaluated__unsigned_int);
	I_SimpleProperty(osg::Stats *, Stats,
	                 __osg_Stats_P1__getStats,
	                 __void__setStats__osg_Stats_P1);
	I_SimpleProperty(osgAnimation::StatsActionVisitor *, StatsVisitor,
	                 __osgAnimation_StatsActionVisitor_P1__getStatsVisitor,
	                 0);
	I_SimpleProperty(osgAnimation::Timeline::TimelineStatus, Status,
	                 __TimelineStatus__getStatus,
	                 0);
END_REFLECTOR

STD_MAP_REFLECTOR(std::map< int COMMA  osgAnimation::Timeline::ActionList >)

<|endoftext|>


<commit_before>AliAnalysisTask *AddTaskHFEElecV2()
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskHFEElecV2", "No analysis manager found.");
    return NULL;
  }

  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskHFEElecV2", "This task requires an input event handler");
    return NULL;
  }
  TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
  if (type=="AOD"){
    ::Error("AddTaskHFEElecV2", "The tasks exits because AODs are in input");
    return NULL;
  }
  Bool_t MCthere=kFALSE;
  AliMCEventHandler *mcH = dynamic_cast<AliMCEventHandler*>(mgr->GetMCtruthEventHandler());
  if(!mcH){
    MCthere=kFALSE;
  }else{
    MCthere=kTRUE;
  }

  //Event plane task
  AliEPSelectionTask *eventplaneTask = new AliEPSelectionTask("EventplaneSelection");
  eventplaneTask->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kSemiCentral | AliVEvent::kCentral | AliVEvent::kEMCEGA);

  eventplaneTask->SetTrackType("TPC");
  eventplaneTask->SetUsePtWeight();
  eventplaneTask->SetUsePhiWeight();
  eventplaneTask->SetSaveTrackContribution();

  mgr->AddTask(eventplaneTask);

  TString containerName3 = mgr->GetCommonFileName();
  containerName3 += ":PWGHF_hfeCalEventPlane";

  AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("EPStat",TList::Class(), AliAnalysisManager::kOutputContainer,containerName3.Data());
  mgr->ConnectInput(eventplaneTask, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(eventplaneTask,1,coutput1);

  //analysis task
//   gROOT->LoadMacro("$ALICE_ROOT/PWGHF/hfe/AliAnalysisTaskElecV2.cxx++g");
  gROOT->LoadMacro("$ALICE_ROOT/PWGHF/hfe/macros/configs/PbPb/ConfigHFEElecV2.C");

  AliAnalysisTaskElecV2 *taskMB = ConfigHFEElecV2(MCthere);
  AliAnalysisTaskElecV2 *taskTR = ConfigHFEElecV2(MCthere);

  mgr->AddTask(taskMB);
  mgr->AddTask(taskTR);

  // Central trigger
  taskMB->SelectCollisionCandidates(AliVEvent::kCentral);

  TString containerName = mgr->GetCommonFileName();
  containerName += ":PWGHF_hfeCalCentralV2";

  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("histMB", TList::Class(),AliAnalysisManager::kOutputContainer, containerName.Data());
  mgr->ConnectInput(taskMB, 0, cinput);
  mgr->ConnectOutput(taskMB, 1, coutput1);

  //L1 gamma trigger
  taskTR->SelectCollisionCandidates(AliVEvent::kEMCEGA);

  TString containerName2 = mgr->GetCommonFileName();
  containerName2 += ":PWGHF_hfeCalL1GammaV2";

  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("histTR", TList::Class(),AliAnalysisManager::kOutputContainer, containerName2.Data());
  mgr->ConnectInput(taskTR, 0, cinput);
  mgr->ConnectOutput(taskTR, 1, coutput1);

  if(MCthere){

    AliAnalysisTaskElecV2 *taskMC = ConfigHFEElecV2(MCthere);
    mgr->AddTask(taskMC);

    taskMC->SelectCollisionCandidates(AliVEvent::kMB);

    TString containerName3 = mgr->GetCommonFileName();
    containerName3 += ":PWGHF_hfeCalMCV2";

    AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
    AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("histMC", TList::Class(),AliAnalysisManager::kOutputContainer, containerName3.Data());
    mgr->ConnectInput(taskMC, 0, cinput);
    mgr->ConnectOutput(taskMC, 1, coutput1);
  }

  return NULL;
}
<commit_msg>added another trigger selections<commit_after>AliAnalysisTask *AddTaskHFEElecV2()
{
  AliAnalysisManager *mgr = AliAnalysisManager::GetAnalysisManager();
  if (!mgr) {
    Error("AddTaskHFEElecV2", "No analysis manager found.");
    return NULL;
  }

  if (!mgr->GetInputEventHandler()) {
    ::Error("AddTaskHFEElecV2", "This task requires an input event handler");
    return NULL;
  }
  TString type = mgr->GetInputEventHandler()->GetDataType(); // can be "ESD" or "AOD"
  if (type=="AOD"){
    ::Error("AddTaskHFEElecV2", "The tasks exits because AODs are in input");
    return NULL;
  }
  Bool_t MCthere=kFALSE;
  AliMCEventHandler *mcH = dynamic_cast<AliMCEventHandler*>(mgr->GetMCtruthEventHandler());
  if(!mcH){
    MCthere=kFALSE;
  }else{
    MCthere=kTRUE;
  }

  //Event plane task
  AliEPSelectionTask *eventplaneTask = new AliEPSelectionTask("EventplaneSelection");
  eventplaneTask->SelectCollisionCandidates(AliVEvent::kMB | AliVEvent::kSemiCentral | AliVEvent::kCentral | AliVEvent::kEMCEGA | AliVEvent::kEMCEJE);

  eventplaneTask->SetTrackType("TPC");
  eventplaneTask->SetUsePtWeight();
  eventplaneTask->SetUsePhiWeight();
  eventplaneTask->SetSaveTrackContribution();

  mgr->AddTask(eventplaneTask);

  TString containerName3 = mgr->GetCommonFileName();
  containerName3 += ":PWGHF_hfeCalEventPlane";

  AliAnalysisDataContainer *cinput0 = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("EPStat",TList::Class(), AliAnalysisManager::kOutputContainer,containerName3.Data());
  mgr->ConnectInput(eventplaneTask, 0, mgr->GetCommonInputContainer());
  mgr->ConnectOutput(eventplaneTask,1,coutput1);

  //analysis task
//   gROOT->LoadMacro("$ALICE_ROOT/PWGHF/hfe/AliAnalysisTaskElecV2.cxx++g");
  gROOT->LoadMacro("$ALICE_ROOT/PWGHF/hfe/macros/configs/PbPb/ConfigHFEElecV2.C");

  AliAnalysisTaskElecV2 *taskMB = ConfigHFEElecV2(MCthere);
  AliAnalysisTaskElecV2 *taskTR = ConfigHFEElecV2(MCthere);

  mgr->AddTask(taskMB);
  mgr->AddTask(taskTR);

  // Central trigger
  taskMB->SelectCollisionCandidates(AliVEvent::kSemiCentral);

  TString containerName = mgr->GetCommonFileName();
  containerName += ":PWGHF_hfeCalCentralV2";

  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("histMB", TList::Class(),AliAnalysisManager::kOutputContainer, containerName.Data());
  mgr->ConnectInput(taskMB, 0, cinput);
  mgr->ConnectOutput(taskMB, 1, coutput1);

  //L1 gamma and jet trigger
  taskTR->SelectCollisionCandidates(AliVEvent::kEMCEGA | AliVEvent::kEMCEJE);

  TString containerName2 = mgr->GetCommonFileName();
  containerName2 += ":PWGHF_hfeCalL1GammaV2";

  AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
  AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("histTR", TList::Class(),AliAnalysisManager::kOutputContainer, containerName2.Data());
  mgr->ConnectInput(taskTR, 0, cinput);
  mgr->ConnectOutput(taskTR, 1, coutput1);

  if(MCthere){

    AliAnalysisTaskElecV2 *taskMC = ConfigHFEElecV2(MCthere);
    mgr->AddTask(taskMC);

    taskMC->SelectCollisionCandidates(AliVEvent::kMB);

    TString containerName3 = mgr->GetCommonFileName();
    containerName3 += ":PWGHF_hfeCalMCV2";

    AliAnalysisDataContainer *cinput = mgr->GetCommonInputContainer();
    AliAnalysisDataContainer *coutput1 = mgr->CreateContainer("histMC", TList::Class(),AliAnalysisManager::kOutputContainer, containerName3.Data());
    mgr->ConnectInput(taskMC, 0, cinput);
    mgr->ConnectOutput(taskMC, 1, coutput1);
  }

  return NULL;
}
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "StateMain.h"
#include "StateAutoPlay.h"
#include "StateMainGame.h"
#include "StateZenGame.h"
#include "Gui/Widgets.h"

//////////////////////////////////////////////////////////////////////////
GuiStateMain::GuiStateMain()
{
  AddWidget( boost::make_shared<Gui::Button>(
    Rect( Point(290, 220), Size(200, 50) ),
    boost::make_shared<Font>( "./_data/gm.ttf", 25),
    boost::make_shared<Texture>( "./_data/button_01.png", 2 ),
    BIND_THIS(StartMainGameState),
    "Start Game"
  ));

  AddWidget( boost::make_shared<Gui::Button>(
    Rect( Point(290, 300), Size(200, 50) ),
    boost::make_shared<Font>( "./_data/gm.ttf", 25),
    boost::make_shared<Texture>( "./_data/button_01.png", 2 ),
    BIND_THIS(StartZenGameState),
    "Zen Mode Game"
  ));

  AddWidget( boost::make_shared<Gui::Button>(
    Rect( Point(290, 380), Size(200, 50) ),
    boost::make_shared<Font>( "./_data/gm.ttf", 25),
    boost::make_shared<Texture>( "./_data/button_01.png", 2 ),
    BIND_THIS(StartAutoplayState),
    "Autoplay Test"
    ));
}
//////////////////////////////////////////////////////////////////////////

void GuiStateMain::StartAutoplayState()
{
  GetManager()->SetState( boost::make_shared<GuiStateAutoPlay>() );
}
//////////////////////////////////////////////////////////////////////////

void GuiStateMain::StartMainGameState()
{
  GetManager()->SetState( boost::make_shared<GuiStateMainGame>() );
}
//////////////////////////////////////////////////////////////////////////

void GuiStateMain::StartZenGameState()
{
  GetManager()->SetState( boost::make_shared<GuiStateZenGame>() );
}
<commit_msg>Main Menu improved<commit_after>#include "stdafx.h"
#include "StateMain.h"
#include "StateAutoPlay.h"
#include "StateMainGame.h"
#include "StateZenGame.h"
#include "Gui/Widgets.h"

//////////////////////////////////////////////////////////////////////////
GuiStateMain::GuiStateMain()
{
  AddWidget( boost::make_shared<Gui::Image>(
    Rect( Point(0, 0), Size(755, 600) ),
    boost::make_shared<Texture>( "./_data/backg_main.png" )
    ));

  const Texture::TPtr pBtnTex = boost::make_shared<Texture>( "./_data/button_01.png", 2 );
  const Font::TPtr pBtnFont = boost::make_shared<Font>( "./_data/gm.ttf", 25);

  AddWidget( boost::make_shared<Gui::Label>(
    Point(377, 10),
    boost::make_shared<Font>( "./_data/gm.ttf", 150),
    "The Game",
    Color::make_white(),
    Gui::Label::Center
  ));

  AddWidget( boost::make_shared<Gui::Label>(
    Point(377, 545),
    boost::make_shared<Font>( "./_data/gm.ttf", 50),
    "Dmitry Shesterkin   dfb@yandex.ru",
    Color::make_white(),
    Gui::Label::Center
  ));

  AddWidget( boost::make_shared<Gui::Button>(
    Rect( Point(252, 220), Size(250, 50) ),
    pBtnFont, pBtnTex,
    BIND_THIS(StartMainGameState),
    "Start Game"
  ));

  AddWidget( boost::make_shared<Gui::Button>(
    Rect( Point(252, 300), Size(250, 50) ),
    pBtnFont, pBtnTex,
    BIND_THIS(StartZenGameState),
    "Zen Mode Game"
  ));

  AddWidget( boost::make_shared<Gui::Button>(
    Rect( Point(252, 380), Size(250, 50) ),
    pBtnFont, pBtnTex,
    BIND_THIS(StartAutoplayState),
    "Autoplay Test"
    ));
}
//////////////////////////////////////////////////////////////////////////

void GuiStateMain::StartAutoplayState()
{
  GetManager()->SetState( boost::make_shared<GuiStateAutoPlay>() );
}
//////////////////////////////////////////////////////////////////////////

void GuiStateMain::StartMainGameState()
{
  GetManager()->SetState( boost::make_shared<GuiStateMainGame>() );
}
//////////////////////////////////////////////////////////////////////////

void GuiStateMain::StartZenGameState()
{
  GetManager()->SetState( boost::make_shared<GuiStateZenGame>() );
}
<|endoftext|>


<commit_before>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__VON_MISES_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__VON_MISES_HPP__

#include <stan/agrad/partials_vari.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/math.hpp>
#include <stan/meta/traits.hpp>
#include <stan/prob/constants.hpp>
#include <stan/prob/traits.hpp>
#include <stan/prob/distributions/univariate/continuous/uniform.hpp>

namespace stan {

  namespace prob {

    template<bool propto,
             typename T_y, typename T_loc, typename T_scale>
    typename return_type<T_y,T_loc,T_scale>::type
    von_mises_log(T_y const& y, T_loc const& mu, T_scale const& kappa) {
      static char const* const function = "stan::prob::von_mises_log(%1%)";

      // check if any vectors are zero length
      if (!(stan::length(y)
            && stan::length(mu)
            && stan::length(kappa)))
        return 0.0;

      using stan::is_constant_struct;
      using stan::math::check_finite;
      using stan::math::check_positive;
      using stan::math::check_greater;
      using stan::math::check_nonnegative;
      using stan::math::check_consistent_sizes;
      using stan::math::value_of;

      // Result accumulator.
      double logp = 0.0;

      // Validate arguments.
      if (!check_finite(function, y, "Random variable", &logp))
        return logp;
      if(!check_finite(function, mu, "Location paramter", &logp))
        return logp;
      if(!check_finite(function, kappa, "Scale parameter", &logp))
        return logp;
      if(!check_positive(function, kappa, "Scale parameter", &logp))
        return logp;
      if(!check_consistent_sizes(function, y, mu, kappa, "Random variable",
                                  "Location parameter", "Scale parameter",
                                  &logp))
        return logp;

      // check if no variables are involved and prop-to
      if (!include_summand<propto,T_y,T_loc,T_scale>::value)
        return logp;

      // Determine constants.
      const bool y_const = is_constant_struct<T_y>::value;
      const bool mu_const = is_constant_struct<T_loc>::value;
      const bool kappa_const = is_constant_struct<T_scale>::value;

      // Determine which expensive computations to perform.
      const bool compute_bessel0 = include_summand<propto,T_scale>::value;
      const bool compute_bessel1 = !kappa_const;
      const double TWO_PI = 2.0 * stan::math::pi();

      // Wrap scalars into vector views.
      VectorView<const T_y> y_vec(y);
      VectorView<const T_loc> mu_vec(mu);
      VectorView<const T_scale> kappa_vec(kappa);

      DoubleVectorView<true,is_vector<T_scale>::value> kappa_dbl(length(kappa));
      DoubleVectorView<include_summand<propto,T_scale>::value,is_vector<T_scale>::value> log_bessel0(length(kappa));
      for (size_t i = 0; i < length(kappa); i++) {
        kappa_dbl[i] = value_of(kappa_vec[i]);
        if (include_summand<propto,T_scale>::value)
          log_bessel0[i] = log(boost::math::cyl_bessel_i(0, value_of(kappa_vec[i])));
      }
      agrad::OperandsAndPartials<T_y, T_loc, T_scale> oap(y, mu, kappa);

      size_t N = max_size(y, mu, kappa);

      for (size_t n = 0; n < N; n++) {
        // Extract argument values.
        const double y_ = value_of(y_vec[n]);
        const double y_dbl =  y_ - std::floor(y_ / TWO_PI) * TWO_PI;
        const double mu_dbl = value_of(mu_vec[n]);

        // Reusable values.
        double bessel0 = 0;
        if (compute_bessel0)
          bessel0 = boost::math::cyl_bessel_i(0, kappa_dbl[n]);
        double bessel1 = 0;
        if (compute_bessel1)
          bessel1 = boost::math::cyl_bessel_i(-1, kappa_dbl[n]);
        const double kappa_sin = kappa_dbl[n] * std::sin(mu_dbl - y_dbl);
        const double kappa_cos = kappa_dbl[n] * std::cos(mu_dbl - y_dbl);

        // Log probability.
        if (include_summand<propto>::value)
          logp -= LOG_TWO_PI;
        if (include_summand<propto,T_scale>::value)
          logp -= log_bessel0[n];
        if (include_summand<propto,T_y,T_loc,T_scale>::value)
          logp += kappa_cos;

        // Gradient.
        if (!y_const)
          oap.d_x1[n] += kappa_sin;
        if (!mu_const)
          oap.d_x2[n] -= kappa_sin;
        if (!kappa_const)
          oap.d_x3[n] += kappa_cos / kappa_dbl[n] - bessel1 / bessel0;
      }

      return oap.to_var(logp);
    }

    template<typename T_y, typename T_loc, typename T_scale>
    inline typename return_type<T_y,T_loc,T_scale>::type
    von_mises_log(T_y const& y, T_loc const& mu, T_scale const& kappa) {
      return von_mises_log<false>(y, mu, kappa);
    }

    template <class RNG>
    inline double
    von_mises_rng(const double mu,
                  const double kappa,
                  RNG& rng) {
      using boost::variate_generator;
      using stan::prob::uniform_rng;

      static const char* function = "stan::prob::von_mises_rng(%1%)";

      stan::math::check_finite(function,kappa,"inverse of variance");
      stan::math::check_positive(function,kappa,"inverse of variance");

      double r = 1 + pow((1 + 4 * kappa * kappa), 0.5);
      double rho = 0.5 * (r - pow(2 * r, 0.5)) / kappa;
      double s = 0.5 * (1 + rho * rho) / rho;

      bool done = 0;
      double W;
      while (!done) {
        double Z = std::cos(stan::math::pi() * uniform_rng(0.0, 1.0, rng));
        W = (1 + s * Z) / (s + Z);
        double Y = kappa * (s - W);
        double U2 = uniform_rng(0.0, 1.0, rng);
        done = Y * (2 - Y) - U2 > 0;

        if(!done)
          done = log(Y / U2) + 1 - Y >= 0;
      }

      double U3 = uniform_rng(0.0, 1.0, rng) - 0.5;

      double sign = ((U3 >= 0) - (U3 <= 0));

      return std::fmod(mu + sign * std::acos(W) + 2 * stan::math::pi(), 2 * stan::math::pi());
    }

  }
}
#endif
<commit_msg>Marcus's suggestion & use TWO_PI<commit_after>#ifndef __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__VON_MISES_HPP__
#define __STAN__PROB__DISTRIBUTIONS__UNIVARIATE__CONTINUOUS__VON_MISES_HPP__

#include <stan/agrad/partials_vari.hpp>
#include <stan/math/error_handling.hpp>
#include <stan/math.hpp>
#include <stan/meta/traits.hpp>
#include <stan/prob/constants.hpp>
#include <stan/prob/traits.hpp>
#include <stan/prob/distributions/univariate/continuous/uniform.hpp>

namespace stan {

  namespace prob {

    template<bool propto,
             typename T_y, typename T_loc, typename T_scale>
    typename return_type<T_y,T_loc,T_scale>::type
    von_mises_log(T_y const& y, T_loc const& mu, T_scale const& kappa) {
      static char const* const function = "stan::prob::von_mises_log(%1%)";

      // check if any vectors are zero length
      if (!(stan::length(y)
            && stan::length(mu)
            && stan::length(kappa)))
        return 0.0;

      using stan::is_constant_struct;
      using stan::math::check_finite;
      using stan::math::check_positive;
      using stan::math::check_greater;
      using stan::math::check_nonnegative;
      using stan::math::check_consistent_sizes;
      using stan::math::value_of;

      // Result accumulator.
      double logp = 0.0;

      // Validate arguments.
      if (!check_finite(function, y, "Random variable", &logp))
        return logp;
      if(!check_finite(function, mu, "Location paramter", &logp))
        return logp;
      if(!check_finite(function, kappa, "Scale parameter", &logp))
        return logp;
      if(!check_positive(function, kappa, "Scale parameter", &logp))
        return logp;
      if(!check_consistent_sizes(function, y, mu, kappa, "Random variable",
                                  "Location parameter", "Scale parameter",
                                  &logp))
        return logp;

      // check if no variables are involved and prop-to
      if (!include_summand<propto,T_y,T_loc,T_scale>::value)
        return logp;

      // Determine constants.
      const bool y_const = is_constant_struct<T_y>::value;
      const bool mu_const = is_constant_struct<T_loc>::value;
      const bool kappa_const = is_constant_struct<T_scale>::value;

      // Determine which expensive computations to perform.
      const bool compute_bessel0 = include_summand<propto,T_scale>::value;
      const bool compute_bessel1 = !kappa_const;
      const double TWO_PI = 2.0 * stan::math::pi();

      // Wrap scalars into vector views.
      VectorView<const T_y> y_vec(y);
      VectorView<const T_loc> mu_vec(mu);
      VectorView<const T_scale> kappa_vec(kappa);

      DoubleVectorView<true,is_vector<T_scale>::value> kappa_dbl(length(kappa));
      DoubleVectorView<include_summand<propto,T_scale>::value,is_vector<T_scale>::value> log_bessel0(length(kappa));
      for (size_t i = 0; i < length(kappa); i++) {
        kappa_dbl[i] = value_of(kappa_vec[i]);
        if (include_summand<propto,T_scale>::value)
          log_bessel0[i] = log(boost::math::cyl_bessel_i(0, value_of(kappa_vec[i])));
      }
      agrad::OperandsAndPartials<T_y, T_loc, T_scale> oap(y, mu, kappa);

      size_t N = max_size(y, mu, kappa);

      for (size_t n = 0; n < N; n++) {
        // Extract argument values.
        const double y_ = value_of(y_vec[n]);
        const double y_dbl =  y_ - std::floor(y_ / TWO_PI) * TWO_PI;
        const double mu_dbl = value_of(mu_vec[n]);

        // Reusable values.
        double bessel0 = 0;
        if (compute_bessel0)
          bessel0 = boost::math::cyl_bessel_i(0, kappa_dbl[n]);
        double bessel1 = 0;
        if (compute_bessel1)
          bessel1 = boost::math::cyl_bessel_i(-1, kappa_dbl[n]);
        const double kappa_sin = kappa_dbl[n] * std::sin(mu_dbl - y_dbl);
        const double kappa_cos = kappa_dbl[n] * std::cos(mu_dbl - y_dbl);

        // Log probability.
        if (include_summand<propto>::value)
          logp -= LOG_TWO_PI;
        if (include_summand<propto,T_scale>::value)
          logp -= log_bessel0[n];
        if (include_summand<propto,T_y,T_loc,T_scale>::value)
          logp += kappa_cos;

        // Gradient.
        if (!y_const)
          oap.d_x1[n] += kappa_sin;
        if (!mu_const)
          oap.d_x2[n] -= kappa_sin;
        if (!kappa_const)
          oap.d_x3[n] += kappa_cos / kappa_dbl[n] - bessel1 / bessel0;
      }

      return oap.to_var(logp);
    }

    template<typename T_y, typename T_loc, typename T_scale>
    inline typename return_type<T_y,T_loc,T_scale>::type
    von_mises_log(T_y const& y, T_loc const& mu, T_scale const& kappa) {
      return von_mises_log<false>(y, mu, kappa);
    }

    template <class RNG>
    inline double
    von_mises_rng(const double mu,
                  const double kappa,
                  RNG& rng) {
      using boost::variate_generator;
      using stan::prob::uniform_rng;

      static const char* function = "stan::prob::von_mises_rng(%1%)";

      stan::math::check_finite(function,kappa,"inverse of variance");
      stan::math::check_positive(function,kappa,"inverse of variance");

      double r = 1 + pow((1 + 4 * kappa * kappa), 0.5);
      double rho = 0.5 * (r - pow(2 * r, 0.5)) / kappa;
      double s = 0.5 * (1 + rho * rho) / rho;

      bool done = 0;
      double W;
      while (!done) {
        double Z = std::cos(stan::math::pi() * uniform_rng(0.0, 1.0, rng));
        W = (1 + s * Z) / (s + Z);
        double Y = kappa * (s - W);
        double U2 = uniform_rng(0.0, 1.0, rng);
        done = Y * (2 - Y) - U2 > 0;

        if(!done)
          done = log(Y / U2) + 1 - Y >= 0;
      }

      double U3 = uniform_rng(0.0, 1.0, rng) - 0.5;

      double sign = ((U3 >= 0) - (U3 <= 0));

      return std::fmod(std::fmod(mu + sign * std::acos(W), TWO_PI) + TWO_PI, TWO_PI);
    }

  }
}
#endif
<|endoftext|>


<commit_before>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-

#include "RateThreadOutput.hpp"

void rd::RateThreadOutput::init(yarp::os::ResourceFinder &rf)
{
    rateMs = DEFAULT_RATE_MS;

    printf("--------------------------------------------------------------\n");
    if (rf.check("help")) {
        printf("RateThreadOutput options:\n");
        printf("\t--help (this help)\t--from [file.ini]\t--context [path]\n");
        printf("\t--rateMs (default: \"%d\")\n",rateMs);
    }
    if (rf.check("rateMs")) rateMs = rf.find("rateMs").asInt();

    printf("RateThreadOutput using rateMs: %d.\n", rateMs);

    printf("--------------------------------------------------------------\n");
    if(rf.check("help")) {
        ::exit(1);
    }

    // http://gameprogrammingtutorials.blogspot.com.es/2010/01/sdl-tutorial-series-part-3-your-first.html
    if (SDL_Init(SDL_INIT_VIDEO) != 0)
    {
        RD_ERROR("SDL_Init(): %s\n",SDL_GetError());
        ::exit(1);
    }

    //display = SDL_SetVideoMode(640, 480, 24, SDL_HWSURFACE | SDL_DOUBLEBUF);SDL_SWSURFACE
    display = SDL_SetVideoMode(640, 480, 8, SDL_SWSURFACE);
    //display = SDL_SetVideoMode(128, 128, 8, SDL_HWSURFACE | SDL_DOUBLEBUF);
    if (display == NULL)
    {
        RD_ERROR("SDL_SetVideoMode(): %s\n",SDL_GetError());
        ::exit(1);
    }

    // Set the title bar
    SDL_WM_SetCaption("Robot Devastation", "Robot Devastation");

    this->setRate(rateMs);
    this->start();

}

void rd::RateThreadOutput::run()
{
    //printf("[RateThreadOutput] run()\n");

    yarp::sig::ImageOf<yarp::sig::PixelRgb> *inYarpImg = pInImg->read(false);
    if (inYarpImg==NULL) {
        printf("No img yet...\n");
        return;
    };

    int depth=8;  // the depth of the surface in bits
    int channels=3;  //
    int widthstep = 1920; // the length of a row of pixels in bytes

    // http://stackoverflow.com/1questions/393954/how-to-convert-an-opencv-iplimage-to-an-sdl-surface
//    SDL_Surface *surface = SDL_CreateRGBSurfaceFrom((void*)inYarpImg->getIplImage(),
    SDL_Surface *surface = SDL_CreateRGBSurfaceFrom((void*)inYarpImg->getRawImage(),
                inYarpImg->width(),
                inYarpImg->height(),
                depth*channels,
                widthstep,
                0x0000ff, 0x00ff00, 0xff0000, 0
                );

    //http://gameprogrammingtutorials.blogspot.com.es/2010/01/sdl-tutorial-series-part-4-how-to-load.html

    // Apply the image to the display
    if (SDL_BlitSurface(surface, NULL, display, NULL) != 0)
    {
        RD_ERROR("SDL_BlitSurface(): %s\n", SDL_GetError());
        ::exit(1);
    }

    SDL_Flip(display);

    printf("[RateThreadOutput] p:%p, w:%d h:%d, %d.\n",surface,inYarpImg->width(),
                inYarpImg->height(),inYarpImg->getRowSize());

    //SDL_Event evt;
    //SDL_WaitEvent(&evt);

    //int x_pos=0, y_pos=0;
    //SDL_Rect rcDest = { x_pos, y_pos, 0, 0 };
    //SDL_BlitSurface ( image, NULL, surface, &rcDest );

    // {yarp ImageOf Rgb -> openCv Mat Bgr}
    //IplImage *inIplImage = cvCreateImage(cvSize(inYarpImg->width(), inYarpImg->height()),
    //                                     IPL_DEPTH_8U, 3 );
    //cvCvtColor((IplImage*)inYarpImg->getIplImage(), inIplImage, CV_RGB2BGR);
    //Mat inCvMat(inIplImage);

}

void rd::RateThreadOutput::setInImg(yarp::os::BufferedPort<yarp::sig::ImageOf<yarp::sig::PixelRgb> > * pInImg) {
    this->pInImg = pInImg;
}

<commit_msg>fixed color issue on cam output<commit_after>// -*- mode:C++; tab-width:4; c-basic-offset:4; indent-tabs-mode:nil -*-

#include "RateThreadOutput.hpp"

void rd::RateThreadOutput::init(yarp::os::ResourceFinder &rf)
{
    rateMs = DEFAULT_RATE_MS;

    printf("--------------------------------------------------------------\n");
    if (rf.check("help")) {
        printf("RateThreadOutput options:\n");
        printf("\t--help (this help)\t--from [file.ini]\t--context [path]\n");
        printf("\t--rateMs (default: \"%d\")\n",rateMs);
    }
    if (rf.check("rateMs")) rateMs = rf.find("rateMs").asInt();

    printf("RateThreadOutput using rateMs: %d.\n", rateMs);

    printf("--------------------------------------------------------------\n");
    if(rf.check("help")) {
        ::exit(1);
    }

    // http://gameprogrammingtutorials.blogspot.com.es/2010/01/sdl-tutorial-series-part-3-your-first.html
    if (SDL_Init(SDL_INIT_VIDEO) != 0)
    {
        RD_ERROR("SDL_Init(): %s\n",SDL_GetError());
        ::exit(1);
    }

    //display = SDL_SetVideoMode(640, 480, 24, SDL_HWSURFACE | SDL_DOUBLEBUF);SDL_SWSURFACE
    display = SDL_SetVideoMode(640, 480, 32, SDL_SWSURFACE);
    //display = SDL_SetVideoMode(128, 128, 8, SDL_HWSURFACE | SDL_DOUBLEBUF);
    if (display == NULL)
    {
        RD_ERROR("SDL_SetVideoMode(): %s\n",SDL_GetError());
        ::exit(1);
    }

    // Set the title bar
    SDL_WM_SetCaption("Robot Devastation", "Robot Devastation");

    this->setRate(rateMs);
    this->start();

}

void rd::RateThreadOutput::run()
{
    //printf("[RateThreadOutput] run()\n");

    yarp::sig::ImageOf<yarp::sig::PixelRgb> *inYarpImg = pInImg->read(false);
    if (inYarpImg==NULL) {
        printf("No img yet...\n");
        return;
    };

    int depth=8;  // the depth of the surface in bits
    int channels=3;  //
    int widthstep = 1920; // the length of a row of pixels in bytes

    // http://stackoverflow.com/1questions/393954/how-to-convert-an-opencv-iplimage-to-an-sdl-surface
//    SDL_Surface *surface = SDL_CreateRGBSurfaceFrom((void*)inYarpImg->getIplImage(),
    SDL_Surface *surface = SDL_CreateRGBSurfaceFrom((void*)inYarpImg->getRawImage(),
                inYarpImg->width(),
                inYarpImg->height(),
                depth*channels,
                widthstep,
                0x0000ff, 0x00ff00, 0xff0000, 0
                );

    //http://gameprogrammingtutorials.blogspot.com.es/2010/01/sdl-tutorial-series-part-4-how-to-load.html

    // Apply the image to the display
    if (SDL_BlitSurface(surface, NULL, display, NULL) != 0)
    {
        RD_ERROR("SDL_BlitSurface(): %s\n", SDL_GetError());
        ::exit(1);
    }

    SDL_Flip(display);

    printf("[RateThreadOutput] p:%p, w:%d h:%d, %d.\n",surface,inYarpImg->width(),
                inYarpImg->height(),inYarpImg->getRowSize());

    //SDL_Event evt;
    //SDL_WaitEvent(&evt);

    //int x_pos=0, y_pos=0;
    //SDL_Rect rcDest = { x_pos, y_pos, 0, 0 };
    //SDL_BlitSurface ( image, NULL, surface, &rcDest );

    // {yarp ImageOf Rgb -> openCv Mat Bgr}
    //IplImage *inIplImage = cvCreateImage(cvSize(inYarpImg->width(), inYarpImg->height()),
    //                                     IPL_DEPTH_8U, 3 );
    //cvCvtColor((IplImage*)inYarpImg->getIplImage(), inIplImage, CV_RGB2BGR);
    //Mat inCvMat(inIplImage);

}

void rd::RateThreadOutput::setInImg(yarp::os::BufferedPort<yarp::sig::ImageOf<yarp::sig::PixelRgb> > * pInImg) {
    this->pInImg = pInImg;
}

<|endoftext|>