<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/adr32s.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,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 adr32s.C
/// @brief Subroutines for the PHY ADR32S registers
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <lib/phy/adr32s.H>

namespace mss
{

// Definition of the ADR32S DLL Config registers
const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::DLL_CNFG_REG =
{
    MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0,
    MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S1
};

// Definition of the ADR32S output driver registers
const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::OUTPUT_DRIVER_REG =
{
    MCA_DDRPHY_ADR_OUTPUT_DRIVER_FORCE_VALUE0_P0_ADR32S0,
    MCA_DDRPHY_ADR_OUTPUT_DRIVER_FORCE_VALUE0_P0_ADR32S1
};

}
<commit_msg>Add f/w implementation of PHY duty cycle distortion cal<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/lib/phy/adr32s.C $  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,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 adr32s.C
/// @brief Subroutines for the PHY ADR32S registers
///
// *HWP HWP Owner: Brian Silver <bsilver@us.ibm.com>
// *HWP HWP Backup: Andre Marin <aamarin@us.ibm.com>
// *HWP Team: Memory
// *HWP Level: 2
// *HWP Consumed by: FSP:HB

#include <fapi2.H>
#include <lib/phy/adr32s.H>
#include <lib/utils/find.H>

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

namespace mss
{

// Definition of the ADR32S DLL Config registers
const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::DLL_CNFG_REG =
{
    MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S0,
    MCA_DDRPHY_ADR_DLL_CNTL_P0_ADR32S1
};

// Definition of the ADR32S output driver registers
const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::OUTPUT_DRIVER_REG =
{
    MCA_DDRPHY_ADR_OUTPUT_DRIVER_FORCE_VALUE0_P0_ADR32S0,
    MCA_DDRPHY_ADR_OUTPUT_DRIVER_FORCE_VALUE0_P0_ADR32S1
};

// Definition of the ADR32S duty cycle distortion registers
const std::vector<uint64_t> adr32sTraits<fapi2::TARGET_TYPE_MCA>::DUTY_CYCLE_DISTORTION_REG =
{
    MCA_DDRPHY_ADR_DCD_CONTROL_P0_ADR32S0,
    MCA_DDRPHY_ADR_DCD_CONTROL_P0_ADR32S1
};

namespace adr32s
{

///
/// @brief Helper to iterate over ADR32S 'sides' when performing DCD cal
/// @param[in] i_target the MCA to iterate for
/// @param[in] i_reg the register (ADR0 or ADR1's register)
/// @param[in] i_seed the seed value for the adjuster
/// @param[in] i_side bool; true if this is side a, false for side b
/// @param[out] o_value the value of the adjuster when the compare bit changes state
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode dcd_cal_helper( const fapi2::Target<TARGET_TYPE_MCA>& i_target,
                                  const uint64_t i_reg,
                                  const uint64_t i_seed,
                                  const bool i_side,
                                  uint64_t& o_value )
{
    typedef adr32sTraits<TARGET_TYPE_MCA> TT;

    constexpr uint64_t l_dcd_adjust_overflow =  0b1111111;
    constexpr uint64_t l_dcd_adjust_underflow = 0b0000000;

    // If compare out is 0, we tick up ...
    // Signed value which helps us increment or decrement the adjustment
    int64_t l_tick = 1;
    // ... and we expect a transition to 1
    bool l_expected = 1;
    // ... and we don't expect to overflow
    uint64_t l_overrun = l_dcd_adjust_overflow;

    fapi2::buffer<uint64_t> l_read;
    uint64_t l_current_adjust = i_seed;
    size_t l_iter = 0;

    // More or less mirror's Bialas's logic for DD2 so we can kind of try out the algorithm on DD1.

    FAPI_INF("enter dcd_cal_helper %s 0x%016lx seed: 0x%016lx side: %d",
             mss::c_str(i_target), i_reg, i_seed, i_side );

    // Prime the system with the starting values. We don't need to read/modify/write here as we're resetting
    // the world and saving a scom here is likely benificial. Clear the compare out bit as writing it set
    // will cause the PHY to throw a parity error
    l_read.insertFromRight<TT::DCD_CONTROL_DLL_ADJUST, TT::DCD_CONTROL_DLL_ADJUST_LEN>(l_current_adjust);
    l_read.writeBit<TT::DCD_CONTROL_DLL_ITER_A>(i_side);
    l_read.clearBit<TT::DCD_CONTROL_DLL_COMPARE_OUT>();
    FAPI_TRY( mss::putScom(i_target, i_reg, l_read) );

    // Algorithm waits 128ck (~100ns) between steps. However, scom takes so long (and rippling up thru
    // the platforms takes time too) that there's no need to actually delay - plenty of time has elapsed.

    // Read. Note the register is volatile in that l_read which we just wrote isn't what we'll read
    // as the distortion logic will take the seeded adjustment value and give us information on the next
    // read (so don't get cute and remove this getScom.)
    FAPI_TRY( mss::getScom(i_target, i_reg, l_read) );

    // Based on the 'direction' we're going, we have some values to setup. We setup the bit == 0 case
    // when we initialized these variables above.
    if (l_read.getBit<TT::DCD_CONTROL_DLL_COMPARE_OUT>() != 0)
    {
        // If compare out is 1, we tick down ...
        l_tick = -1;

        // ... and we expect a transition to 0
        l_expected = 0;

        // ... and we don't expect to underflow
        l_overrun = l_dcd_adjust_underflow;
    }

    do
    {
        l_iter += 1;
        bool l_current_compare = l_read.getBit<TT::DCD_CONTROL_DLL_COMPARE_OUT>();

        FAPI_INF("dcd_cal_helper: iter %d tick: %d expected: %d overrun: 0x%x out: %d adj: 0x%x",
                 l_iter, l_tick, l_expected, l_overrun, l_current_compare, l_current_adjust);

        if (l_current_compare == l_expected)
        {
            break;
        }

        // If we're here we're not done, so just adjust and try again. Clear the compare out bit, it must
        // always be 0 or the PHY will parity error
        l_read.insertFromRight<TT::DCD_CONTROL_DLL_ADJUST, TT::DCD_CONTROL_DLL_ADJUST_LEN>(l_current_adjust + l_tick);
        l_read.clearBit<TT::DCD_CONTROL_DLL_COMPARE_OUT>();
        FAPI_TRY( mss::putScom(i_target, i_reg, l_read) );

        // Wait 128ck (~100ns) ...

        FAPI_TRY( mss::getScom(i_target, i_reg, l_read) );

        l_read.extractToRight<TT::DCD_CONTROL_DLL_ADJUST, TT::DCD_CONTROL_DLL_ADJUST_LEN>(l_current_adjust);

    }
    while (l_current_adjust != l_overrun);

    FAPI_ASSERT( l_current_adjust != l_overrun,
                 fapi2::MSS_DUTY_CLOCK_DISTORTION_CAL_FAILED()
                 .set_CURRENT_ADJUST(l_current_adjust)
                 .set_SIDE(i_side)
                 .set_REGISTER(i_reg)
                 .set_REGISTER_VALUE(l_read),
                 "Failed ADR DCD for %s 0x%016lx", mss::c_str(i_target), i_reg );

    // If we're here, we were done and there were no errors. So we can return back the current adjust value
    // as the output/result of our operation
    o_value = l_current_adjust;
    FAPI_INF("side: %d final adjust value: 0x%x (0x%x)", i_side, o_value, l_current_adjust);

    return FAPI2_RC_SUCCESS;

fapi_try_exit:
    return fapi2::current_err;
}

///
/// @brief Perform ADR DCD calibration - Nimbus Only
/// @param[in] i_target the MCBIST (controler) to perform calibration on
/// @return FAPI2_RC_SUCCESS iff ok
///
fapi2::ReturnCode duty_cycle_distortion_calibration( const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target )
{
    typedef adr32sTraits<TARGET_TYPE_MCA> TT;

    const auto l_mca = mss::find_targets<TARGET_TYPE_MCA>(i_target);
    fapi2::buffer<uint64_t> l_read;
    uint8_t is_sim = 0;

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

    // Nothing works here in cycle sim ...
    if (is_sim)
    {
        return FAPI2_RC_SUCCESS;
    }

    if (l_mca.size() == 0)
    {
        FAPI_INF("No MCA, skipping duty cycle distortion calibration");
        return FAPI2_RC_SUCCESS;
    }

    // Do a quick check to make sure this chip doesn't have the DCD logic built in (e.g., DD1 Nimbus)
    // TODO RTC:159687 For DD2 all we need to do is kick off the h/w cal and wait. We can check any ADR_DCD
    // register, they all should reflect the inclusion of the DCD logic.

    FAPI_TRY( mss::getScom(l_mca[0], TT::DUTY_CYCLE_DISTORTION_REG[0], l_read) );

    if (l_read.getBit<TT::DCD_CONTROL_DLL_CORRECT_EN>() == 1)
    {
        FAPI_ERR("seeing ADR DCD algorithm is in the logic but we didn't code it?");
        fapi2::Assert(false);
    }

    // We must calibrate each of our ports. Each has 2 ADR units and each unit needs it's A-side and B-side calibrated.
    for (const auto& p : mss::find_targets<TARGET_TYPE_MCA>(i_target))
    {
        uint64_t l_seed = TT::DCD_ADJUST_DEFAULT;

        for (const auto& r : TT::DUTY_CYCLE_DISTORTION_REG)
        {
            uint64_t l_a_side_value = 0;
            uint64_t l_b_side_value = 0;

            FAPI_TRY( dcd_cal_helper(p, r, l_seed, true, l_a_side_value) );

            // We want to seed the other side (and each subsequent port) with the
            // value found in the pervious iteration as that will likely reduce the number
            // of iterations to find the transition. We back up one so that if we're on
            // a transition, we don't 'bounce' from a 1 to a 0. This will give us a good
            // transition if the a-side value is really to be the b-side value too.
            FAPI_TRY( dcd_cal_helper(p, r, l_a_side_value - 1, false, l_b_side_value) );

            // The final value is the average of the a-side and b-side values.
            l_seed = (l_a_side_value + l_b_side_value) / 2;

            FAPI_INF("average for both sides 0x%02x", l_seed);

            // Note this writes all the other values to 0's which is OK for DD1
            FAPI_TRY( mss::putScom(p, r, l_seed) );
        }
    }

fapi_try_exit:
    return fapi2::current_err;
}

} // close namespace adrs32

} // close namespace mss
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_pll_initf.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_mem_pll_initf.C
///
/// @brief Scan MC ring bucket based on ATTR_MSS_FREQ.
//------------------------------------------------------------------------------
// *HWP HW Owner        : Anusha Reddy Rangareddygari <anusrang@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : Sunil Kumar <skumar8j@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 2
// *HWP Consumed by     : HB
//------------------------------------------------------------------------------

//## auto_generated
#include "p9_mem_pll_initf.H"
#include <p9_ring_id.h>

fapi2::ReturnCode p9_mem_pll_initf(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
    FAPI_INF("Entering ...");

    uint8_t l_sync_mode;
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MC_SYNC_MODE, i_target_chip, l_sync_mode),
             "Error from FAPI_ATTR_GET (ATTR_MC_SYNC_MODE)");

    if (l_sync_mode == 0)
    {
        FAPI_DBG("Re-scanning PLL ring to set final frequency");

        for (auto l_mcbist_target : i_target_chip.getChildren<fapi2::TARGET_TYPE_MCBIST>(fapi2::TARGET_STATE_FUNCTIONAL))
        {
            uint64_t l_mss_freq = 0;
            RingID l_ring_id = mc_pll_bndy_bucket_1;

            FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MSS_FREQ, l_mcbist_target, l_mss_freq),
                     "Error from FAPI_ATTR_GET (ATTR_MSS_FREQ)");

            switch (l_mss_freq)
            {
                case fapi2::ENUM_ATTR_MSS_FREQ_MT1866:
                    FAPI_DBG("Scan mc_pll_bndy_bucket_1 ring");
                    l_ring_id = mc_pll_bndy_bucket_1;
                    break;

                case fapi2::ENUM_ATTR_MSS_FREQ_MT2133:
                    FAPI_DBG("Scan mc_pll_bndy_bucket_2 ring");
                    l_ring_id = mc_pll_bndy_bucket_2;
                    break;

                case fapi2::ENUM_ATTR_MSS_FREQ_MT2400:
                    FAPI_DBG("Scan mc_pll_bndy_bucket_3 ring");
                    l_ring_id = mc_pll_bndy_bucket_3;
                    break;

                case fapi2::ENUM_ATTR_MSS_FREQ_MT2666:
                    FAPI_DBG("Scan mc_pll_bndy_bucket_4 ring");
                    l_ring_id = mc_pll_bndy_bucket_4;
                    break;

                default:
                    FAPI_ASSERT(false,
                                fapi2::P9_MEM_PLL_INITF_UNSUPPORTED_FREQ().
                                set_TARGET(l_mcbist_target).
                                set_MSS_FREQ(l_mss_freq),
                                "Unsupported MSS_FREQ attribute value!");
            }

            FAPI_TRY(fapi2::putRing(l_mcbist_target, l_ring_id, fapi2::RING_MODE_SET_PULSE_NSL),
                     "Error from putRing (mc_pll_bndy, ringID: %d)", l_ring_id);
        }
    }
    else
    {
        FAPI_DBG("Skipping PLL re-scan");
    }

fapi_try_exit:
    FAPI_INF("Exiting ...");
    return fapi2::current_err;
}
<commit_msg>Create dmi.pll.scan.initfile<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_mem_pll_initf.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_mem_pll_initf.C
///
/// @brief Scan MC ring bucket based on ATTR_MSS_FREQ.
//------------------------------------------------------------------------------
// *HWP HW Owner        : Anusha Reddy Rangareddygari <anusrang@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : Sunil Kumar <skumar8j@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 2
// *HWP Consumed by     : HB
//------------------------------------------------------------------------------

//## auto_generated
#include "p9_mem_pll_initf.H"
#include <p9_ring_id.h>

fapi2::ReturnCode p9_mem_pll_initf(const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip)
{
    FAPI_INF("Entering ...");

    uint8_t l_sync_mode;
    uint8_t l_use_dmi_buckets = 0;
    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MC_SYNC_MODE, i_target_chip, l_sync_mode),
             "Error from FAPI_ATTR_GET (ATTR_MC_SYNC_MODE)");

    FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_EC_FEATURE_DMI_MC_PLL_SCAN_BUCKETS, i_target_chip, l_use_dmi_buckets),
             "Error from FAPI_ATTR_GET (ATTR_CHIP_EC_FEATURE_DMI_MC_PLL_SCAN_BUCKETS)");

    if (l_sync_mode == 0 && l_use_dmi_buckets == 0)
    {
        FAPI_DBG("Re-scanning PLL ring to set final frequency");

        for (auto l_mcbist_target : i_target_chip.getChildren<fapi2::TARGET_TYPE_MCBIST>(fapi2::TARGET_STATE_FUNCTIONAL))
        {
            uint64_t l_mss_freq = 0;
            RingID l_ring_id = mc_pll_bndy_bucket_1;

            FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_MSS_FREQ, l_mcbist_target, l_mss_freq),
                     "Error from FAPI_ATTR_GET (ATTR_MSS_FREQ)");

            switch (l_mss_freq)
            {
                case fapi2::ENUM_ATTR_MSS_FREQ_MT1866:
                    FAPI_DBG("Scan mc_pll_bndy_bucket_1 ring");
                    l_ring_id = mc_pll_bndy_bucket_1;
                    break;

                case fapi2::ENUM_ATTR_MSS_FREQ_MT2133:
                    FAPI_DBG("Scan mc_pll_bndy_bucket_2 ring");
                    l_ring_id = mc_pll_bndy_bucket_2;
                    break;

                case fapi2::ENUM_ATTR_MSS_FREQ_MT2400:
                    FAPI_DBG("Scan mc_pll_bndy_bucket_3 ring");
                    l_ring_id = mc_pll_bndy_bucket_3;
                    break;

                case fapi2::ENUM_ATTR_MSS_FREQ_MT2666:
                    FAPI_DBG("Scan mc_pll_bndy_bucket_4 ring");
                    l_ring_id = mc_pll_bndy_bucket_4;
                    break;

                default:
                    FAPI_ASSERT(false,
                                fapi2::P9_MEM_PLL_INITF_UNSUPPORTED_FREQ().
                                set_TARGET(l_mcbist_target).
                                set_MSS_FREQ(l_mss_freq),
                                "Unsupported MSS_FREQ attribute value!");
            }

            FAPI_TRY(fapi2::putRing(l_mcbist_target, l_ring_id, fapi2::RING_MODE_SET_PULSE_NSL),
                     "Error from putRing (mc_pll_bndy, ringID: %d)", l_ring_id);
        }
    }
    else
    {
        FAPI_DBG("Skipping PLL re-scan");
    }

fapi_try_exit:
    FAPI_INF("Exiting ...");
    return fapi2::current_err;
}
<|endoftext|>


<commit_before><commit_msg>Build fix: VC warning<commit_after><|endoftext|>


<commit_before><commit_msg>coverity#735762 Unchecked dynamic_cast<commit_after><|endoftext|>


<commit_before>/*
 * StepFrameConverter.hpp
 *
 *  Created on: Nov 11, 2016
 *      Author: Péter Fankhauser
 *   Institute: ETH Zurich, Robotic Systems Lab
 */

#pragma once

#include <free_gait_core/free_gait_core.hpp>

// ROS
#include <ros/ros.h>
#include <tf2_ros/buffer.h>

// STD
#include <memory>
#include <string>

namespace free_gait {

class StepFrameConverter
{
 public:
  StepFrameConverter(tf2_ros::Buffer& tfBuffer);
  virtual ~StepFrameConverter();

  bool adaptCoordinates(StepQueue& stepQueue, const std::string& sourceFrameId,
                        const std::string& targetFrameId,
                        const Transform& transformInSourceFrame = Transform(),
                        const ros::Time& time = ros::Time(0));

  bool adaptCoordinates(Step& step, const std::string& sourceFrameId,
                        const std::string& targetFrameId,
                        const Transform& transformInSourceFrame = Transform(),
                        const ros::Time& time = ros::Time(0));

  bool adaptCoordinates(Footstep& footstep, const std::string& sourceFrameId,
                        const std::string& targetFrameId,
                        const Transform& transformInSourceFrame = Transform(),
                        const ros::Time& time = ros::Time(0));

  bool adaptCoordinates(EndEffectorTrajectory& endEffectorTrajectory, const std::string& sourceFrameId,
                        const std::string& targetFrameId,
                        const Transform& transformInSourceFrame = Transform(),
                        const ros::Time& time = ros::Time(0));

  bool adaptCoordinates(BaseTrajectory& baseTrajectory, const std::string& sourceFrameId,
                        const std::string& targetFrameId,
                        const Transform& transformInSourceFrame,
                        const ros::Time& time);

 private:

  bool getTransform(const std::string& sourceFrameId, const std::string& targetFrameId,
                    const Transform& transformInSourceFrame, const ros::Time& time,
                    Transform& transform);

  /// TF buffer used to read the transformations.
  /// Note: Needs to be updated from outside with
  /// a TF Listener!
  tf2_ros::Buffer& tfBuffer_;

  /// Cached transform for faster conversion.
  std::string cachedTargetFrameId_, cachedSourceFrameId_;
  ros::Time cachedTime_;
  Transform cachedTransformInSourceFrame_;
  Transform cachedTransform_;
};

} /* namespace free_gait */
<commit_msg>Moved method from private to public.<commit_after>/*
 * StepFrameConverter.hpp
 *
 *  Created on: Nov 11, 2016
 *      Author: Péter Fankhauser
 *   Institute: ETH Zurich, Robotic Systems Lab
 */

#pragma once

#include <free_gait_core/free_gait_core.hpp>

// ROS
#include <ros/ros.h>
#include <tf2_ros/buffer.h>

// STD
#include <memory>
#include <string>

namespace free_gait {

class StepFrameConverter
{
 public:
  StepFrameConverter(tf2_ros::Buffer& tfBuffer);
  virtual ~StepFrameConverter();

  bool adaptCoordinates(StepQueue& stepQueue, const std::string& sourceFrameId,
                        const std::string& targetFrameId,
                        const Transform& transformInSourceFrame = Transform(),
                        const ros::Time& time = ros::Time(0));

  bool adaptCoordinates(Step& step, const std::string& sourceFrameId,
                        const std::string& targetFrameId,
                        const Transform& transformInSourceFrame = Transform(),
                        const ros::Time& time = ros::Time(0));

  bool adaptCoordinates(Footstep& footstep, const std::string& sourceFrameId,
                        const std::string& targetFrameId,
                        const Transform& transformInSourceFrame = Transform(),
                        const ros::Time& time = ros::Time(0));

  bool adaptCoordinates(EndEffectorTrajectory& endEffectorTrajectory, const std::string& sourceFrameId,
                        const std::string& targetFrameId,
                        const Transform& transformInSourceFrame = Transform(),
                        const ros::Time& time = ros::Time(0));

  bool adaptCoordinates(BaseTrajectory& baseTrajectory, const std::string& sourceFrameId,
                        const std::string& targetFrameId,
                        const Transform& transformInSourceFrame,
                        const ros::Time& time);

  bool getTransform(const std::string& sourceFrameId, const std::string& targetFrameId,
                    const Transform& transformInSourceFrame, const ros::Time& time,
                    Transform& transform);

 private:

  /// TF buffer used to read the transformations.
  /// Note: Needs to be updated from outside with
  /// a TF Listener!
  tf2_ros::Buffer& tfBuffer_;

  /// Cached transform for faster conversion.
  std::string cachedTargetFrameId_, cachedSourceFrameId_;
  ros::Time cachedTime_;
  Transform cachedTransformInSourceFrame_;
  Transform cachedTransform_;
};

} /* namespace free_gait */
<|endoftext|>


<commit_before>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrConvolutionEffect.h"
#include "gl/GrGLProgramStage.h"
#include "gl/GrGLSL.h"
#include "gl/GrGLTexture.h"
#include "GrProgramStageFactory.h"

class GrGLConvolutionEffect : public GrGLProgramStage {
public:
    GrGLConvolutionEffect(const GrProgramStageFactory& factory,
                          const GrCustomStage& stage);

    virtual void setupVariables(GrGLShaderBuilder* state,
                                int stage) SK_OVERRIDE;
    virtual void emitVS(GrGLShaderBuilder* state,
                        const char* vertexCoords) SK_OVERRIDE;
    virtual void emitFS(GrGLShaderBuilder* state,
                        const char* outputColor,
                        const char* inputColor,
                        const char* samplerName) SK_OVERRIDE;

    virtual void initUniforms(const GrGLInterface*, int programID) SK_OVERRIDE;

    virtual void setData(const GrGLInterface*,
                         const GrGLTexture&,
                         const GrCustomStage&,
                         int stageNum) SK_OVERRIDE;

    static inline StageKey GenKey(const GrCustomStage&);

private:
    int width() const { return Gr1DKernelEffect::WidthFromRadius(fRadius); }

    int                   fRadius;
    const GrGLShaderVar*  fKernelVar;
    GrGLint               fKernelLocation;
    const GrGLShaderVar*  fImageIncrementVar;
    GrGLint               fImageIncrementLocation;

    typedef GrGLProgramStage INHERITED;
};

GrGLConvolutionEffect::GrGLConvolutionEffect(const GrProgramStageFactory& factory,
                                             const GrCustomStage& stage)
    : GrGLProgramStage(factory)
    , fKernelVar(NULL)
    , fKernelLocation(0)
    , fImageIncrementVar(NULL)
    , fImageIncrementLocation(0) {
    const GrConvolutionEffect& c =
        static_cast<const GrConvolutionEffect&>(stage);
    fRadius = c.radius();
}

void GrGLConvolutionEffect::setupVariables(GrGLShaderBuilder* state,
                                           int stage) {
    fImageIncrementVar = &state->addUniform(
        GrGLShaderBuilder::kBoth_VariableLifetime,
        kVec2f_GrSLType, "uImageIncrement", stage);
    fKernelVar = &state->addUniform(
        GrGLShaderBuilder::kFragment_VariableLifetime,
        kFloat_GrSLType, "uKernel", stage, this->width());

    fImageIncrementLocation = kUseUniform;
    fKernelLocation = kUseUniform;
}

void GrGLConvolutionEffect::emitVS(GrGLShaderBuilder* state,
                                   const char* vertexCoords) {
    GrStringBuilder* code = &state->fVSCode;
    code->appendf("\t\t%s -= vec2(%d, %d) * %s;\n",
                  vertexCoords, fRadius, fRadius,
                  fImageIncrementVar->getName().c_str());
}

void GrGLConvolutionEffect::emitFS(GrGLShaderBuilder* state,
                                   const char* outputColor,
                                   const char* inputColor,
                                   const char* samplerName) {
    GrStringBuilder* code = &state->fFSCode;
 // const char* texFunc = "texture2D";
 // bool complexCoord = false;

    state->fFSCode.appendf("\t\tvec4 sum = vec4(0, 0, 0, 0);\n");

    code->appendf("\t\tvec2 coord = %s;\n", state->fSampleCoords.c_str());
    code->appendf("\t\tfor (int i = 0; i < %d; i++) {\n", this->width());

    // Creates the string "kernel[i]" with workarounds for
    // possible driver bugs
    GrStringBuilder kernelIndex;
    fKernelVar->appendArrayAccess("i", &kernelIndex);
    state->fFSCode.appendf("\t\t\tsum += ");
    state->emitTextureLookup(samplerName, "coord");
    state->fFSCode.appendf(" * %s;\n", kernelIndex.c_str());

    code->appendf("\t\t\tcoord += %s;\n",
                  fImageIncrementVar->getName().c_str());
    code->appendf("\t\t}\n");

    state->fFSCode.appendf("\t\t%s = sum%s;\n",
                           outputColor,
                           state->fModulate.c_str());
}

void GrGLConvolutionEffect::initUniforms(const GrGLInterface* gl,
                                         int programID) {
    GR_GL_CALL_RET(gl, fImageIncrementLocation,
        GetUniformLocation(programID,
            fImageIncrementVar->getName().c_str()));
    GR_GL_CALL_RET(gl, fKernelLocation,
        GetUniformLocation(programID, fKernelVar->getName().c_str()));
}

void GrGLConvolutionEffect::setData(const GrGLInterface* gl,
                                    const GrGLTexture& texture,
                                    const GrCustomStage& data,
                                    int stageNum) {
    const GrConvolutionEffect& conv =
        static_cast<const GrConvolutionEffect&>(data);
    // the code we generated was for a specific kernel radius
    GrAssert(conv.radius() == fRadius);
    float imageIncrement[2] = { 0 };
    switch (conv.direction()) {
        case Gr1DKernelEffect::kX_Direction:
            imageIncrement[0] = 1.0f / texture.width();
            break;
        case Gr1DKernelEffect::kY_Direction:
            imageIncrement[1] = 1.0f / texture.height();
            break;
        default:
            GrCrash("Unknown filter direction.");
    }
    GR_GL_CALL(gl, Uniform2fv(fImageIncrementLocation, 1, imageIncrement));

    GR_GL_CALL(gl, Uniform1fv(fKernelLocation, this->width(), conv.kernel()));
}

GrGLProgramStage::StageKey GrGLConvolutionEffect::GenKey(
                                                    const GrCustomStage& s) {
    return static_cast<const GrConvolutionEffect&>(s).radius();
}

///////////////////////////////////////////////////////////////////////////////

GrConvolutionEffect::GrConvolutionEffect(Direction direction,
                                         int radius,
                                         const float* kernel)
    : Gr1DKernelEffect(direction, radius) {
    GrAssert(radius <= kMaxKernelRadius);
    int width = this->width();
    if (NULL != kernel) {
        for (int i = 0; i < width; i++) {
            fKernel[i] = kernel[i];
        }
    }
}

GrConvolutionEffect::~GrConvolutionEffect() {
}

const GrProgramStageFactory& GrConvolutionEffect::getFactory() const {
    return GrTProgramStageFactory<GrConvolutionEffect>::getInstance();
}

bool GrConvolutionEffect::isEqual(const GrCustomStage& sBase) const {
     const GrConvolutionEffect& s =
        static_cast<const GrConvolutionEffect&>(sBase);
    return (this->radius() == s.radius() &&
             this->direction() == s.direction() &&
             0 == memcmp(fKernel, s.fKernel, this->width() * sizeof(float)));
}

void GrConvolutionEffect::setGaussianKernel(float sigma) {
    int width = this->width();
    float sum = 0.0f;
    float denom = 1.0f / (2.0f * sigma * sigma);
    for (int i = 0; i < width; ++i) {
        float x = static_cast<float>(i - this->radius());
        // Note that the constant term (1/(sqrt(2*pi*sigma^2)) of the Gaussian
        // is dropped here, since we renormalize the kernel below.
        fKernel[i] = sk_float_exp(- x * x * denom);
        sum += fKernel[i];
    }
    // Normalize the kernel
    float scale = 1.0f / sum;
    for (int i = 0; i < width; ++i) {
        fKernel[i] *= scale;
    }
}
<commit_msg>Manually unroll loop in convolution (blur) - most GL drivers do, but some don't, and this leads to 20-30% benchmark speedup.<commit_after>/*
 * Copyright 2012 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */

#include "GrConvolutionEffect.h"
#include "gl/GrGLProgramStage.h"
#include "gl/GrGLSL.h"
#include "gl/GrGLTexture.h"
#include "GrProgramStageFactory.h"

class GrGLConvolutionEffect : public GrGLProgramStage {
public:
    GrGLConvolutionEffect(const GrProgramStageFactory& factory,
                          const GrCustomStage& stage);

    virtual void setupVariables(GrGLShaderBuilder* state,
                                int stage) SK_OVERRIDE;
    virtual void emitVS(GrGLShaderBuilder* state,
                        const char* vertexCoords) SK_OVERRIDE;
    virtual void emitFS(GrGLShaderBuilder* state,
                        const char* outputColor,
                        const char* inputColor,
                        const char* samplerName) SK_OVERRIDE;

    virtual void initUniforms(const GrGLInterface*, int programID) SK_OVERRIDE;

    virtual void setData(const GrGLInterface*,
                         const GrGLTexture&,
                         const GrCustomStage&,
                         int stageNum) SK_OVERRIDE;

    static inline StageKey GenKey(const GrCustomStage&);

private:
    int width() const { return Gr1DKernelEffect::WidthFromRadius(fRadius); }

    int                   fRadius;
    const GrGLShaderVar*  fKernelVar;
    GrGLint               fKernelLocation;
    const GrGLShaderVar*  fImageIncrementVar;
    GrGLint               fImageIncrementLocation;

    typedef GrGLProgramStage INHERITED;
};

GrGLConvolutionEffect::GrGLConvolutionEffect(const GrProgramStageFactory& factory,
                                             const GrCustomStage& stage)
    : GrGLProgramStage(factory)
    , fKernelVar(NULL)
    , fKernelLocation(0)
    , fImageIncrementVar(NULL)
    , fImageIncrementLocation(0) {
    const GrConvolutionEffect& c =
        static_cast<const GrConvolutionEffect&>(stage);
    fRadius = c.radius();
}

void GrGLConvolutionEffect::setupVariables(GrGLShaderBuilder* state,
                                           int stage) {
    fImageIncrementVar = &state->addUniform(
        GrGLShaderBuilder::kBoth_VariableLifetime,
        kVec2f_GrSLType, "uImageIncrement", stage);
    fKernelVar = &state->addUniform(
        GrGLShaderBuilder::kFragment_VariableLifetime,
        kFloat_GrSLType, "uKernel", stage, this->width());

    fImageIncrementLocation = kUseUniform;
    fKernelLocation = kUseUniform;
}

void GrGLConvolutionEffect::emitVS(GrGLShaderBuilder* state,
                                   const char* vertexCoords) {
    GrStringBuilder* code = &state->fVSCode;
    code->appendf("\t\t%s -= vec2(%d, %d) * %s;\n",
                  vertexCoords, fRadius, fRadius,
                  fImageIncrementVar->getName().c_str());
}

void GrGLConvolutionEffect::emitFS(GrGLShaderBuilder* state,
                                   const char* outputColor,
                                   const char* inputColor,
                                   const char* samplerName) {
    GrStringBuilder* code = &state->fFSCode;

    code->appendf("\t\tvec4 sum = vec4(0, 0, 0, 0);\n");

    code->appendf("\t\tvec2 coord = %s;\n", state->fSampleCoords.c_str());

    // Manually unroll loop because some drivers don't; yields 20-30% speedup.
    for (int i = 0; i < this->width(); i++) {
        GrStringBuilder index;
        GrStringBuilder kernelIndex;
        index.appendS32(i);
        fKernelVar->appendArrayAccess(index.c_str(), &kernelIndex);
        code->appendf("\t\tsum += ");
        state->emitTextureLookup(samplerName, "coord");
        code->appendf(" * %s;\n", kernelIndex.c_str());
        code->appendf("\t\tcoord += %s;\n",
                      fImageIncrementVar->getName().c_str());
    }

    code->appendf("\t\t%s = sum%s;\n", outputColor, state->fModulate.c_str());
}

void GrGLConvolutionEffect::initUniforms(const GrGLInterface* gl,
                                         int programID) {
    GR_GL_CALL_RET(gl, fImageIncrementLocation,
        GetUniformLocation(programID,
            fImageIncrementVar->getName().c_str()));
    GR_GL_CALL_RET(gl, fKernelLocation,
        GetUniformLocation(programID, fKernelVar->getName().c_str()));
}

void GrGLConvolutionEffect::setData(const GrGLInterface* gl,
                                    const GrGLTexture& texture,
                                    const GrCustomStage& data,
                                    int stageNum) {
    const GrConvolutionEffect& conv =
        static_cast<const GrConvolutionEffect&>(data);
    // the code we generated was for a specific kernel radius
    GrAssert(conv.radius() == fRadius);
    float imageIncrement[2] = { 0 };
    switch (conv.direction()) {
        case Gr1DKernelEffect::kX_Direction:
            imageIncrement[0] = 1.0f / texture.width();
            break;
        case Gr1DKernelEffect::kY_Direction:
            imageIncrement[1] = 1.0f / texture.height();
            break;
        default:
            GrCrash("Unknown filter direction.");
    }
    GR_GL_CALL(gl, Uniform2fv(fImageIncrementLocation, 1, imageIncrement));

    GR_GL_CALL(gl, Uniform1fv(fKernelLocation, this->width(), conv.kernel()));
}

GrGLProgramStage::StageKey GrGLConvolutionEffect::GenKey(
                                                    const GrCustomStage& s) {
    return static_cast<const GrConvolutionEffect&>(s).radius();
}

///////////////////////////////////////////////////////////////////////////////

GrConvolutionEffect::GrConvolutionEffect(Direction direction,
                                         int radius,
                                         const float* kernel)
    : Gr1DKernelEffect(direction, radius) {
    GrAssert(radius <= kMaxKernelRadius);
    int width = this->width();
    if (NULL != kernel) {
        for (int i = 0; i < width; i++) {
            fKernel[i] = kernel[i];
        }
    }
}

GrConvolutionEffect::~GrConvolutionEffect() {
}

const GrProgramStageFactory& GrConvolutionEffect::getFactory() const {
    return GrTProgramStageFactory<GrConvolutionEffect>::getInstance();
}

bool GrConvolutionEffect::isEqual(const GrCustomStage& sBase) const {
     const GrConvolutionEffect& s =
        static_cast<const GrConvolutionEffect&>(sBase);
    return (this->radius() == s.radius() &&
             this->direction() == s.direction() &&
             0 == memcmp(fKernel, s.fKernel, this->width() * sizeof(float)));
}

void GrConvolutionEffect::setGaussianKernel(float sigma) {
    int width = this->width();
    float sum = 0.0f;
    float denom = 1.0f / (2.0f * sigma * sigma);
    for (int i = 0; i < width; ++i) {
        float x = static_cast<float>(i - this->radius());
        // Note that the constant term (1/(sqrt(2*pi*sigma^2)) of the Gaussian
        // is dropped here, since we renormalize the kernel below.
        fKernel[i] = sk_float_exp(- x * x * denom);
        sum += fKernel[i];
    }
    // Normalize the kernel
    float scale = 1.0f / sum;
    for (int i = 0; i < width; ++i) {
        fKernel[i] *= scale;
    }
}
<|endoftext|>


<commit_before>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "gl/SkNativeGLContext.h"

#include <GL/glu.h>

SkNativeGLContext::AutoContextRestore::AutoContextRestore() {
    fOldGLXContext = glXGetCurrentContext();
    fOldDisplay = glXGetCurrentDisplay();
    fOldDrawable = glXGetCurrentDrawable();
}

SkNativeGLContext::AutoContextRestore::~AutoContextRestore() {
    if (NULL != fOldDisplay) {
        glXMakeCurrent(fOldDisplay, fOldDrawable, fOldGLXContext);
    }
}

///////////////////////////////////////////////////////////////////////////////

static bool ctxErrorOccurred = false;
static int ctxErrorHandler(Display *dpy, XErrorEvent *ev) {
    ctxErrorOccurred = true;
    return 0;
}

SkNativeGLContext::SkNativeGLContext()
    : fContext(NULL)
    , fDisplay(NULL)
    , fPixmap(0)
    , fGlxPixmap(0) {
}

SkNativeGLContext::~SkNativeGLContext() {
    this->destroyGLContext();
}

void SkNativeGLContext::destroyGLContext() {
    if (fDisplay) {
        glXMakeCurrent(fDisplay, 0, 0);

        if (fContext) {
            glXDestroyContext(fDisplay, fContext);
            fContext = NULL;
        }

        if (fGlxPixmap) {
            glXDestroyGLXPixmap(fDisplay, fGlxPixmap);
            fGlxPixmap = 0;
        }

        if (fPixmap) {
            XFreePixmap(fDisplay, fPixmap);
            fPixmap = 0;
        }

        XCloseDisplay(fDisplay);
        fDisplay = NULL;
    }
}

const GrGLInterface* SkNativeGLContext::createGLContext() {
    fDisplay = XOpenDisplay(0);

    if (!fDisplay) {
        SkDebugf("Failed to open X display.\n");
        this->destroyGLContext();
        return NULL;
    }

    // Get a matching FB config
    static int visual_attribs[] = {
        GLX_X_RENDERABLE    , True,
        GLX_DRAWABLE_TYPE   , GLX_PIXMAP_BIT,
        None
    };

    int glx_major, glx_minor;

    // FBConfigs were added in GLX version 1.3.
    if (!glXQueryVersion(fDisplay, &glx_major, &glx_minor) ||
            ( (glx_major == 1) && (glx_minor < 3) ) || (glx_major < 1))
    {
        SkDebugf("Invalid GLX version.");
        this->destroyGLContext();
        return NULL;
    }

    //SkDebugf("Getting matching framebuffer configs.\n");
    int fbcount;
    GLXFBConfig *fbc = glXChooseFBConfig(fDisplay, DefaultScreen(fDisplay),
                                          visual_attribs, &fbcount);
    if (!fbc) {
        SkDebugf("Failed to retrieve a framebuffer config.\n");
        this->destroyGLContext();
        return NULL;
    }
    //SkDebugf("Found %d matching FB configs.\n", fbcount);

    // Pick the FB config/visual with the most samples per pixel
    //SkDebugf("Getting XVisualInfos.\n");
    int best_fbc = -1, worst_fbc = -1, best_num_samp = -1, worst_num_samp = 999;

    int i;
    for (i = 0; i < fbcount; ++i) {
        XVisualInfo *vi = glXGetVisualFromFBConfig(fDisplay, fbc[i]);
        if (vi) {
            int samp_buf, samples;
            glXGetFBConfigAttrib(fDisplay, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf);
            glXGetFBConfigAttrib(fDisplay, fbc[i], GLX_SAMPLES, &samples);

            //SkDebugf("  Matching fbconfig %d, visual ID 0x%2x: SAMPLE_BUFFERS = %d,"
            //       " SAMPLES = %d\n",
            //        i, (unsigned int)vi->visualid, samp_buf, samples);

            if (best_fbc < 0 || (samp_buf && samples > best_num_samp))
                best_fbc = i, best_num_samp = samples;
            if (worst_fbc < 0 || !samp_buf || samples < worst_num_samp)
                worst_fbc = i, worst_num_samp = samples;
        }
        XFree(vi);
    }

    GLXFBConfig bestFbc = fbc[best_fbc];

    // Be sure to free the FBConfig list allocated by glXChooseFBConfig()
    XFree(fbc);

    // Get a visual
    XVisualInfo *vi = glXGetVisualFromFBConfig(fDisplay, bestFbc);
    //SkDebugf("Chosen visual ID = 0x%x\n", (unsigned int)vi->visualid);

    fPixmap = XCreatePixmap(fDisplay, RootWindow(fDisplay, vi->screen), 10, 10, vi->depth);

    if (!fPixmap) {
        SkDebugf("Failed to create pixmap.\n");
        this->destroyGLContext();
        return NULL;
    }

    fGlxPixmap = glXCreateGLXPixmap(fDisplay, vi, fPixmap);

    // Done with the visual info data
    XFree(vi);

    // Create the context

    // Install an X error handler so the application won't exit if GL 3.0
    // context allocation fails.
    //
    // Note this error handler is global.
    // All display connections in all threads of a process use the same
    // error handler, so be sure to guard against other threads issuing
    // X commands while this code is running.
    ctxErrorOccurred = false;
    int (*oldHandler)(Display*, XErrorEvent*) =
        XSetErrorHandler(&ctxErrorHandler);

    // Get the default screen's GLX extension list
    const char *glxExts = glXQueryExtensionsString(
        fDisplay, DefaultScreen(fDisplay)
    );
    // Check for the GLX_ARB_create_context extension string and the function.
    // If either is not present, use GLX 1.3 context creation method.
    if (!gluCheckExtension(
          reinterpret_cast<const GLubyte*>("GLX_ARB_create_context")
          , reinterpret_cast<const GLubyte*>(glxExts)))
    {
        //SkDebugf("GLX_ARB_create_context not found."
        //       " Using old-style GLX context.\n");
        fContext = glXCreateNewContext(fDisplay, bestFbc, GLX_RGBA_TYPE, 0, True);

    } else {
        //SkDebugf("Creating context.\n");

        PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB =
            (PFNGLXCREATECONTEXTATTRIBSARBPROC) glXGetProcAddressARB((GrGLubyte*)"glXCreateContextAttribsARB");
        int context_attribs[] = {
            GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
            GLX_CONTEXT_MINOR_VERSION_ARB, 0,
            //GLX_CONTEXT_FLAGS_ARB        , GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
            None
        };
        fContext = glXCreateContextAttribsARB(
            fDisplay, bestFbc, 0, True, context_attribs
        );

        // Sync to ensure any errors generated are processed.
        XSync(fDisplay, False);
        if (!ctxErrorOccurred && fContext) {
           //SkDebugf( "Created GL 3.0 context.\n" );
        } else {
            // Couldn't create GL 3.0 context.
            // Fall back to old-style 2.x context.
            // When a context version below 3.0 is requested,
            // implementations will return the newest context version compatible
            // with OpenGL versions less than version 3.0.

            // GLX_CONTEXT_MAJOR_VERSION_ARB = 1
            context_attribs[1] = 1;
            // GLX_CONTEXT_MINOR_VERSION_ARB = 0
            context_attribs[3] = 0;

            ctxErrorOccurred = false;

            //SkDebugf("Failed to create GL 3.0 context."
            //       " Using old-style GLX context.\n");
            fContext = glXCreateContextAttribsARB(
                fDisplay, bestFbc, 0, True, context_attribs
            );
        }
    }

    // Sync to ensure any errors generated are processed.
    XSync(fDisplay, False);

    // Restore the original error handler
    XSetErrorHandler(oldHandler);

    if (ctxErrorOccurred || !fContext) {
        SkDebugf("Failed to create an OpenGL context.\n");
        this->destroyGLContext();
        return NULL;
    }

    // Verify that context is a direct context
    if (!glXIsDirect(fDisplay, fContext)) {
        //SkDebugf("Indirect GLX rendering context obtained.\n");
    } else {
        //SkDebugf("Direct GLX rendering context obtained.\n");
    }

    //SkDebugf("Making context current.\n");
    if (!glXMakeCurrent(fDisplay, fGlxPixmap, fContext)) {
      SkDebugf("Could not set the context.\n");
        this->destroyGLContext();
        return NULL;
    }

    const GrGLInterface* interface = GrGLCreateNativeInterface();
    if (!interface) {
        SkDebugf("Failed to create gl interface");
        this->destroyGLContext();
        return NULL;
    }
    return interface;
}

void SkNativeGLContext::makeCurrent() const {
    if (!glXMakeCurrent(fDisplay, fGlxPixmap, fContext)) {
        SkDebugf("Could not set the context.\n");
    }
}
<commit_msg>This update fixes the problem with GLX failing to find a valid configuration on Linux laptops (Issue 513). <commit_after>
/*
 * Copyright 2011 Google Inc.
 *
 * Use of this source code is governed by a BSD-style license that can be
 * found in the LICENSE file.
 */
#include "gl/SkNativeGLContext.h"

#include <GL/glu.h>

#define GLX_1_3 1

SkNativeGLContext::AutoContextRestore::AutoContextRestore() {
    fOldGLXContext = glXGetCurrentContext();
    fOldDisplay = glXGetCurrentDisplay();
    fOldDrawable = glXGetCurrentDrawable();
}

SkNativeGLContext::AutoContextRestore::~AutoContextRestore() {
    if (NULL != fOldDisplay) {
        glXMakeCurrent(fOldDisplay, fOldDrawable, fOldGLXContext);
    }
}

///////////////////////////////////////////////////////////////////////////////

static bool ctxErrorOccurred = false;
static int ctxErrorHandler(Display *dpy, XErrorEvent *ev) {
    ctxErrorOccurred = true;
    return 0;
}

SkNativeGLContext::SkNativeGLContext()
    : fContext(NULL)
    , fDisplay(NULL)
    , fPixmap(0)
    , fGlxPixmap(0) {
}

SkNativeGLContext::~SkNativeGLContext() {
    this->destroyGLContext();
}

void SkNativeGLContext::destroyGLContext() {
    if (fDisplay) {
        glXMakeCurrent(fDisplay, 0, 0);

        if (fContext) {
            glXDestroyContext(fDisplay, fContext);
            fContext = NULL;
        }

        if (fGlxPixmap) {
            glXDestroyGLXPixmap(fDisplay, fGlxPixmap);
            fGlxPixmap = 0;
        }

        if (fPixmap) {
            XFreePixmap(fDisplay, fPixmap);
            fPixmap = 0;
        }

        XCloseDisplay(fDisplay);
        fDisplay = NULL;
    }
}

const GrGLInterface* SkNativeGLContext::createGLContext() {
    fDisplay = XOpenDisplay(0);

    if (!fDisplay) {
        SkDebugf("Failed to open X display.\n");
        this->destroyGLContext();
        return NULL;
    }

    // Get a matching FB config
    static int visual_attribs[] = {
        GLX_X_RENDERABLE    , True,
        GLX_DRAWABLE_TYPE   , GLX_PIXMAP_BIT,
        None
    };

#ifdef GLX_1_3
    //SkDebugf("Getting matching framebuffer configs.\n");
    int fbcount;
    GLXFBConfig *fbc = glXChooseFBConfig(fDisplay, DefaultScreen(fDisplay),
                                          visual_attribs, &fbcount);
    if (!fbc) {
        SkDebugf("Failed to retrieve a framebuffer config.\n");
        this->destroyGLContext();
        return NULL;
    }
    //SkDebugf("Found %d matching FB configs.\n", fbcount);

    // Pick the FB config/visual with the most samples per pixel
    //SkDebugf("Getting XVisualInfos.\n");
    int best_fbc = -1, best_num_samp = -1;

    int i;
    for (i = 0; i < fbcount; ++i) {
        XVisualInfo *vi = glXGetVisualFromFBConfig(fDisplay, fbc[i]);
        if (vi) {
            int samp_buf, samples;
            glXGetFBConfigAttrib(fDisplay, fbc[i], GLX_SAMPLE_BUFFERS, &samp_buf);
            glXGetFBConfigAttrib(fDisplay, fbc[i], GLX_SAMPLES, &samples);

            //SkDebugf("  Matching fbconfig %d, visual ID 0x%2x: SAMPLE_BUFFERS = %d,"
            //       " SAMPLES = %d\n",
            //        i, (unsigned int)vi->visualid, samp_buf, samples);

            if (best_fbc < 0 || (samp_buf && samples > best_num_samp))
                best_fbc = i, best_num_samp = samples;
        }
        XFree(vi);
    }

    GLXFBConfig bestFbc = fbc[best_fbc];

    // Be sure to free the FBConfig list allocated by glXChooseFBConfig()
    XFree(fbc);

    // Get a visual
    XVisualInfo *vi = glXGetVisualFromFBConfig(fDisplay, bestFbc);
    //SkDebugf("Chosen visual ID = 0x%x\n", (unsigned int)vi->visualid);
#else
    int numVisuals;
    XVisualInfo visTemplate, *visReturn;

    visReturn = XGetVisualInfo(fDisplay, VisualNoMask, &visTemplate, &numVisuals);
    if (NULL == visReturn)
    {
        SkDebugf("Failed to get visual information.\n");
        this->destroyGLContext();
        return NULL;
    }

    int best = -1, best_num_samp = -1;

    for (int i = 0; i < numVisuals; ++i)
    {
        int samp_buf, samples;

        glXGetConfig(fDisplay, &visReturn[i], GLX_SAMPLE_BUFFERS, &samp_buf);
        glXGetConfig(fDisplay, &visReturn[i], GLX_SAMPLES, &samples);

        if (best < 0 || (samp_buf && samples > best_num_samp))
            best = i, best_num_samp = samples;
    }

    XVisualInfo temp = visReturn[best];
    XVisualInfo *vi = &temp;

    XFree(visReturn);
#endif

    fPixmap = XCreatePixmap(fDisplay, RootWindow(fDisplay, vi->screen), 10, 10, vi->depth);

    if (!fPixmap) {
        SkDebugf("Failed to create pixmap.\n");
        this->destroyGLContext();
        return NULL;
    }

    fGlxPixmap = glXCreateGLXPixmap(fDisplay, vi, fPixmap);

#ifdef GLX_1_3
    // Done with the visual info data
    XFree(vi);
#endif

    // Create the context

    // Install an X error handler so the application won't exit if GL 3.0
    // context allocation fails.
    //
    // Note this error handler is global.
    // All display connections in all threads of a process use the same
    // error handler, so be sure to guard against other threads issuing
    // X commands while this code is running.
    ctxErrorOccurred = false;
    int (*oldHandler)(Display*, XErrorEvent*) =
        XSetErrorHandler(&ctxErrorHandler);

    // Get the default screen's GLX extension list
    const char *glxExts = glXQueryExtensionsString(
        fDisplay, DefaultScreen(fDisplay)
    );
    // Check for the GLX_ARB_create_context extension string and the function.
    // If either is not present, use GLX 1.3 context creation method.
    if (!gluCheckExtension(
          reinterpret_cast<const GLubyte*>("GLX_ARB_create_context")
          , reinterpret_cast<const GLubyte*>(glxExts)))
    {
        //SkDebugf("GLX_ARB_create_context not found."
        //       " Using old-style GLX context.\n");
#ifdef GLX_1_3
        fContext = glXCreateNewContext(fDisplay, bestFbc, GLX_RGBA_TYPE, 0, True);
#else
        fContext = glXCreateContext(fDisplay, vi, 0, True);
#endif

    }
#ifdef GLX_1_3
    else {
        //SkDebugf("Creating context.\n");

        PFNGLXCREATECONTEXTATTRIBSARBPROC glXCreateContextAttribsARB =
            (PFNGLXCREATECONTEXTATTRIBSARBPROC) glXGetProcAddressARB((GrGLubyte*)"glXCreateContextAttribsARB");
        int context_attribs[] = {
            GLX_CONTEXT_MAJOR_VERSION_ARB, 3,
            GLX_CONTEXT_MINOR_VERSION_ARB, 0,
            //GLX_CONTEXT_FLAGS_ARB        , GLX_CONTEXT_FORWARD_COMPATIBLE_BIT_ARB,
            None
        };
        fContext = glXCreateContextAttribsARB(
            fDisplay, bestFbc, 0, True, context_attribs
        );

        // Sync to ensure any errors generated are processed.
        XSync(fDisplay, False);
        if (!ctxErrorOccurred && fContext) {
           //SkDebugf( "Created GL 3.0 context.\n" );
        } else {
            // Couldn't create GL 3.0 context.
            // Fall back to old-style 2.x context.
            // When a context version below 3.0 is requested,
            // implementations will return the newest context version compatible
            // with OpenGL versions less than version 3.0.

            // GLX_CONTEXT_MAJOR_VERSION_ARB = 1
            context_attribs[1] = 1;
            // GLX_CONTEXT_MINOR_VERSION_ARB = 0
            context_attribs[3] = 0;

            ctxErrorOccurred = false;

            //SkDebugf("Failed to create GL 3.0 context."
            //       " Using old-style GLX context.\n");
            fContext = glXCreateContextAttribsARB(
                fDisplay, bestFbc, 0, True, context_attribs
            );
        }
    }
#endif

    // Sync to ensure any errors generated are processed.
    XSync(fDisplay, False);

    // Restore the original error handler
    XSetErrorHandler(oldHandler);

    if (ctxErrorOccurred || !fContext) {
        SkDebugf("Failed to create an OpenGL context.\n");
        this->destroyGLContext();
        return NULL;
    }

    // Verify that context is a direct context
    if (!glXIsDirect(fDisplay, fContext)) {
        //SkDebugf("Indirect GLX rendering context obtained.\n");
    } else {
        //SkDebugf("Direct GLX rendering context obtained.\n");
    }

    //SkDebugf("Making context current.\n");
    if (!glXMakeCurrent(fDisplay, fGlxPixmap, fContext)) {
      SkDebugf("Could not set the context.\n");
        this->destroyGLContext();
        return NULL;
    }

    const GrGLInterface* interface = GrGLCreateNativeInterface();
    if (!interface) {
        SkDebugf("Failed to create gl interface");
        this->destroyGLContext();
        return NULL;
    }
    return interface;
}

void SkNativeGLContext::makeCurrent() const {
    if (!glXMakeCurrent(fDisplay, fGlxPixmap, fContext)) {
        SkDebugf("Could not set the context.\n");
    }
}
<|endoftext|>


<commit_before>/* $Id$ */

/*
 * Copyright (c) 2014 Antonio de la Piedra
 * Copyright (c) 2013 Roland van Rijswijk-Deij
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*****************************************************************************
 silvia_irma_manager.h

 Credential manager for IRMA cards
 *****************************************************************************/

#include "config.h"
#include <gmpxx.h>
#include "silvia_types.h"
#include "silvia_apdu.h"
#include "silvia_rand.h"
#include "silvia_parameters.h"
#include "silvia_irma_manager.h"
#include <vector>
#include <iomanip>
#include <ctime>
#include <assert.h>
#include <time.h>

silvia_irma_manager::silvia_irma_manager()
{
	/* XXXX: Not implemented! */
}

silvia_irma_manager::~silvia_irma_manager()
{
}

std::vector<bytestring> silvia_irma_manager::get_log_commands(std::string PIN)
{
	bool rv = true;

	std::vector<bytestring> commands;
	std::vector<bytestring> results;

	assert(PIN.size() <= 8);

	////////////////////////////////////////////////////////////////////
	// Step 1: select application
	////////////////////////////////////////////////////////////////////

	commands.push_back("00A4040009F849524D416361726400");	// version >= 0.8

	////////////////////////////////////////////////////////////////////
	// Step 2: verify PIN
	////////////////////////////////////////////////////////////////////

	silvia_apdu verify_pin(0x00, 0x20, 0x00, 0x01);

	bytestring pin_data;
	pin_data.wipe(8);

	memcpy(&pin_data[0], PIN.c_str(), PIN.size());

	verify_pin.append_data(pin_data);

	commands.push_back(verify_pin.get_apdu());

	////////////////////////////////////////////////////////////////////
	// Step 3: Get log entries
	////////////////////////////////////////////////////////////////////

	for (char start_entry = 0x00; start_entry < LOG_SIZE; start_entry = (char)(start_entry + LOG_ENTRIES_PER_APDU))
	{
		silvia_apdu get_log_apdu(0x80, 0x3b, start_entry, 0x00);
		commands.push_back(get_log_apdu.get_apdu());
	}

	return commands;
}

std::vector<bytestring> silvia_irma_manager::del_cred_commands(std::string credential, std::string PIN)
{
	bool rv = true;

	std::vector<bytestring> commands;
	std::vector<bytestring> results;

	assert(PIN.size() <= 8);
	//assert(credential.size() == 2);

	////////////////////////////////////////////////////////////////////
	// Step 1: select application
	////////////////////////////////////////////////////////////////////

	commands.push_back("00A4040009F849524D416361726400");	// version >= 0.8

	////////////////////////////////////////////////////////////////////
	// Step 2: verify PIN
	////////////////////////////////////////////////////////////////////

	silvia_apdu verify_pin(0x00, 0x20, 0x00, 0x01);

	bytestring pin_data;
	pin_data.wipe(8);

	memcpy(&pin_data[0], PIN.c_str(), PIN.size());

	verify_pin.append_data(pin_data);

	commands.push_back(verify_pin.get_apdu());

	////////////////////////////////////////////////////////////////////
	// Step 3: select credential
	////////////////////////////////////////////////////////////////////

	std::stringstream ss;

	ss << std::setfill ('0') << std::setw(4) << std::hex << atoi(credential.c_str());
        std::string cmd = std::string("8030000002") + ss.str();
	commands.push_back(cmd.c_str());

	ss.str("");
	ss.clear();

	////////////////////////////////////////////////////////////////////
	// Step 4: delete credential
	////////////////////////////////////////////////////////////////////

	ss << std::setfill ('0') << std::setw(4) << std::hex << std::time(0); //timestamp
        std::string cmd_del = std::string("8031000004") + ss.str();

	commands.push_back(cmd_del.c_str());

	return commands;
}

std::vector<bytestring> silvia_irma_manager::update_admin_pin_commands(std::string old_pin, std::string new_pin)
{

	bool rv = true;

	std::vector<bytestring> commands;
	std::vector<bytestring> results;

	assert(old_pin.size() <= 8);
	assert(new_pin.size() <= 8);

	////////////////////////////////////////////////////////////////////
	// Step 1: select application
	////////////////////////////////////////////////////////////////////

	commands.push_back("00A4040009F849524D416361726400");	// version >= 0.8

	////////////////////////////////////////////////////////////////////
	// Step 2: update admin PIN
	////////////////////////////////////////////////////////////////////

	silvia_apdu verify_pin(0x00, 0x24, 0x00, 0x01);

	bytestring old_pin_data, new_pin_data;
	old_pin_data.wipe(8);
	new_pin_data.wipe(8);

	memcpy(&old_pin_data[0], old_pin.c_str(), old_pin.size());
	memcpy(&new_pin_data[0], new_pin.c_str(), new_pin.size());

	verify_pin.append_data(old_pin_data);
	verify_pin.append_data(new_pin_data);

	commands.push_back(verify_pin.get_apdu());

	return commands;
}

std::vector<bytestring> silvia_irma_manager::update_cred_pin_commands(std::string old_pin, std::string new_pin)
{
	/* XXXX: Not implemented! */
}

std::vector<bytestring> silvia_irma_manager::list_credentials_commands(std::string PIN)
{
	bool rv = true;

	std::vector<bytestring> commands;
	std::vector<bytestring> results;

	assert(PIN.size() <= 8);

	////////////////////////////////////////////////////////////////////
	// Step 1: select application
	////////////////////////////////////////////////////////////////////

	commands.push_back("00A4040009F849524D416361726400");	// version >= 0.8

	////////////////////////////////////////////////////////////////////
	// Step 2: verify PIN
	////////////////////////////////////////////////////////////////////

	silvia_apdu verify_pin(0x00, 0x20, 0x00, 0x01);

	bytestring pin_data;
	pin_data.wipe(8);

	memcpy(&pin_data[0], PIN.c_str(), PIN.size());

	verify_pin.append_data(pin_data);

	commands.push_back(verify_pin.get_apdu());

	////////////////////////////////////////////////////////////////////
	// Step 3: get credentials
	////////////////////////////////////////////////////////////////////

	silvia_apdu list_credentials(0x80, 0x3A, 0x00, 0x00);

	commands.push_back(list_credentials.get_apdu());

	return commands;
}
<commit_msg>silvia_irma_manager.cpp<commit_after>/* $Id$ */

/*
 * Copyright (c) 2014 Antonio de la Piedra
 * Copyright (c) 2013 Roland van Rijswijk-Deij
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
 * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
 * IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
 * IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*****************************************************************************
 silvia_irma_manager.h

 Credential manager for IRMA cards
 *****************************************************************************/

#include "config.h"
#include <gmpxx.h>
#include "silvia_types.h"
#include "silvia_apdu.h"
#include "silvia_rand.h"
#include "silvia_parameters.h"
#include "silvia_irma_manager.h"
#include <vector>
#include <iomanip>
#include <ctime>
#include <assert.h>
#include <time.h>

silvia_irma_manager::silvia_irma_manager()
{
	/* XXXX: Not implemented! */
}

silvia_irma_manager::~silvia_irma_manager()
{
}

std::vector<bytestring> silvia_irma_manager::get_log_commands(std::string PIN)
{
	bool rv = true;

	std::vector<bytestring> commands;
	std::vector<bytestring> results;

	assert(PIN.size() <= 8);

	////////////////////////////////////////////////////////////////////
	// Step 1: select application
	////////////////////////////////////////////////////////////////////

	commands.push_back("00A4040009F849524D416361726400");	// version >= 0.8

	////////////////////////////////////////////////////////////////////
	// Step 2: verify PIN
	////////////////////////////////////////////////////////////////////

	silvia_apdu verify_pin(0x00, 0x20, 0x00, 0x01);

	bytestring pin_data;
	pin_data.wipe(8);

	memcpy(&pin_data[0], PIN.c_str(), PIN.size());

	verify_pin.append_data(pin_data);

	commands.push_back(verify_pin.get_apdu());

	////////////////////////////////////////////////////////////////////
	// Step 3: Get log entries
	////////////////////////////////////////////////////////////////////

	for (char start_entry = 0x00; start_entry < LOG_SIZE; start_entry = (char)(start_entry + LOG_ENTRIES_PER_APDU))
	{
		silvia_apdu get_log_apdu(0x80, 0x3b, start_entry, 0x00);
		commands.push_back(get_log_apdu.get_apdu());
	}

	return commands;
}

std::vector<bytestring> silvia_irma_manager::del_cred_commands(std::string credential, std::string PIN)
{
	bool rv = true;

	std::vector<bytestring> commands;
	std::vector<bytestring> results;

	assert(PIN.size() <= 8);
	//assert(credential.size() == 2);

	////////////////////////////////////////////////////////////////////
	// Step 1: select application
	////////////////////////////////////////////////////////////////////

	commands.push_back("00A4040009F849524D416361726400");	// version >= 0.8

	////////////////////////////////////////////////////////////////////
	// Step 2: verify PIN
	////////////////////////////////////////////////////////////////////

	silvia_apdu verify_pin(0x00, 0x20, 0x00, 0x01);

	bytestring pin_data;
	pin_data.wipe(8);

	memcpy(&pin_data[0], PIN.c_str(), PIN.size());

	verify_pin.append_data(pin_data);

	commands.push_back(verify_pin.get_apdu());

	////////////////////////////////////////////////////////////////////
	// Step 3: select credential
	////////////////////////////////////////////////////////////////////

	std::stringstream ss;

	ss << std::setfill ('0') << std::setw(4) << std::hex << atoi(credential.c_str());
        std::string cmd = std::string("8030000002") + ss.str();
	commands.push_back(cmd.c_str());

	ss.str("");
	ss.clear();

	////////////////////////////////////////////////////////////////////
	// Step 4: delete credential
	////////////////////////////////////////////////////////////////////

	/* TODO: Add credential id in P1P2 for logging */
	ss << std::setfill ('0') << std::setw(4) << std::hex << std::time(0); //timestamp
        std::string cmd_del = std::string("8031000004") + ss.str();

	commands.push_back(cmd_del.c_str());

	return commands;
}

std::vector<bytestring> silvia_irma_manager::update_admin_pin_commands(std::string old_pin, std::string new_pin)
{

	bool rv = true;

	std::vector<bytestring> commands;
	std::vector<bytestring> results;

	assert(old_pin.size() <= 8);
	assert(new_pin.size() <= 8);

	////////////////////////////////////////////////////////////////////
	// Step 1: select application
	////////////////////////////////////////////////////////////////////

	commands.push_back("00A4040009F849524D416361726400");	// version >= 0.8

	////////////////////////////////////////////////////////////////////
	// Step 2: update admin PIN
	////////////////////////////////////////////////////////////////////

	silvia_apdu verify_pin(0x00, 0x24, 0x00, 0x01);

	bytestring old_pin_data, new_pin_data;
	old_pin_data.wipe(8);
	new_pin_data.wipe(8);

	memcpy(&old_pin_data[0], old_pin.c_str(), old_pin.size());
	memcpy(&new_pin_data[0], new_pin.c_str(), new_pin.size());

	verify_pin.append_data(old_pin_data);
	verify_pin.append_data(new_pin_data);

	commands.push_back(verify_pin.get_apdu());

	return commands;
}

std::vector<bytestring> silvia_irma_manager::update_cred_pin_commands(std::string old_pin, std::string new_pin)
{
	/* XXXX: Not implemented! */
}

std::vector<bytestring> silvia_irma_manager::list_credentials_commands(std::string PIN)
{
	bool rv = true;

	std::vector<bytestring> commands;
	std::vector<bytestring> results;

	assert(PIN.size() <= 8);

	////////////////////////////////////////////////////////////////////
	// Step 1: select application
	////////////////////////////////////////////////////////////////////

	commands.push_back("00A4040009F849524D416361726400");	// version >= 0.8

	////////////////////////////////////////////////////////////////////
	// Step 2: verify PIN
	////////////////////////////////////////////////////////////////////

	silvia_apdu verify_pin(0x00, 0x20, 0x00, 0x01);

	bytestring pin_data;
	pin_data.wipe(8);

	memcpy(&pin_data[0], PIN.c_str(), PIN.size());

	verify_pin.append_data(pin_data);

	commands.push_back(verify_pin.get_apdu());

	////////////////////////////////////////////////////////////////////
	// Step 3: get credentials
	////////////////////////////////////////////////////////////////////

	silvia_apdu list_credentials(0x80, 0x3A, 0x00, 0x00);

	commands.push_back(list_credentials.get_apdu());

	return commands;
}
<|endoftext|>


<commit_before>//
// Copyright 2017 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// SizedMRUCache_unittest.h: Unit tests for the sized MRU cached.

#include <gtest/gtest.h>

#include "libANGLE/SizedMRUCache.h"

namespace angle
{

using Blob = std::vector<uint8_t>;

Blob MakeBlob(size_t size)
{
    Blob blob;
    for (uint8_t value = 0; value < size; ++value)
    {
        blob.push_back(value);
    }
    return blob;
}

// Test a cache with a value that takes up maximum size.
TEST(SizedMRUCacheTest, MaxSizedValue)
{
    constexpr size_t kSize = 32;
    SizedMRUCache<std::string, Blob> sizedCache(kSize);

    EXPECT_TRUE(sizedCache.put("test", MakeBlob(kSize), kSize));
    EXPECT_EQ(32u, sizedCache.size());
    EXPECT_FALSE(sizedCache.empty());

    EXPECT_TRUE(sizedCache.put("test2", MakeBlob(kSize), kSize));
    EXPECT_EQ(32u, sizedCache.size());
    EXPECT_FALSE(sizedCache.empty());

    const Blob *blob = nullptr;
    EXPECT_FALSE(sizedCache.get("test", &blob));

    sizedCache.clear();
    EXPECT_TRUE(sizedCache.empty());
}

// Test a cache with many small values, that it can handle unlimited inserts.
TEST(SizedMRUCacheTest, ManySmallValues)
{
    constexpr size_t kSize = 32;
    SizedMRUCache<size_t, size_t> sizedCache(kSize);

    for (size_t value = 0; value < kSize; ++value)
    {
        EXPECT_TRUE(sizedCache.put(value, std::move(value), 1));

        const size_t *qvalue = nullptr;
        EXPECT_TRUE(sizedCache.get(value, &qvalue));
        if (qvalue)
        {
            EXPECT_EQ(value, *qvalue);
        }
    }

    EXPECT_EQ(32u, sizedCache.size());
    EXPECT_FALSE(sizedCache.empty());

    // Putting one element evicts the first element.
    EXPECT_TRUE(sizedCache.put(kSize, std::move(static_cast<int>(kSize)), 1));

    const size_t *qvalue = nullptr;
    EXPECT_FALSE(sizedCache.get(0, &qvalue));

    // Putting one large element cleans out the whole stack.
    EXPECT_TRUE(sizedCache.put(kSize + 1, kSize + 1, kSize));
    EXPECT_EQ(32u, sizedCache.size());
    EXPECT_FALSE(sizedCache.empty());

    for (size_t value = 0; value <= kSize; ++value)
    {
        EXPECT_FALSE(sizedCache.get(value, &qvalue));
    }
    EXPECT_TRUE(sizedCache.get(kSize + 1, &qvalue));
    if (qvalue)
    {
        EXPECT_EQ(kSize + 1, *qvalue);
    }

    // Put a bunch of items in the cache sequentially.
    for (size_t value = 0; value < kSize * 10; ++value)
    {
        EXPECT_TRUE(sizedCache.put(value, std::move(value), 1));
    }

    EXPECT_EQ(32u, sizedCache.size());
}

// Tests putting an oversize element.
TEST(SizedMRUCacheTest, OversizeValue)
{
    constexpr size_t kSize = 32;
    SizedMRUCache<size_t, size_t> sizedCache(kSize);

    EXPECT_FALSE(sizedCache.put(5, 5, 100));
}

}  // namespace angle
<commit_msg>Fix useless move() in SizedMRUCache_unittest.cpp<commit_after>//
// Copyright 2017 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// SizedMRUCache_unittest.h: Unit tests for the sized MRU cached.

#include <gtest/gtest.h>

#include "libANGLE/SizedMRUCache.h"

namespace angle
{

using Blob = std::vector<uint8_t>;

Blob MakeBlob(size_t size)
{
    Blob blob;
    for (uint8_t value = 0; value < size; ++value)
    {
        blob.push_back(value);
    }
    return blob;
}

// Test a cache with a value that takes up maximum size.
TEST(SizedMRUCacheTest, MaxSizedValue)
{
    constexpr size_t kSize = 32;
    SizedMRUCache<std::string, Blob> sizedCache(kSize);

    EXPECT_TRUE(sizedCache.put("test", MakeBlob(kSize), kSize));
    EXPECT_EQ(32u, sizedCache.size());
    EXPECT_FALSE(sizedCache.empty());

    EXPECT_TRUE(sizedCache.put("test2", MakeBlob(kSize), kSize));
    EXPECT_EQ(32u, sizedCache.size());
    EXPECT_FALSE(sizedCache.empty());

    const Blob *blob = nullptr;
    EXPECT_FALSE(sizedCache.get("test", &blob));

    sizedCache.clear();
    EXPECT_TRUE(sizedCache.empty());
}

// Test a cache with many small values, that it can handle unlimited inserts.
TEST(SizedMRUCacheTest, ManySmallValues)
{
    constexpr size_t kSize = 32;
    SizedMRUCache<size_t, size_t> sizedCache(kSize);

    for (size_t value = 0; value < kSize; ++value)
    {
        size_t valueCopy = value;
        EXPECT_TRUE(sizedCache.put(value, std::move(valueCopy), 1));

        const size_t *qvalue = nullptr;
        EXPECT_TRUE(sizedCache.get(value, &qvalue));
        if (qvalue)
        {
            EXPECT_EQ(value, *qvalue);
        }
    }

    EXPECT_EQ(32u, sizedCache.size());
    EXPECT_FALSE(sizedCache.empty());

    // Putting one element evicts the first element.
    EXPECT_TRUE(sizedCache.put(kSize, std::move(static_cast<int>(kSize)), 1));

    const size_t *qvalue = nullptr;
    EXPECT_FALSE(sizedCache.get(0, &qvalue));

    // Putting one large element cleans out the whole stack.
    EXPECT_TRUE(sizedCache.put(kSize + 1, kSize + 1, kSize));
    EXPECT_EQ(32u, sizedCache.size());
    EXPECT_FALSE(sizedCache.empty());

    for (size_t value = 0; value <= kSize; ++value)
    {
        EXPECT_FALSE(sizedCache.get(value, &qvalue));
    }
    EXPECT_TRUE(sizedCache.get(kSize + 1, &qvalue));
    if (qvalue)
    {
        EXPECT_EQ(kSize + 1, *qvalue);
    }

    // Put a bunch of items in the cache sequentially.
    for (size_t value = 0; value < kSize * 10; ++value)
    {
        size_t valueCopy = value;
        EXPECT_TRUE(sizedCache.put(value, std::move(valueCopy), 1));
    }

    EXPECT_EQ(32u, sizedCache.size());
}

// Tests putting an oversize element.
TEST(SizedMRUCacheTest, OversizeValue)
{
    constexpr size_t kSize = 32;
    SizedMRUCache<size_t, size_t> sizedCache(kSize);

    EXPECT_FALSE(sizedCache.put(5, 5, 100));
}

}  // namespace angle
<|endoftext|>


<commit_before>#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace cv;

int main( int argc, char** argv )
{
    Mat img(500, 500, CV_8UC3);
    RNG& rng = theRNG();

    for(;;)
    {
        char key;
        int i, count = (unsigned)rng%100 + 1;

        vector<Point> points;

        for( i = 0; i < count; i++ )
        {
            Point pt;
            pt.x = rng.uniform(img.cols/4, img.cols*3/4);
            pt.y = rng.uniform(img.rows/4, img.rows*3/4);

            points.push_back(pt);
        }

        vector<int> hull;
        convexHull(Mat(points), hull, CV_CLOCKWISE);

        img = Scalar::all(0);
        for( i = 0; i < count; i++ )
            circle(img, points[i], 3, Scalar(0, 0, 255), CV_FILLED, CV_AA);

        int hullcount = (int)hull.size();
        Point pt0 = points[hull[hullcount-1]];

        for( i = 0; i < hullcount; i++ )
        {
            Point pt = points[hull[i]];
            line(img, pt0, pt, Scalar(0, 255, 0), 1, CV_AA);
            pt0 = pt;
        }

        imshow("hull", img);

        key = (char)waitKey();
        if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
            break;
    }

    return 0;
}
<commit_msg>help function added<commit_after>#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>
#include <fstream>
#include <iostream>

using namespace cv;
using namespace std;

void help()
{
	cout << "\nThis sample demonstrates the use of the convexHull() function\n"
		 << "Call:\n"
		 << "./convexhull\n" << endl;
}

int main( int argc, char** argv )
{
    Mat img(500, 500, CV_8UC3);
    RNG& rng = theRNG();

    help();

    for(;;)
    {
        char key;
        int i, count = (unsigned)rng%100 + 1;

        vector<Point> points;

        for( i = 0; i < count; i++ )
        {
            Point pt;
            pt.x = rng.uniform(img.cols/4, img.cols*3/4);
            pt.y = rng.uniform(img.rows/4, img.rows*3/4);

            points.push_back(pt);
        }

        vector<int> hull;
        convexHull(Mat(points), hull, CV_CLOCKWISE);

        img = Scalar::all(0);
        for( i = 0; i < count; i++ )
            circle(img, points[i], 3, Scalar(0, 0, 255), CV_FILLED, CV_AA);

        int hullcount = (int)hull.size();
        Point pt0 = points[hull[hullcount-1]];

        for( i = 0; i < hullcount; i++ )
        {
            Point pt = points[hull[i]];
            line(img, pt0, pt, Scalar(0, 255, 0), 1, CV_AA);
            pt0 = pt;
        }

        imshow("hull", img);

        key = (char)waitKey();
        if( key == 27 || key == 'q' || key == 'Q' ) // 'ESC'
            break;
    }

    return 0;
}
<|endoftext|>


<commit_before>// Copyright (c) 2011 Timur Iskhodzhanov and MIPT students. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "gtest/gtest.h"

template<typename K, typename V>
class LruCache {
 public:
  explicit LruCache(int size) {}

  void Put(const K &key, const V &value) {}

  // Doesn't update timestamps.
  bool Contains(const K &key) const { return false; }

  // Updates timestamps.
  bool Lookup(const K &key, V *value) { return false; }

  bool LookupNoUpdate(const K &key, V *value) const { return false; }
};

TEST(LruCacheTests, DISABLED_Simple) {
  LruCache<int, int> lru(2);

  ASSERT_FALSE(lru.Contains(1));
  lru.Put(1 /* key */, 42 /* value */);
  ASSERT_TRUE(lru.Contains(1));
  int value = -1;
  ASSERT_TRUE(lru.Lookup(1, &value));
  ASSERT_EQ(421, value);

  lru.Put(13, 77);
  ASSERT_TRUE(lru.Contains(13));
  ASSERT_TRUE(lru.Contains(1));
}

TEST(LruCacheTests, DISABLED_Eviction) {
  LruCache<int, int> lru(2);
  lru.Put(1, 42);
  lru.Put(2, 13);
  ASSERT_TRUE(lru.Contains(1));
  ASSERT_TRUE(lru.Contains(2));

  lru.Put(3, 77);  // should evict '1'.
  ASSERT_FALSE(lru.Contains(1));
  ASSERT_TRUE(lru.Contains(2));
  ASSERT_TRUE(lru.Contains(3));

  lru.Put(2, 42);  // refreshes the timestamp of '2'
  ASSERT_TRUE(lru.Contains(2));
  int value = -1;
  ASSERT_TRUE(lru.LookupNoUpdate(2, &value));
  ASSERT_EQ(42, value);
  ASSERT_TRUE(lru.Contains(3));

  lru.Put(4, 99);  // should evict '3'.
  ASSERT_TRUE(lru.Contains(2));
  ASSERT_FALSE(lru.Contains(3));
  ASSERT_TRUE(lru.Contains(4));
}
<commit_msg>Intentionally break a test - 4<commit_after>// Copyright (c) 2011 Timur Iskhodzhanov and MIPT students. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "gtest/gtest.h"

template<typename K, typename V>
class LruCache {
 public:
  explicit LruCache(int size) {}

  void Put(const K &key, const V &value) {}

  // Doesn't update timestamps.
  bool Contains(const K &key) const { return false; }

  // Updates timestamps.
  bool Lookup(const K &key, V *value) { return false; }

  bool LookupNoUpdate(const K &key, V *value) const { return false; }
};

TEST(LruCacheTests, /*DISABLED_*/Simple) {
  LruCache<int, int> lru(2);

  ASSERT_FALSE(lru.Contains(1));
  lru.Put(1 /* key */, 42 /* value */);
  ASSERT_TRUE(lru.Contains(1));
  int value = -1;
  ASSERT_TRUE(lru.Lookup(1, &value));
  ASSERT_EQ(42, value);

  lru.Put(13, 77);
  ASSERT_TRUE(lru.Contains(13));
  ASSERT_TRUE(lru.Contains(1));
}

TEST(LruCacheTests, DISABLED_Eviction) {
  LruCache<int, int> lru(2);
  lru.Put(1, 42);
  lru.Put(2, 13);
  ASSERT_TRUE(lru.Contains(1));
  ASSERT_TRUE(lru.Contains(2));

  lru.Put(3, 77);  // should evict '1'.
  ASSERT_FALSE(lru.Contains(1));
  ASSERT_TRUE(lru.Contains(2));
  ASSERT_TRUE(lru.Contains(3));

  lru.Put(2, 42);  // refreshes the timestamp of '2'
  ASSERT_TRUE(lru.Contains(2));
  int value = -1;
  ASSERT_TRUE(lru.LookupNoUpdate(2, &value));
  ASSERT_EQ(42, value);
  ASSERT_TRUE(lru.Contains(3));

  lru.Put(4, 99);  // should evict '3'.
  ASSERT_TRUE(lru.Contains(2));
  ASSERT_FALSE(lru.Contains(3));
  ASSERT_TRUE(lru.Contains(4));
}
<|endoftext|>


<commit_before>/*
 * File:   testTANRA_all.cpp
 * Author: chteflio
 *
 * Created on August 24, 2015, 10:04 AM
 */

#include <iostream>
#include <taLib/taLib.h>

#include <sys/time.h>
#include <fstream>
#include <climits>
#include <cmath>
#include <algorithm>

using namespace std;
using namespace ta;
using namespace rg;

int main() {

    LEMPArg args;
    args.theta = 1.74;

    args.usersFile = "/home/chteflio/data/ta-data/so_x_p_proj5_1-w-50-svd.mma";
    args.itemsFile = "/home/chteflio/data/ta-data/so_x_p_proj5_1-h-50-svd.mma";

    args.logFile = "/home/chteflio/workspace/Log.txt";

    ta::TANRA_all algo(args);
    algo.multiply();

    return 0;
}

<commit_msg>Update testTANRA_all.cpp<commit_after>// Copyright 2015 Christina Teflioudi
//
// 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.
/*
* runNaive.cc
*
* Created on: Sep 21, 2012
* Author: chteflio
*/
/*
 * File:   testTANRA_all.cpp
 * Author: chteflio
 *
 * Created on August 24, 2015, 10:04 AM
 */

#include <iostream>
#include <taLib/taLib.h>

#include <sys/time.h>
#include <fstream>
#include <climits>
#include <cmath>
#include <algorithm>

using namespace std;
using namespace ta;
using namespace rg;

int main() {

    LEMPArg args;
    args.theta = 1.74;

    args.usersFile = "/home/chteflio/data/ta-data/so_x_p_proj5_1-w-50-svd.mma";
    args.itemsFile = "/home/chteflio/data/ta-data/so_x_p_proj5_1-h-50-svd.mma";

    args.logFile = "/home/chteflio/workspace/Log.txt";

    ta::TANRA_all algo(args);
    algo.multiply();

    return 0;
}

<|endoftext|>