<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_ddr_phy_reset.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_ddr_phy_reset.C
/// @brief Reset the DDR PHY
///
// *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 <stdint.h>
#include <string.h>

#include <fapi2.H>
#include <mss.H>

#include <p9_mss_ddr_phy_reset.H>
#include <lib/utils/count_dimm.H>
#include <lib/phy/adr32s.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/fir/check.H>
#include <lib/fir/unmask.H>

using fapi2::TARGET_TYPE_MCBIST;

extern "C"
{

///
/// @brief Perform a phy reset on all the PHY related to this half-chip (mcbist)
/// @param[in] the mcbist representing the PHY
/// @return FAPI2_RC_SUCCESS iff OK
///
    fapi2::ReturnCode p9_mss_ddr_phy_reset(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target)
    {

        // 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 ddr_phy_reset %s - no DIMM ...", mss::c_str(i_target));
            return fapi2::FAPI2_RC_SUCCESS;
        }

        FAPI_TRY(mss::change_force_mclk_low(i_target, mss::LOW),
                 "force_mclk_low (set high) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );

        // New for Nimbus - perform duty cycle clock distortion calibration
#ifdef RUN_DCD
        FAPI_TRY( mss::adr32s::duty_cycle_distortion_calibration(i_target) );
#endif

        // 1. Drive all control signals to the PHY to their inactive state, idle state, or inactive value.
        FAPI_TRY( mss::dp16::reset_sysclk(i_target) );

        //    (Note: The chip should already be in this state.)
        FAPI_DBG("All control signals to the PHYs should be set to their inactive state, idle state, or inactive values");

        // 2. Assert reset to PHY for 32 memory clocks
        FAPI_TRY( mss::change_resetn(i_target, mss::HIGH), "change_resetn for %s failed", mss::c_str(i_target) );
        fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32));

        // 3. Deassert reset_n
        FAPI_TRY( mss::change_resetn(i_target, mss::LOW), "change_resetn for %s failed", mss::c_str(i_target) );

        //
        // Flush output drivers
        //

        // 8. Set FLUSH=1 and INIT_IO=1 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL and DDRPHY_DP16_DATA_BIT_DIR1 register
        // 9. Wait at least 32 dphy_gckn clock cycles.
        // 10. Set FLUSH=0 and INIT_IO=0 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL register
        FAPI_TRY( mss::flush_output_drivers(i_target), "unable to flush output drivers for %s", mss::c_str(i_target) );

        //
        // ZCTL Enable
        //

        // 11. Assert the ZCNTL enable to the internal impedance controller in DDRPHY_PC_RESETS register
        // 12. Wait at least 1024 dphy_gckn cycles
        // 13. Deassert the ZCNTL impedance controller enable, Check for DONE in DDRPHY_PC_DLL_ZCAL
        FAPI_TRY( mss::enable_zctl(i_target), "enable_zctl for %s failed", mss::c_str(i_target) );

        //
        // DLL calibration
        //

        // 14. Begin DLL calibrations by setting INIT_RXDLL_CAL_RESET=0 in the DDRPHY_DP16_DLL_CNTL{0:1} registers
        // and DDRPHY_ADR_DLL_CNTL registers
        // 15. Monitor the DDRPHY_PC_DLL_ZCAL_CAL_STATUS register to determine when calibration is
        // complete. One of the 3 bits will be asserted for ADR and DP16.
        FAPI_INF( "starting DLL calibration %s", mss::c_str(i_target) );
        FAPI_TRY( mss::dll_calibration(i_target) );

        //
        // Start bang-bang-lock
        //

        // 16. Take dphy_nclk/SysClk alignment circuits out of reset and put into continuous update mode,
        FAPI_INF("set up of phase rotator controls %s", mss::c_str(i_target) );
        FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::ON) );

        // 17. Wait at least 5932 dphy_nclk clock cycles to allow the dphy_nclk/SysClk alignment circuit to
        // perform initial alignment.
        FAPI_INF("Wait at least 5932 memory clock cycles for clock alignment circuit to perform initial alignment %s",
                 mss::c_str(i_target));
        FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 5932), 2000) );

        // 18. Check for LOCK in DDRPHY_DP16_SYSCLK_PR_VALUE registers and DDRPHY_ADR_SYSCLK_PR_VALUE
        FAPI_INF("Checking for bang-bang lock %s ...", mss::c_str(i_target));
        FAPI_TRY( mss::check_bang_bang_lock(i_target) );

        // 19. Write 0b0 into the DDRPHY_PC_RESETS register bit 1. This write de-asserts the SYSCLK_RESET.
        FAPI_INF("deassert sysclk reset %s", mss::c_str(i_target));
        FAPI_TRY( mss::deassert_sysclk_reset(i_target), "deassert_sysclk_reset failed for %s", mss::c_str(i_target) );

        // 20. Write 8020h into the DDRPHY_ADR_SYSCLK_CNTL_PR Registers and
        // DDRPHY_DP16_SYSCLK_PR0/1 registers This write takes the dphy_nclk/
        // SysClk alignment circuit out of the Continuous Update mode.
        FAPI_INF("take sysclk alignment out of cont update mode %s", mss::c_str(i_target));
        FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::OFF),
                  "set up of phase rotator controls failed (out of cont update) %s", mss::c_str(i_target) );

        // 21. Wait at least 32 dphy_nclk clock cycles.
        FAPI_DBG("Wait at least 32 memory clock cycles %s", mss::c_str(i_target));
        FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32)) );

        //
        // Done bang-bang-lock
        //

        // Per J. Bialas, force_mclk_low can be dasserted.
        FAPI_TRY(mss::change_force_mclk_low(i_target, mss::HIGH),
                 "force_mclk_low (set low) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );

        // Workarounds
        FAPI_TRY( mss::workarounds::dp16::after_phy_reset(i_target) );

        // mss::check::during_phy_reset checks to see if there are any FIR. We do this 'twice' once here
        // (as part of the good-path) and once if we jump to the fapi_try label.
        if ((fapi2::current_err = mss::check::during_phy_reset(i_target)) != fapi2::FAPI2_RC_SUCCESS)
        {
            goto leave_for_real;
        }

        // Unmask the FIR we want unmasked after phy reset is complete. Note this is the "good path."
        // The algorithm is 'good path do after_phy_reset, all paths (error or not) perform the checks
        // which are defined in during_phy_reset'. We won't run after_phy_reset (unmask of FIR) unless
        // we're done with a success.
        FAPI_TRY( mss::unmask::after_phy_reset(i_target) );

        // Leave as we're all good and checked the FIR already ...
        return fapi2::current_err;

        // ... here on a bad-path, check FIR and leave ...
    fapi_try_exit:

        // mss::check::during_phy_reset handles the error/no error case internally. All we need to do is
        // return the ReturnCode it hands us - it's taken care of commiting anything it needed to.
        return mss::check::during_phy_reset(i_target);

        // ... here if the good-path FIR check found an error. We jumped over the unmasking and are
        // returning an error to the caller.
    leave_for_real:
        return fapi2::current_err;

    }

}
<commit_msg>Updates code to run PHY DCD calibration<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/memory/p9_mss_ddr_phy_reset.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_ddr_phy_reset.C
/// @brief Reset the DDR PHY
///
// *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 <stdint.h>
#include <string.h>

#include <fapi2.H>
#include <mss.H>

#include <p9_mss_ddr_phy_reset.H>
#include <lib/utils/count_dimm.H>
#include <lib/phy/adr32s.H>
#include <lib/workarounds/dp16_workarounds.H>
#include <lib/fir/check.H>
#include <lib/fir/unmask.H>

using fapi2::TARGET_TYPE_MCBIST;

extern "C"
{

///
/// @brief Perform a phy reset on all the PHY related to this half-chip (mcbist)
/// @param[in] the mcbist representing the PHY
/// @return FAPI2_RC_SUCCESS iff OK
///
    fapi2::ReturnCode p9_mss_ddr_phy_reset(const fapi2::Target<fapi2::TARGET_TYPE_MCBIST>& i_target)
    {

        // 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 ddr_phy_reset %s - no DIMM ...", mss::c_str(i_target));
            return fapi2::FAPI2_RC_SUCCESS;
        }

        FAPI_TRY(mss::change_force_mclk_low(i_target, mss::LOW),
                 "force_mclk_low (set high) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );

        // 1. Drive all control signals to the PHY to their inactive state, idle state, or inactive value.
        FAPI_TRY( mss::dp16::reset_sysclk(i_target) );

        //    (Note: The chip should already be in this state.)
        FAPI_DBG("All control signals to the PHYs should be set to their inactive state, idle state, or inactive values");

        // 2. Assert reset to PHY for 32 memory clocks
        FAPI_TRY( mss::change_resetn(i_target, mss::HIGH), "change_resetn for %s failed", mss::c_str(i_target) );
        fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32));

        // 3. Deassert reset_n
        FAPI_TRY( mss::change_resetn(i_target, mss::LOW), "change_resetn for %s failed", mss::c_str(i_target) );

        //
        // Flush output drivers
        //

        // 8. Set FLUSH=1 and INIT_IO=1 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL and DDRPHY_DP16_DATA_BIT_DIR1 register
        // 9. Wait at least 32 dphy_gckn clock cycles.
        // 10. Set FLUSH=0 and INIT_IO=0 in the DDRPHY_ADR_OUTPUT_FORCE_ATEST_CNTL register
        FAPI_TRY( mss::flush_output_drivers(i_target), "unable to flush output drivers for %s", mss::c_str(i_target) );

        //
        // ZCTL Enable
        //

        // 11. Assert the ZCNTL enable to the internal impedance controller in DDRPHY_PC_RESETS register
        // 12. Wait at least 1024 dphy_gckn cycles
        // 13. Deassert the ZCNTL impedance controller enable, Check for DONE in DDRPHY_PC_DLL_ZCAL
        FAPI_TRY( mss::enable_zctl(i_target), "enable_zctl for %s failed", mss::c_str(i_target) );

        //
        // DLL calibration
        //

        // 14. Begin DLL calibrations by setting INIT_RXDLL_CAL_RESET=0 in the DDRPHY_DP16_DLL_CNTL{0:1} registers
        // and DDRPHY_ADR_DLL_CNTL registers
        // 15. Monitor the DDRPHY_PC_DLL_ZCAL_CAL_STATUS register to determine when calibration is
        // complete. One of the 3 bits will be asserted for ADR and DP16.
        FAPI_INF( "starting DLL calibration %s", mss::c_str(i_target) );
        FAPI_TRY( mss::dll_calibration(i_target) );

        //
        // Start bang-bang-lock
        //

        // 16. Take dphy_nclk/SysClk alignment circuits out of reset and put into continuous update mode,
        FAPI_INF("set up of phase rotator controls %s", mss::c_str(i_target) );
        FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::ON) );

        // 17. Wait at least 5932 dphy_nclk clock cycles to allow the dphy_nclk/SysClk alignment circuit to
        // perform initial alignment.
        FAPI_INF("Wait at least 5932 memory clock cycles for clock alignment circuit to perform initial alignment %s",
                 mss::c_str(i_target));
        FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 5932), 2000) );

        // 18. Check for LOCK in DDRPHY_DP16_SYSCLK_PR_VALUE registers and DDRPHY_ADR_SYSCLK_PR_VALUE
        FAPI_INF("Checking for bang-bang lock %s ...", mss::c_str(i_target));
        FAPI_TRY( mss::check_bang_bang_lock(i_target) );

        // 19. Write 0b0 into the DDRPHY_PC_RESETS register bit 1. This write de-asserts the SYSCLK_RESET.
        FAPI_INF("deassert sysclk reset %s", mss::c_str(i_target));
        FAPI_TRY( mss::deassert_sysclk_reset(i_target), "deassert_sysclk_reset failed for %s", mss::c_str(i_target) );

        // 20. Write 8020h into the DDRPHY_ADR_SYSCLK_CNTL_PR Registers and
        // DDRPHY_DP16_SYSCLK_PR0/1 registers This write takes the dphy_nclk/
        // SysClk alignment circuit out of the Continuous Update mode.
        FAPI_INF("take sysclk alignment out of cont update mode %s", mss::c_str(i_target));
        FAPI_TRY( mss::setup_phase_rotator_control_registers(i_target, mss::OFF),
                  "set up of phase rotator controls failed (out of cont update) %s", mss::c_str(i_target) );

        // 21. Wait at least 32 dphy_nclk clock cycles.
        FAPI_DBG("Wait at least 32 memory clock cycles %s", mss::c_str(i_target));
        FAPI_TRY( fapi2::delay(mss::cycles_to_ns(i_target, 32), mss::cycles_to_simcycles(32)) );

        //
        // Done bang-bang-lock
        //

        // Per J. Bialas, force_mclk_low can be dasserted.
        FAPI_TRY(mss::change_force_mclk_low(i_target, mss::HIGH),
                 "force_mclk_low (set low) Failed rc = 0x%08X", uint64_t(fapi2::current_err) );

        // Workarounds
        FAPI_TRY( mss::workarounds::dp16::after_phy_reset(i_target) );

        // New for Nimbus - perform duty cycle clock distortion calibration (DCD cal)
        // Per PHY team's characterization, the DCD cal needs to be run after DLL calibration
        FAPI_TRY( mss::adr32s::duty_cycle_distortion_calibration(i_target) );

        // mss::check::during_phy_reset checks to see if there are any FIR. We do this 'twice' once here
        // (as part of the good-path) and once if we jump to the fapi_try label.
        if ((fapi2::current_err = mss::check::during_phy_reset(i_target)) != fapi2::FAPI2_RC_SUCCESS)
        {
            goto leave_for_real;
        }

        // Unmask the FIR we want unmasked after phy reset is complete. Note this is the "good path."
        // The algorithm is 'good path do after_phy_reset, all paths (error or not) perform the checks
        // which are defined in during_phy_reset'. We won't run after_phy_reset (unmask of FIR) unless
        // we're done with a success.
        FAPI_TRY( mss::unmask::after_phy_reset(i_target) );

        // Leave as we're all good and checked the FIR already ...
        return fapi2::current_err;

        // ... here on a bad-path, check FIR and leave ...
    fapi_try_exit:

        // mss::check::during_phy_reset handles the error/no error case internally. All we need to do is
        // return the ReturnCode it hands us - it's taken care of commiting anything it needed to.
        return mss::check::during_phy_reset(i_target);

        // ... here if the good-path FIR check found an error. We jumped over the unmasking and are
        // returning an error to the caller.
    leave_for_real:
        return fapi2::current_err;

    }

}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_chiplet_enable_ridi.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_chiplet_enable_ridi.C
///
/// @brief Enable RI/DI chip wide
//------------------------------------------------------------------------------
// *HWP HW Owner        : Abhishek Agarwal <abagarw8@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_chiplet_enable_ridi.H"

#include "p9_perv_scom_addresses.H"

static fapi2::ReturnCode p9_chiplet_enable_ridi_net_ctrl_action_function(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);

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

    for(auto l_target_cplt : i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV>
        (fapi2::TARGET_FILTER_SYNC_MODE_ALL_IO_EXCEPT_NEST, fapi2::TARGET_STATE_FUNCTIONAL))
    {
        FAPI_INF("Call p9_chiplet_enable_ridi_net_ctrl_action_function");
        FAPI_TRY(p9_chiplet_enable_ridi_net_ctrl_action_function(l_target_cplt));
    }

    FAPI_DBG("Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}

/// @brief Enable Drivers/Recievers of MC, ABUS, OBUS, XBUS chiplet
///
/// @param[in]     i_target_chiplet   Reference to TARGET_TYPE_PERV target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_chiplet_enable_ridi_net_ctrl_action_function(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
    bool l_read_reg = false;
    fapi2::buffer<uint64_t> l_data64;
    FAPI_DBG("Entering ...");

    FAPI_INF("Check for chiplet enable");
    //Getting NET_CTRL0 register value
    FAPI_TRY(fapi2::getScom(i_target_chiplet, PERV_NET_CTRL0, l_data64));
    l_read_reg = l_data64.getBit<0>();  //l_read_reg = NET_CTRL0.CHIPLET_ENABLE

    if ( l_read_reg )
    {
        FAPI_INF("Enable Recievers, Drivers DI1 & DI2");
        //Setting NET_CTRL0 register value
        l_data64.flush<0>();
        l_data64.setBit<19>();  //NET_CTRL0.RI_N = 1
        l_data64.setBit<20>();  //NET_CTRL0.DI1_N = 1
        l_data64.setBit<21>();  //NET_CTRL0.DI2_N = 1
        FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WOR, l_data64));
    }

    FAPI_DBG("Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}
<commit_msg>security -- split p9_chiplet_scominit and p9_chiplet_enable_ridi isteps<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_chiplet_enable_ridi.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_chiplet_enable_ridi.C
///
/// @brief Enable RI/DI for all IO chiplets (excluding XBUS)
//------------------------------------------------------------------------------
// *HWP HW Owner        : Abhishek Agarwal <abagarw8@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_chiplet_enable_ridi.H"

#include "p9_perv_scom_addresses.H"

static fapi2::ReturnCode p9_chiplet_enable_ridi_net_ctrl_action_function(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet);

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

    for(auto l_target_cplt : i_target_chip.getChildren<fapi2::TARGET_TYPE_PERV>
        (static_cast<fapi2::TargetFilter>(fapi2::TARGET_FILTER_ALL_MC  |
                                          fapi2::TARGET_FILTER_ALL_PCI |
                                          fapi2::TARGET_FILTER_ALL_OBUS),
         fapi2::TARGET_STATE_FUNCTIONAL))
    {
        FAPI_INF("Call p9_chiplet_enable_ridi_net_ctrl_action_function");
        FAPI_TRY(p9_chiplet_enable_ridi_net_ctrl_action_function(l_target_cplt));
    }

    FAPI_DBG("Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}

/// @brief Enable Drivers/Recievers of O, PCIE, MC chiplets
///
/// @param[in]     i_target_chiplet   Reference to TARGET_TYPE_PERV target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
static fapi2::ReturnCode p9_chiplet_enable_ridi_net_ctrl_action_function(
    const fapi2::Target<fapi2::TARGET_TYPE_PERV>& i_target_chiplet)
{
    bool l_read_reg = false;
    fapi2::buffer<uint64_t> l_data64;
    FAPI_DBG("Entering ...");

    FAPI_INF("Check for chiplet enable");
    //Getting NET_CTRL0 register value
    FAPI_TRY(fapi2::getScom(i_target_chiplet, PERV_NET_CTRL0, l_data64));
    l_read_reg = l_data64.getBit<0>();  //l_read_reg = NET_CTRL0.CHIPLET_ENABLE

    if ( l_read_reg )
    {
        FAPI_INF("Enable Recievers, Drivers DI1 & DI2");
        //Setting NET_CTRL0 register value
        l_data64.flush<0>();
        l_data64.setBit<19>();  //NET_CTRL0.RI_N = 1
        l_data64.setBit<20>();  //NET_CTRL0.DI1_N = 1
        l_data64.setBit<21>();  //NET_CTRL0.DI2_N = 1
        FAPI_TRY(fapi2::putScom(i_target_chiplet, PERV_NET_CTRL0_WOR, l_data64));
    }

    FAPI_DBG("Exiting ...");

fapi_try_exit:
    return fapi2::current_err;

}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_pgpe.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017,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                                                     */
#ifndef __PM_RECOVERY_FFDC_PGPE_
#define __PM_RECOVERY_FFDC_PGPE_

///
/// @file   p9_pm_recovery_ffdc_pgpe.H
/// @brief  Models PGPE platform for the FFDC collection of PM complex
///
/// *HWP HWP Owner:      Greg Still <stillgs@us.ibm.com>
/// *HWP FW Owner:       Prem S Jha <premjha2@in.ibm.com>
/// *HWP Team:           PM
/// *HWP Level:          2
/// *HWP Consumed by:    Hostboot
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <fapi2.H>
#include <stdint.h>
#include <p9_pm_recovery_ffdc_base.H>

namespace p9_stop_recov_ffdc
{

    class PlatPgpe : public PlatPmComplex
    {
            public:
            /// @brief  constructor
            PlatPgpe( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt );

            /// @brief  destructor
            virtual ~PlatPgpe() { };

            /// @brief      Initializes the PGPE FFDC Sub-Section in HOMER with default header
            /// @param[in]  i_pHomerBuf  points to base of P9 HOMER.
            ///  @return     fapi2 return code
            fapi2::ReturnCode init ( void* i_pHomerBuf );

            /// @brief      collects FFDC pertaining to all functional PGPEs in the chip.
            /// @param[in]  i_pHomerBuf  points to base of P9 HOMER.
            /// @param[in]  i_ffdcType   indicates the content type to collect
            /// @return     fapi2 return code.
            fapi2::ReturnCode collectFfdc( void*   i_pHomerBuf,
                                           uint8_t i_ffdcType = ALL );

        private:
            /// @brief      collects trace info from PGPE's SRAM buffer.
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for PGPE Trace info.
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectTrace( uint8_t * i_pHomerBuf );

            /// @brief      collects  global variables from PGPE's's SRAM.
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for PGPE's global variable
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectGlobals( uint8_t * i_pHomerBuf );

            /// @brief      collects PGPE state
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for PGPE's state.
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectPgpeState( uint8_t * i_pHomerBuf );

            /// @brief      collects internal register info for a PGPE
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for PGPE internal register.
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectInternalReg( uint8_t * i_pHomerBuf );

            /// @brief      collects PGPE Image Header info from PGPE SRAM buffer.
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for PGPE's header.
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectImageHeader( uint8_t * i_pHomerBuf );

            /// @brief updates the PGPE FFDC Header
            ///@param[in]   i_pHomerBuf     points to a location in HOMER meant for PGPE FFDC Header
            ///@param[in]   i_sectionsValid bit vector summarizing FFDC validity
            ///@return      fapi2 return code.
            fapi2::ReturnCode updatePgpeFfdcHeader( uint8_t* i_pHomerBuf,
                                                    uint16_t i_sectionsValid );

            ///@brief returns type of platform
            PmComplexPlatId getPlatType() { return iv_plat; }

        private:
            PmComplexPlatId iv_plat;
    };

extern "C"
{
    typedef fapi2::ReturnCode( *p9_pm_recovery_ffdc_pgpe_FP_t )
            ( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > & i_procChipTgt,
              void * i_pgpeFfdcBuf );
}

} //namespace p9_stop_recov_ffdc ends

#endif //__PM_RECOVERY_FFDC_PGPE_
<commit_msg>PM: Generation of summarized version of STOP Recovery FFDC.<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_recovery_ffdc_pgpe.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2017,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                                                     */
#ifndef __PM_RECOVERY_FFDC_PGPE_
#define __PM_RECOVERY_FFDC_PGPE_

///
/// @file   p9_pm_recovery_ffdc_pgpe.H
/// @brief  Models PGPE platform for the FFDC collection of PM complex
///
/// *HWP HWP Owner:      Greg Still <stillgs@us.ibm.com>
/// *HWP FW Owner:       Prem S Jha <premjha2@in.ibm.com>
/// *HWP Team:           PM
/// *HWP Level:          2
/// *HWP Consumed by:    Hostboot
//
// *INDENT-OFF*
//--------------------------------------------------------------------------
// Includes
//--------------------------------------------------------------------------
#include <fapi2.H>
#include <stdint.h>
#include <p9_pm_recovery_ffdc_base.H>

namespace p9_stop_recov_ffdc
{

    class PlatPgpe : public PlatPmComplex
    {
            public:
            /// @brief  constructor
            PlatPgpe( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > i_procChipTgt );

            /// @brief  destructor
            virtual ~PlatPgpe() { };

            /// @brief      Initializes the PGPE FFDC Sub-Section in HOMER with default header
            /// @param[in]  i_pHomerBuf  points to base of P9 HOMER.
            ///  @return     fapi2 return code
            fapi2::ReturnCode init ( void* i_pHomerBuf );

            /// @brief      collects FFDC pertaining to all functional PGPEs in the chip.
            /// @param[in]  i_pHomerBuf  points to base of P9 HOMER.
            /// @param[in]  i_ffdcType   indicates the content type to collect
            /// @return     fapi2 return code.
            fapi2::ReturnCode collectFfdc( void*   i_pHomerBuf,
                                           uint8_t i_ffdcType = ALL );

            /// @brief      generates summary of FFDC pertaining to a given platform.
            /// @param[in]  i_pHomer    points to Homer base.
            /// @return     fapi2 return code
            fapi2::ReturnCode generateSummary( void * i_pHomer );

        private:
            /// @brief      collects trace info from PGPE's SRAM buffer.
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for PGPE Trace info.
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectTrace( uint8_t * i_pHomerBuf );

            /// @brief      collects  global variables from PGPE's's SRAM.
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for PGPE's global variable
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectGlobals( uint8_t * i_pHomerBuf );

            /// @brief      collects PGPE state
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for PGPE's state.
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectPgpeState( uint8_t * i_pHomerBuf );

            /// @brief      collects internal register info for a PGPE
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for PGPE internal register.
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectInternalReg( uint8_t * i_pHomerBuf );

            /// @brief      collects PGPE Image Header info from PGPE SRAM buffer.
            /// @param[in]  i_pHomerBuf     points to location of HOMER meant for PGPE's header.
            /// @return     fapi2 return code.
            fapi2::ReturnCode  collectImageHeader( uint8_t * i_pHomerBuf );

            /// @brief updates the PGPE FFDC Header
            ///@param[in]   i_pHomerBuf     points to a location in HOMER meant for PGPE FFDC Header
            ///@param[in]   i_sectionsValid bit vector summarizing FFDC validity
            ///@return      fapi2 return code.
            fapi2::ReturnCode updatePgpeFfdcHeader( uint8_t* i_pHomerBuf,
                                                    uint16_t i_sectionsValid );

            ///@brief returns type of platform
            PmComplexPlatId getPlatType() { return iv_plat; }

            ///@brief initializes a list of register for generation of FFDC summary.
            void initRegList();

        private:
            PmComplexPlatId iv_plat;
    };

    //---------------------------------------------------------------------------------------------
    // function pointer typedef definition for HWP call support
    typedef fapi2::ReturnCode( *p9_pm_recovery_ffdc_pgpe_FP_t )
            ( const fapi2::Target< fapi2::TARGET_TYPE_PROC_CHIP > & i_procChipTgt,
              void * i_pgpeFfdcBuf );
extern "C"
{
    // -----------------------------------------------------------------------------
    // Function prototypes
    // -----------------------------------------------------------------------------
    ///
    /// @brief Populates the PGPE FFDC section with FFDC collected from PGPE.
    ///
    /// @param[in] i_procChipTarget Proc Chip target
    /// @param[in] i_pHomerImage    Pointer to the base of the chip HOMER region
    ///
    /// @return FAPI2_RC_SUCCESS on success or error return code
    ///
        fapi2::ReturnCode p9_pm_recovery_ffdc_pgpe
        ( const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_procChipTarget,
          void* i_pHomerImage );
}

} //namespace p9_stop_recov_ffdc ends

#endif //__PM_RECOVERY_FFDC_PGPE_
<|endoftext|>


<commit_before>7fcc05e8-4b02-11e5-96f1-28cfe9171a43<commit_msg>fixes, fixes for everyone<commit_after>7fd895c2-4b02-11e5-a89c-28cfe9171a43<|endoftext|>


<commit_before>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2010 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <iomanip>

#include <vpr/vpr.h>
#include <vpr/IO/Port/SerialPort.h>
#include <vpr/IO/Port/SerialTypes.h>

int main (int argc, char* argv[])
{
   vpr::SerialPort* port;

   port = new vpr::SerialPort(argv[1]);

   port->setOpenReadWrite();
   port->setBlocking(false);
   try
   {
      port->open();
      unsigned char read_buffer[27];
      //int val;

      std::cerr << "Port opened\n";
      //port->setUpdateAction(vpr::SerialTypes::NOW);
      //port->flushQueue(vpr::SerialTypes::IO_QUEUES);
      port->clearAll();
      port->setRead(true);
      port->setMinInputSize(1);
      //port->setCanonicalInput(false);
      //port->setLocalAttach(true);
      //port->setBreakByteIgnore(true);

      port->setOutputBaudRate(115200); // Put me before input to be safe
      port->setInputBaudRate(115200);
      port->setCharacterSize(vpr::SerialTypes::CS_BITS_8);

      //port->setHardwareFlowControl(false);
      //port->setParityGeneration(false);
      //port->setInputParityCheck(false);
      //port->setStartStopInput(false);
      //port->setStopBits(1);
      std::cerr << "reading\n";

      const char *hex = "0123456789abcdef";

      unsigned int how_many = 0;
      //port->flushQueue(vpr::SerialTypes::IO_QUEUES);
      unsigned int min_val[14];
      unsigned int max_val[14];

      for ( int i = 0; i > -1; i++ )
      {
         std::vector<vpr::Uint8> sm_rd;
         unsigned int how_many_start = 0;
         unsigned int how_many_end = 0;
         unsigned int bytes_read;
         bytes_read = port->read(sm_rd, 1);
         vpr::Uint8 switcher;

         std::vector<unsigned int> glove_rec;

         for(unsigned int j = 0; j < bytes_read; ++j)
         {
            //switcher = ((sm_rd[j] >> 4) & 0x0f) | ((sm_rd[j] << 4) & 0xf0);
            switcher = sm_rd[j];
               //std::cout
               //   << hex[((switcher & 0xf0) >> 4) & 0x0f ]
               //   << hex[((switcher & 0x0f) >> 0) & 0x0f ]  << " " << std::endl;
            while(switcher != 0x3c)
            {
               bytes_read = port->read(sm_rd, 1);
               switcher = sm_rd[j];
               //std::cout
               //   << hex[((switcher & 0xf0) >> 4) & 0x0f ]
               //   << hex[((switcher & 0x0f) >> 0) & 0x0f ]  << " ";
            }
#if 1
            if(switcher == 0x3c)
            {
               //std::cout << float(sm_rd) / 255.0 << " ";
               //port->read(&sm_rd, 1);
               how_many_start++;
               //std::cout << "<";
               //std::cout << std::endl;
               how_many = 0;
               //std::cout
               //   << hex[((switcher & 0xf0) >> 4) & 0x0f ]
               //   << hex[((switcher & 0x0f) >> 0) & 0x0f ] ;
               glove_rec.push_back(  ( ((switcher & 0xf0) >> 4) & 0x0f ) );
               glove_rec.push_back(  ( ((switcher & 0x0f) >> 0) & 0x0f ) );

               //std::cout << int( ((switcher & 0xf0) >> 4) & 0x0f )  << " "
               //          << int( ((switcher & 0x0f) >> 0) & 0x0f ) << std::endl;

               bytes_read = 0;
               while( bytes_read < 28 )
               {
                  unsigned int bytes_this_read = 0;
                  bytes_this_read = port->read(sm_rd, 28 - bytes_read);
                  bytes_read+=bytes_this_read;
                  for( unsigned int kk=0; kk < bytes_this_read; ++kk)
                  {
                     //switcher = ((sm_rd[kk] >> 4) & 0x0f) | ((sm_rd[kk] << 4) & 0xf0);
                     switcher = sm_rd[kk]; // >> 4) & 0x0f) | ((sm_rd[kk] << 4) & 0xf0);
                     glove_rec.push_back( (((switcher & 0xf0) >> 4) & 0x0f ));
                     glove_rec.push_back( (((switcher & 0x0f) >> 0) & 0x0f ));

                     //std::cout << " "
                     //   << int(((switcher & 0xf0) >> 4) & 0x0f);
                     //   << hex[((switcher & 0x0f) >> 0) & 0x0f ] ;
                   }
               }
               //std::cout << int(glove_rec[6]) << std::endl;

               unsigned int sens_num = 12;
               unsigned int offset = 7;
               unsigned int reading = 0;

               //( ((glove_rec[sens_num + offset] & 0x0f) >> 4) & 0x0f ) |
               //std::cout << int ( ( glove_rec[sens_num + offset] << 8) & 0x0f00) << " "
               //          << int ( ( glove_rec[sens_num + offset + 1] << 4) & 0x00f0) << " "
               //          << int ( ( glove_rec[sens_num + offset + 2] << 0) & 0x000f) << std::endl;
                          //( ((glove_rec[sens_num + offset + 1] & 0x0f) >> 4) & 0x0f );// |
                          //( ((glove_rec[sens_num + offset + 2] & 0x0f) >> 4) & 0x0f ) ;
               reading =     ( ( ( (glove_rec[sens_num + offset] & 0x000f) << 8) & 0x0f00) |
                               ( ( (glove_rec[sens_num + offset + 1] & 0x000f) << 4) & 0x00f0) |
                               ( ( (glove_rec[sens_num + offset + 2] & 0x000f) << 0) & 0x000f) );

               for(unsigned int foo = 0; foo < glove_rec.size(); foo++)
               {
                  if( /* (foo <= 5 && foo % 2 == 0) || */
                      (foo >  5 && foo % 3 == 0 && foo < 48) /*||
                      (foo >= 54 && foo % 2 == 0)*/
                    )
                     std::cout << "[";

                  if(foo >  5 && foo % 3 == 0 && foo < 48)
                  {
                     reading=( ( ( (glove_rec[foo] & 0x000f) << 8) & 0x0f00) |
                               ( ( (glove_rec[foo + 1] & 0x000f) << 4) & 0x00f0) |
                               ( ( (glove_rec[foo + 2] & 0x000f) << 0) & 0x000f) );
                     unsigned int entry = (foo - 6) / 3;
                     if(i == 0)
                     {
                        min_val[entry] = reading;
                        max_val[entry] = reading;
                     }
                     else
                     {
                        if( reading > max_val[entry] )
                        {
                           max_val[entry] = reading;
                        }
                        if( reading < min_val[entry] )
                        {
                           min_val[entry] = reading;
                        }
                     }
                     float top = (reading - min_val[entry]);
                     float bottom = (max_val[entry] - min_val[entry]);
                     float new_reading = (top / bottom);

                     //std::cout << reading;
                     std::cout << entry << "] " << std::fixed << std::setprecision(2) << new_reading << " ";
                  }
                  else if( foo <= 5 || foo >=54 )
                  {
                     //std::cout << hex[((glove_rec[foo] & 0x000f) >> 0) & 0x000f ] ;
                  }

                  //if( /* (foo <= 5 && foo % 2 == 1) || */
                    //  (foo > 5 && foo % 3 == 2 && foo < 51) /* ||
                     // (foo >= 54 && foo % 2 == 1)*/
                   // )
                   //  std::cout << "] ";

                  /*
                  if( foo == 5 )
                  {
                     std::cout << "   ";
                  }
                  if( foo == 53 )
                  {
                     std::cout << "   ";
                  }
                  */
               }
               std::cout << std::endl;
               //std::cout << "  (" << sens_num << " : " << reading << ")"  << std::endl;
               bytes_read = 0;
               glove_rec.clear();
            }
            //port->flushQueue(vpr::SerialTypes::INPUT_QUEUE);

#endif
#if 0
            how_many++;

            //std::cout << std::setbase(16) << sm_rd[j] << " ";;

            //port->read(&sm_rd,1);
            if(sm_rd[j] == 0x3e)
            {
               //std::cout << float(sm_rd) / 255.0 << " ";
               //port->read(&sm_rd, 1);
               //std::cout << ">";
               how_many_end++;
               std::cout << std::endl;
               how_many = 0;
            }

            if (how_many > 28 )
            {
               std::cout << std::endl;
               how_many = 0;
            }
#endif

         }
         //std::cout << std::endl;
         //std::cout << bytes_read << "  < " << how_many_start << "  >" << how_many_end << std::endl;
         //port->flushQueue(vpr::SerialTypes::INPUT_QUEUE);

#if 0
         std::cout << "... Got it! :" << std::setbase(16) << read_buffer[0] << std::endl;

         memset((void*) &read_buffer, '\0', sizeof(read_buffer));
         port->read(read_buffer, sizeof(read_buffer));

         std::cout << "Type: " << std::setbase(16) << read_buffer[0];
         std::cout << "     Version: " << float(read_buffer[1]) << std::endl;
         for( unsigned int i = 2; i < 25; ++i )
         {
            std::cout << float(read_buffer[i]) << " ";
         }
         std::cout << std::endl;
         std::cout << "Checksum: " << int(read_buffer[25]);
         std::cout << " " << std::setbase(16) << read_buffer[26] << std::endl;

         //val = atoi(read_buffer);
         //val++;
#endif
      }
      //std::cout << std::endl;
   }
   catch(...)
   {
      std::cout << "Serial Port Failed" << std::endl;
   }

   return 0;
}
<commit_msg>Silenced an unused variable warning.<commit_after>/*************** <auto-copyright.pl BEGIN do not edit this line> **************
 *
 * VR Juggler is (C) Copyright 1998-2010 by Iowa State University
 *
 * Original Authors:
 *   Allen Bierbaum, Christopher Just,
 *   Patrick Hartling, Kevin Meinert,
 *   Carolina Cruz-Neira, Albert Baker
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 *
 *************** <auto-copyright.pl END do not edit this line> ***************/

#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <iomanip>

#include <vpr/vpr.h>
#include <vpr/IO/Port/SerialPort.h>
#include <vpr/IO/Port/SerialTypes.h>

int main (int argc, char* argv[])
{
   vpr::SerialPort* port;

   port = new vpr::SerialPort(argv[1]);

   port->setOpenReadWrite();
   port->setBlocking(false);
   try
   {
      port->open();
      //int val;

      std::cerr << "Port opened\n";
      //port->setUpdateAction(vpr::SerialTypes::NOW);
      //port->flushQueue(vpr::SerialTypes::IO_QUEUES);
      port->clearAll();
      port->setRead(true);
      port->setMinInputSize(1);
      //port->setCanonicalInput(false);
      //port->setLocalAttach(true);
      //port->setBreakByteIgnore(true);

      port->setOutputBaudRate(115200); // Put me before input to be safe
      port->setInputBaudRate(115200);
      port->setCharacterSize(vpr::SerialTypes::CS_BITS_8);

      //port->setHardwareFlowControl(false);
      //port->setParityGeneration(false);
      //port->setInputParityCheck(false);
      //port->setStartStopInput(false);
      //port->setStopBits(1);
      std::cerr << "reading\n";

      const char *hex = "0123456789abcdef";

      unsigned int how_many = 0;
      //port->flushQueue(vpr::SerialTypes::IO_QUEUES);
      unsigned int min_val[14];
      unsigned int max_val[14];

      for ( int i = 0; i > -1; i++ )
      {
         std::vector<vpr::Uint8> sm_rd;
         unsigned int how_many_start = 0;
         unsigned int how_many_end = 0;
         unsigned int bytes_read;
         bytes_read = port->read(sm_rd, 1);
         vpr::Uint8 switcher;

         std::vector<unsigned int> glove_rec;

         for(unsigned int j = 0; j < bytes_read; ++j)
         {
            //switcher = ((sm_rd[j] >> 4) & 0x0f) | ((sm_rd[j] << 4) & 0xf0);
            switcher = sm_rd[j];
               //std::cout
               //   << hex[((switcher & 0xf0) >> 4) & 0x0f ]
               //   << hex[((switcher & 0x0f) >> 0) & 0x0f ]  << " " << std::endl;
            while(switcher != 0x3c)
            {
               bytes_read = port->read(sm_rd, 1);
               switcher = sm_rd[j];
               //std::cout
               //   << hex[((switcher & 0xf0) >> 4) & 0x0f ]
               //   << hex[((switcher & 0x0f) >> 0) & 0x0f ]  << " ";
            }
#if 1
            if(switcher == 0x3c)
            {
               //std::cout << float(sm_rd) / 255.0 << " ";
               //port->read(&sm_rd, 1);
               how_many_start++;
               //std::cout << "<";
               //std::cout << std::endl;
               how_many = 0;
               //std::cout
               //   << hex[((switcher & 0xf0) >> 4) & 0x0f ]
               //   << hex[((switcher & 0x0f) >> 0) & 0x0f ] ;
               glove_rec.push_back(  ( ((switcher & 0xf0) >> 4) & 0x0f ) );
               glove_rec.push_back(  ( ((switcher & 0x0f) >> 0) & 0x0f ) );

               //std::cout << int( ((switcher & 0xf0) >> 4) & 0x0f )  << " "
               //          << int( ((switcher & 0x0f) >> 0) & 0x0f ) << std::endl;

               bytes_read = 0;
               while( bytes_read < 28 )
               {
                  unsigned int bytes_this_read = 0;
                  bytes_this_read = port->read(sm_rd, 28 - bytes_read);
                  bytes_read+=bytes_this_read;
                  for( unsigned int kk=0; kk < bytes_this_read; ++kk)
                  {
                     //switcher = ((sm_rd[kk] >> 4) & 0x0f) | ((sm_rd[kk] << 4) & 0xf0);
                     switcher = sm_rd[kk]; // >> 4) & 0x0f) | ((sm_rd[kk] << 4) & 0xf0);
                     glove_rec.push_back( (((switcher & 0xf0) >> 4) & 0x0f ));
                     glove_rec.push_back( (((switcher & 0x0f) >> 0) & 0x0f ));

                     //std::cout << " "
                     //   << int(((switcher & 0xf0) >> 4) & 0x0f);
                     //   << hex[((switcher & 0x0f) >> 0) & 0x0f ] ;
                   }
               }
               //std::cout << int(glove_rec[6]) << std::endl;

               unsigned int sens_num = 12;
               unsigned int offset = 7;
               unsigned int reading = 0;

               //( ((glove_rec[sens_num + offset] & 0x0f) >> 4) & 0x0f ) |
               //std::cout << int ( ( glove_rec[sens_num + offset] << 8) & 0x0f00) << " "
               //          << int ( ( glove_rec[sens_num + offset + 1] << 4) & 0x00f0) << " "
               //          << int ( ( glove_rec[sens_num + offset + 2] << 0) & 0x000f) << std::endl;
                          //( ((glove_rec[sens_num + offset + 1] & 0x0f) >> 4) & 0x0f );// |
                          //( ((glove_rec[sens_num + offset + 2] & 0x0f) >> 4) & 0x0f ) ;
               reading =     ( ( ( (glove_rec[sens_num + offset] & 0x000f) << 8) & 0x0f00) |
                               ( ( (glove_rec[sens_num + offset + 1] & 0x000f) << 4) & 0x00f0) |
                               ( ( (glove_rec[sens_num + offset + 2] & 0x000f) << 0) & 0x000f) );

               for(unsigned int foo = 0; foo < glove_rec.size(); foo++)
               {
                  if( /* (foo <= 5 && foo % 2 == 0) || */
                      (foo >  5 && foo % 3 == 0 && foo < 48) /*||
                      (foo >= 54 && foo % 2 == 0)*/
                    )
                     std::cout << "[";

                  if(foo >  5 && foo % 3 == 0 && foo < 48)
                  {
                     reading=( ( ( (glove_rec[foo] & 0x000f) << 8) & 0x0f00) |
                               ( ( (glove_rec[foo + 1] & 0x000f) << 4) & 0x00f0) |
                               ( ( (glove_rec[foo + 2] & 0x000f) << 0) & 0x000f) );
                     unsigned int entry = (foo - 6) / 3;
                     if(i == 0)
                     {
                        min_val[entry] = reading;
                        max_val[entry] = reading;
                     }
                     else
                     {
                        if( reading > max_val[entry] )
                        {
                           max_val[entry] = reading;
                        }
                        if( reading < min_val[entry] )
                        {
                           min_val[entry] = reading;
                        }
                     }
                     float top = (reading - min_val[entry]);
                     float bottom = (max_val[entry] - min_val[entry]);
                     float new_reading = (top / bottom);

                     //std::cout << reading;
                     std::cout << entry << "] " << std::fixed << std::setprecision(2) << new_reading << " ";
                  }
                  else if( foo <= 5 || foo >=54 )
                  {
                     //std::cout << hex[((glove_rec[foo] & 0x000f) >> 0) & 0x000f ] ;
                  }

                  //if( /* (foo <= 5 && foo % 2 == 1) || */
                    //  (foo > 5 && foo % 3 == 2 && foo < 51) /* ||
                     // (foo >= 54 && foo % 2 == 1)*/
                   // )
                   //  std::cout << "] ";

                  /*
                  if( foo == 5 )
                  {
                     std::cout << "   ";
                  }
                  if( foo == 53 )
                  {
                     std::cout << "   ";
                  }
                  */
               }
               std::cout << std::endl;
               //std::cout << "  (" << sens_num << " : " << reading << ")"  << std::endl;
               bytes_read = 0;
               glove_rec.clear();
            }
            //port->flushQueue(vpr::SerialTypes::INPUT_QUEUE);

#endif
#if 0
            how_many++;

            //std::cout << std::setbase(16) << sm_rd[j] << " ";;

            //port->read(&sm_rd,1);
            if(sm_rd[j] == 0x3e)
            {
               //std::cout << float(sm_rd) / 255.0 << " ";
               //port->read(&sm_rd, 1);
               //std::cout << ">";
               how_many_end++;
               std::cout << std::endl;
               how_many = 0;
            }

            if (how_many > 28 )
            {
               std::cout << std::endl;
               how_many = 0;
            }
#endif

         }
         //std::cout << std::endl;
         //std::cout << bytes_read << "  < " << how_many_start << "  >" << how_many_end << std::endl;
         //port->flushQueue(vpr::SerialTypes::INPUT_QUEUE);

#if 0
         std::cout << "... Got it! :" << std::setbase(16) << read_buffer[0] << std::endl;

         memset((void*) &read_buffer, '\0', sizeof(read_buffer));
         port->read(read_buffer, sizeof(read_buffer));

         std::cout << "Type: " << std::setbase(16) << read_buffer[0];
         std::cout << "     Version: " << float(read_buffer[1]) << std::endl;
         for( unsigned int i = 2; i < 25; ++i )
         {
            std::cout << float(read_buffer[i]) << " ";
         }
         std::cout << std::endl;
         std::cout << "Checksum: " << int(read_buffer[25]);
         std::cout << " " << std::setbase(16) << read_buffer[26] << std::endl;

         //val = atoi(read_buffer);
         //val++;
#endif
      }
      //std::cout << std::endl;
   }
   catch(...)
   {
      std::cout << "Serial Port Failed" << std::endl;
   }

   return 0;
}
<|endoftext|>


<commit_before>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2011, Dirk Holz (University of Bonn)
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * 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.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "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
 *  COPYRIGHT OWNER OR CONTRIBUTORS 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.
 *
 * $Id$
 *
 */

#ifndef PCL_SURFACE_ORGANIZED_FAST_MESH_HPP_
#define PCL_SURFACE_ORGANIZED_FAST_MESH_HPP_

#include <pcl/surface/organized_fast_mesh.h>

/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::performReconstruction (pcl::PolygonMesh &output)
{
  reconstructPolygons (output.polygons);

  // Get the field names
  int x_idx = pcl::getFieldIndex (output.cloud, "x");
  int y_idx = pcl::getFieldIndex (output.cloud, "y");
  int z_idx = pcl::getFieldIndex (output.cloud, "z");
  if (x_idx == -1 || y_idx == -1 || z_idx == -1)
    return;
  // correct all measurements,
  // (running over complete image since some rows and columns are left out
  // depending on triangle_pixel_size)
  // avoid to do that here (only needed for ASCII mesh file output, e.g., in vtk files
  for (unsigned int i = 0; i < input_->points.size (); ++i)
    if (!isFinite (input_->points[i]))
      resetPointData (i, output, 0.0f, x_idx, y_idx, z_idx);
}

/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::performReconstruction (std::vector<pcl::Vertices> &polygons)
{
  reconstructPolygons (polygons);
}

/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::reconstructPolygons (std::vector<pcl::Vertices> &polygons)
{
  if (triangulation_type_ == TRIANGLE_RIGHT_CUT)
    makeRightCutMesh (polygons);
  else if (triangulation_type_ == TRIANGLE_LEFT_CUT)
    makeLeftCutMesh (polygons);
  else if (triangulation_type_ == TRIANGLE_ADAPTIVE_CUT)
    makeAdaptiveCutMesh (polygons);
  else if (triangulation_type_ == QUAD_MESH)
    makeQuadMesh (polygons);
}

/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeQuadMesh (std::vector<pcl::Vertices>& polygons)
{
  int last_column = input_->width - triangle_pixel_size_;
  int last_row = input_->height - triangle_pixel_size_;

  int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
  int y_big_incr = triangle_pixel_size_ * input_->width,
      x_big_incr = y_big_incr + triangle_pixel_size_;
  // Reserve enough space
  polygons.resize (input_->width * input_->height);

  // Go over the rows first
  for (int y = 0; y < last_row; y += triangle_pixel_size_)
  {
    // Initialize a new row
    i = y * input_->width;
    index_right = i + triangle_pixel_size_;
    index_down = i + y_big_incr;
    index_down_right = i + x_big_incr;

    // Go over the columns
    for (int x = 0; x < last_column; x += triangle_pixel_size_,
                                     i += triangle_pixel_size_,
                                     index_right += triangle_pixel_size_,
                                     index_down += triangle_pixel_size_,
                                     index_down_right += triangle_pixel_size_)
    {
      if (isValidQuad (i, index_right, index_down_right, index_down))
        if (store_shadowed_faces_ || !isShadowedQuad (i, index_right, index_down_right, index_down))
          addQuad (i, index_right, index_down_right, index_down, idx++, polygons);
    }
  }
  polygons.resize (idx);
}

/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeRightCutMesh (std::vector<pcl::Vertices>& polygons)
{
  int last_column = input_->width - triangle_pixel_size_;
  int last_row = input_->height - triangle_pixel_size_;

  int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
  int y_big_incr = triangle_pixel_size_ * input_->width,
      x_big_incr = y_big_incr + triangle_pixel_size_;
  // Reserve enough space
  polygons.resize (input_->width * input_->height * 2);

  // Go over the rows first
  for (int y = 0; y < last_row; y += triangle_pixel_size_)
  {
    // Initialize a new row
    i = y * input_->width;
    index_right = i + triangle_pixel_size_;
    index_down = i + y_big_incr;
    index_down_right = i + x_big_incr;

    // Go over the columns
    for (int x = 0; x < last_column; x += triangle_pixel_size_,
                                     i += triangle_pixel_size_,
                                     index_right += triangle_pixel_size_,
                                     index_down += triangle_pixel_size_,
                                     index_down_right += triangle_pixel_size_)
    {
      if (isValidTriangle (i, index_down_right, index_right))
        if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down_right, index_right))
          addTriangle (i, index_down_right, index_right, idx++, polygons);

      if (isValidTriangle (i, index_down, index_down_right))
        if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_down_right))
          addTriangle (i, index_down, index_down_right, idx++, polygons);
    }
  }
  polygons.resize (idx);
}

/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeLeftCutMesh (std::vector<pcl::Vertices>& polygons)
{
  int last_column = input_->width - triangle_pixel_size_;
  int last_row = input_->height - triangle_pixel_size_;

  int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
  int y_big_incr = triangle_pixel_size_ * input_->width,
      x_big_incr = y_big_incr + triangle_pixel_size_;
  // Reserve enough space
  polygons.resize (input_->width * input_->height * 2);

  // Go over the rows first
  for (int y = 0; y < last_row; y += triangle_pixel_size_)
  {
    // Initialize a new row
    i = y * input_->width;
    index_right = i + triangle_pixel_size_;
    index_down = i + y_big_incr;
    index_down_right = i + x_big_incr;

    // Go over the columns
    for (int x = 0; x < last_column; x += triangle_pixel_size_,
                                     i += triangle_pixel_size_,
                                     index_right += triangle_pixel_size_,
                                     index_down += triangle_pixel_size_,
                                     index_down_right += triangle_pixel_size_)
    {
      if (isValidTriangle (i, index_down, index_right))
        if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_right))
          addTriangle (i, index_down, index_right, idx++, polygons);

      if (isValidTriangle (index_right, index_down, index_down_right))
        if (store_shadowed_faces_ || !isShadowedTriangle (index_right, index_down, index_down_right))
          addTriangle (index_right, index_down, index_down_right, idx++, polygons);
    }
  }
  polygons.resize (idx);
}

/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeAdaptiveCutMesh (std::vector<pcl::Vertices>& polygons)
{
  int last_column = input_->width - triangle_pixel_size_;
  int last_row = input_->height - triangle_pixel_size_;

  int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
  int y_big_incr = triangle_pixel_size_ * input_->width,
      x_big_incr = y_big_incr + triangle_pixel_size_;
  // Reserve enough space
  polygons.resize (input_->width * input_->height * 4);

  // Go over the rows first
  for (int y = 0; y < last_row; y += triangle_pixel_size_)
  {
    // Initialize a new row
    i = y * input_->width;
    index_right = i + triangle_pixel_size_;
    index_down = i + y_big_incr;
    index_down_right = i + x_big_incr;

    // Go over the columns
    for (int x = 0; x < last_column; x += triangle_pixel_size_,
                                     i += triangle_pixel_size_,
                                     index_right += triangle_pixel_size_,
                                     index_down += triangle_pixel_size_,
                                     index_down_right += triangle_pixel_size_)
    {
      const bool right_cut_upper = isValidTriangle (i, index_down_right, index_right);
      const bool right_cut_lower = isValidTriangle (i, index_down, index_down_right);
      const bool left_cut_upper = isValidTriangle (i, index_down, index_right);
      const bool left_cut_lower = isValidTriangle (index_right, index_down, index_down_right);

      if (right_cut_upper && right_cut_lower && left_cut_upper && left_cut_lower)
      {
        float dist_right_cut = fabs (input_->points[index_down].z - input_->points[index_right].z);
        float dist_left_cut = fabs (input_->points[i].z - input_->points[index_down_right].z);
        if (dist_right_cut >= dist_left_cut)
        {
          if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down_right, index_right))
            addTriangle (i, index_down_right, index_right, idx++, polygons);
          if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_down_right))
            addTriangle (i, index_down, index_down_right, idx++, polygons);
        }
        else
        {
          if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_right))
            addTriangle (i, index_down, index_right, idx++, polygons);
          if (store_shadowed_faces_ || !isShadowedTriangle (index_right, index_down, index_down_right))
            addTriangle (index_right, index_down, index_down_right, idx++, polygons);
        }
      }
      else
      {
        if (right_cut_upper)
          if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down_right, index_right))
            addTriangle (i, index_down_right, index_right, idx++, polygons);
        if (right_cut_lower)
          if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_down_right))
            addTriangle (i, index_down, index_down_right, idx++, polygons);
        if (left_cut_upper)
          if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_right))
            addTriangle (i, index_down, index_right, idx++, polygons);
        if (left_cut_lower)
          if (store_shadowed_faces_ || !isShadowedTriangle (index_right, index_down, index_down_right))
            addTriangle (index_right, index_down, index_down_right, idx++, polygons);
      }
    }
  }
  polygons.resize (idx);
}

#define PCL_INSTANTIATE_OrganizedFastMesh(T)                \
  template class PCL_EXPORTS pcl::OrganizedFastMesh<T>;

#endif  // PCL_SURFACE_ORGANIZED_FAST_MESH_HPP_
<commit_msg>Corrected OrganizedFastMesh quad vertex order<commit_after>/*
 * Software License Agreement (BSD License)
 *
 *  Point Cloud Library (PCL) - www.pointclouds.org
 *  Copyright (c) 2011, Dirk Holz (University of Bonn)
 *  Copyright (c) 2010-2011, Willow Garage, Inc.
 *
 *  All rights reserved.
 *
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions
 *  are met:
 *
 *   * Redistributions of source code must retain the above copyright
 *     notice, this list of conditions and the following disclaimer.
 *   * 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.
 *   * Neither the name of Willow Garage, Inc. nor the names of its
 *     contributors may be used to endorse or promote products derived
 *     from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 *  "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
 *  COPYRIGHT OWNER OR CONTRIBUTORS 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.
 *
 * $Id$
 *
 */

#ifndef PCL_SURFACE_ORGANIZED_FAST_MESH_HPP_
#define PCL_SURFACE_ORGANIZED_FAST_MESH_HPP_

#include <pcl/surface/organized_fast_mesh.h>

/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::performReconstruction (pcl::PolygonMesh &output)
{
  reconstructPolygons (output.polygons);

  // Get the field names
  int x_idx = pcl::getFieldIndex (output.cloud, "x");
  int y_idx = pcl::getFieldIndex (output.cloud, "y");
  int z_idx = pcl::getFieldIndex (output.cloud, "z");
  if (x_idx == -1 || y_idx == -1 || z_idx == -1)
    return;
  // correct all measurements,
  // (running over complete image since some rows and columns are left out
  // depending on triangle_pixel_size)
  // avoid to do that here (only needed for ASCII mesh file output, e.g., in vtk files
  for (unsigned int i = 0; i < input_->points.size (); ++i)
    if (!isFinite (input_->points[i]))
      resetPointData (i, output, 0.0f, x_idx, y_idx, z_idx);
}

/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::performReconstruction (std::vector<pcl::Vertices> &polygons)
{
  reconstructPolygons (polygons);
}

/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::reconstructPolygons (std::vector<pcl::Vertices> &polygons)
{
  if (triangulation_type_ == TRIANGLE_RIGHT_CUT)
    makeRightCutMesh (polygons);
  else if (triangulation_type_ == TRIANGLE_LEFT_CUT)
    makeLeftCutMesh (polygons);
  else if (triangulation_type_ == TRIANGLE_ADAPTIVE_CUT)
    makeAdaptiveCutMesh (polygons);
  else if (triangulation_type_ == QUAD_MESH)
    makeQuadMesh (polygons);
}

/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeQuadMesh (std::vector<pcl::Vertices>& polygons)
{
  int last_column = input_->width - triangle_pixel_size_;
  int last_row = input_->height - triangle_pixel_size_;

  int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
  int y_big_incr = triangle_pixel_size_ * input_->width,
      x_big_incr = y_big_incr + triangle_pixel_size_;
  // Reserve enough space
  polygons.resize (input_->width * input_->height);

  // Go over the rows first
  for (int y = 0; y < last_row; y += triangle_pixel_size_)
  {
    // Initialize a new row
    i = y * input_->width;
    index_right = i + triangle_pixel_size_;
    index_down = i + y_big_incr;
    index_down_right = i + x_big_incr;

    // Go over the columns
    for (int x = 0; x < last_column; x += triangle_pixel_size_,
                                     i += triangle_pixel_size_,
                                     index_right += triangle_pixel_size_,
                                     index_down += triangle_pixel_size_,
                                     index_down_right += triangle_pixel_size_)
    {
      if (isValidQuad (i, index_down, index_right, index_down_right))
        if (store_shadowed_faces_ || !isShadowedQuad (i, index_right, index_down_right, index_down))
          addQuad (i, index_down, index_right, index_down_right, idx++, polygons);
    }
  }
  polygons.resize (idx);
}

/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeRightCutMesh (std::vector<pcl::Vertices>& polygons)
{
  int last_column = input_->width - triangle_pixel_size_;
  int last_row = input_->height - triangle_pixel_size_;

  int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
  int y_big_incr = triangle_pixel_size_ * input_->width,
      x_big_incr = y_big_incr + triangle_pixel_size_;
  // Reserve enough space
  polygons.resize (input_->width * input_->height * 2);

  // Go over the rows first
  for (int y = 0; y < last_row; y += triangle_pixel_size_)
  {
    // Initialize a new row
    i = y * input_->width;
    index_right = i + triangle_pixel_size_;
    index_down = i + y_big_incr;
    index_down_right = i + x_big_incr;

    // Go over the columns
    for (int x = 0; x < last_column; x += triangle_pixel_size_,
                                     i += triangle_pixel_size_,
                                     index_right += triangle_pixel_size_,
                                     index_down += triangle_pixel_size_,
                                     index_down_right += triangle_pixel_size_)
    {
      if (isValidTriangle (i, index_down_right, index_right))
        if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down_right, index_right))
          addTriangle (i, index_down_right, index_right, idx++, polygons);

      if (isValidTriangle (i, index_down, index_down_right))
        if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_down_right))
          addTriangle (i, index_down, index_down_right, idx++, polygons);
    }
  }
  polygons.resize (idx);
}

/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeLeftCutMesh (std::vector<pcl::Vertices>& polygons)
{
  int last_column = input_->width - triangle_pixel_size_;
  int last_row = input_->height - triangle_pixel_size_;

  int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
  int y_big_incr = triangle_pixel_size_ * input_->width,
      x_big_incr = y_big_incr + triangle_pixel_size_;
  // Reserve enough space
  polygons.resize (input_->width * input_->height * 2);

  // Go over the rows first
  for (int y = 0; y < last_row; y += triangle_pixel_size_)
  {
    // Initialize a new row
    i = y * input_->width;
    index_right = i + triangle_pixel_size_;
    index_down = i + y_big_incr;
    index_down_right = i + x_big_incr;

    // Go over the columns
    for (int x = 0; x < last_column; x += triangle_pixel_size_,
                                     i += triangle_pixel_size_,
                                     index_right += triangle_pixel_size_,
                                     index_down += triangle_pixel_size_,
                                     index_down_right += triangle_pixel_size_)
    {
      if (isValidTriangle (i, index_down, index_right))
        if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_right))
          addTriangle (i, index_down, index_right, idx++, polygons);

      if (isValidTriangle (index_right, index_down, index_down_right))
        if (store_shadowed_faces_ || !isShadowedTriangle (index_right, index_down, index_down_right))
          addTriangle (index_right, index_down, index_down_right, idx++, polygons);
    }
  }
  polygons.resize (idx);
}

/////////////////////////////////////////////////////////////////////////////////////////////
template <typename PointInT> void
pcl::OrganizedFastMesh<PointInT>::makeAdaptiveCutMesh (std::vector<pcl::Vertices>& polygons)
{
  int last_column = input_->width - triangle_pixel_size_;
  int last_row = input_->height - triangle_pixel_size_;

  int i = 0, index_down = 0, index_right = 0, index_down_right = 0, idx = 0;
  int y_big_incr = triangle_pixel_size_ * input_->width,
      x_big_incr = y_big_incr + triangle_pixel_size_;
  // Reserve enough space
  polygons.resize (input_->width * input_->height * 4);

  // Go over the rows first
  for (int y = 0; y < last_row; y += triangle_pixel_size_)
  {
    // Initialize a new row
    i = y * input_->width;
    index_right = i + triangle_pixel_size_;
    index_down = i + y_big_incr;
    index_down_right = i + x_big_incr;

    // Go over the columns
    for (int x = 0; x < last_column; x += triangle_pixel_size_,
                                     i += triangle_pixel_size_,
                                     index_right += triangle_pixel_size_,
                                     index_down += triangle_pixel_size_,
                                     index_down_right += triangle_pixel_size_)
    {
      const bool right_cut_upper = isValidTriangle (i, index_down_right, index_right);
      const bool right_cut_lower = isValidTriangle (i, index_down, index_down_right);
      const bool left_cut_upper = isValidTriangle (i, index_down, index_right);
      const bool left_cut_lower = isValidTriangle (index_right, index_down, index_down_right);

      if (right_cut_upper && right_cut_lower && left_cut_upper && left_cut_lower)
      {
        float dist_right_cut = fabs (input_->points[index_down].z - input_->points[index_right].z);
        float dist_left_cut = fabs (input_->points[i].z - input_->points[index_down_right].z);
        if (dist_right_cut >= dist_left_cut)
        {
          if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down_right, index_right))
            addTriangle (i, index_down_right, index_right, idx++, polygons);
          if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_down_right))
            addTriangle (i, index_down, index_down_right, idx++, polygons);
        }
        else
        {
          if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_right))
            addTriangle (i, index_down, index_right, idx++, polygons);
          if (store_shadowed_faces_ || !isShadowedTriangle (index_right, index_down, index_down_right))
            addTriangle (index_right, index_down, index_down_right, idx++, polygons);
        }
      }
      else
      {
        if (right_cut_upper)
          if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down_right, index_right))
            addTriangle (i, index_down_right, index_right, idx++, polygons);
        if (right_cut_lower)
          if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_down_right))
            addTriangle (i, index_down, index_down_right, idx++, polygons);
        if (left_cut_upper)
          if (store_shadowed_faces_ || !isShadowedTriangle (i, index_down, index_right))
            addTriangle (i, index_down, index_right, idx++, polygons);
        if (left_cut_lower)
          if (store_shadowed_faces_ || !isShadowedTriangle (index_right, index_down, index_down_right))
            addTriangle (index_right, index_down, index_down_right, idx++, polygons);
      }
    }
  }
  polygons.resize (idx);
}

#define PCL_INSTANTIATE_OrganizedFastMesh(T)                \
  template class PCL_EXPORTS pcl::OrganizedFastMesh<T>;

#endif  // PCL_SURFACE_ORGANIZED_FAST_MESH_HPP_
<|endoftext|>


<commit_before>aa57b145-2747-11e6-b08d-e0f84713e7b8<commit_msg>Tuesday, turns out it was tuesday<commit_after>aa6a356e-2747-11e6-8217-e0f84713e7b8<|endoftext|>


<commit_before>9afffbf5-2747-11e6-96f8-e0f84713e7b8<commit_msg>Fix that bug where things didn't work but now they should<commit_after>9b10193a-2747-11e6-8c9b-e0f84713e7b8<|endoftext|>


<commit_before>8b4a9c68-4b02-11e5-bf16-28cfe9171a43<commit_msg>Does anyone even read these anymore???<commit_after>8b57d247-4b02-11e5-b452-28cfe9171a43<|endoftext|>


<commit_before>7428c7cf-ad5c-11e7-9161-ac87a332f658<commit_msg>Initial commit.2<commit_after>749c1fc7-ad5c-11e7-8bc3-ac87a332f658<|endoftext|>


<commit_before>#include <vexcl/devlist.hpp>
#include <vexcl/spmat.hpp>
#include <vexcl/vector.hpp>

#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DynamicVector.h>
#include <blaze/math/DenseSubvector.h>

#include <blaze/util/serialization/Archive.h>
#include <blaze/math/serialization/MatrixSerializer.h>
#include <blaze/math/serialization/VectorSerializer.h>

#include <vector>
#include <sstream>
#include <string>
#include <iostream>

void ConvertSpMat(std::vector<size_t>& row, std::vector<size_t>& col, std::vector<double>& val, blaze::CompressedMatrix<double>& mat) {
	uint non_zeros = mat.nonZeros();
	row.clear();
	col.clear();
	val.clear();
	uint count = 0;
	for (int i = 0; i < mat.rows(); ++i) {
		row.push_back(count);
		for (blaze::CompressedMatrix<double>::Iterator it = mat.begin(i); it != mat.end(i); ++it) {
			col.push_back(it->index());
			val.push_back(it->value());
			count++;
		}
	}
	row.push_back(count);
}

std::string slurp(std::string fname){
	std::ifstream file(fname.c_str());
	std::string buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
	return buffer;
}

void readSPMAT(std::string & data, blaze::CompressedMatrix<double> & mat){
	std::stringstream ss(data);

	uint rows, cols, nonzeros;
	ss>>rows>>cols>>nonzeros;
	//printf("INFO: rows: %d, columns: %d, non zeros: %d\n",rows, cols, nonzeros);
	mat.resize(rows,cols);
	mat.reserve(nonzeros);
	uint row_nonzeros;
	uint colval;
	double v;

	for(int i=0; i<rows; i++){
		if(i%1000000==0){printf("%d, ",i);}

		ss>>row_nonzeros;

		for(int j=0; j<row_nonzeros; j++){
			ss>>colval>>v;
			mat.append(i,colval,v);
		}
		mat.finalize(i);
	}
	printf("\n");
}
void readVector(std::string & data, std::vector<double> & vec){
	std::stringstream ss(data);

	uint size;
	ss>>size;
	vec.resize(size);

	//printf("INFO: size: %d\n",size);
	double v;
	for(int i=0; i<size; i++){
		ss>>v;
		vec[i] = v;
	}
}
int main(){
	printf("start execution \n");
	vex::Context ctx(vex::Filter::Env && vex::Filter::DoublePrecision);
	std::cout<<ctx<<std::endl;
	printf("create context \n");

	blaze::CompressedMatrix<double> D_T, M_invD;
	std::vector<double> g,b;
	printf("read D^T \n");
	{
		std::string data = slurp("D_T.mat");
		readSPMAT(data, D_T);
	}

	{
		std::string data = slurp("M_invD.mat");
		readSPMAT(data, M_invD);
	}
	{
		std::string data = slurp("gamma.vec");
		readVector(data, g);
	}

	{
		std::string data = slurp("b.vec");
		readVector(data, b);
	}

	printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T.rows(), D_T.columns(), D_T.nonZeros());
	printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD.rows(), M_invD.columns(), M_invD.nonZeros());
	printf("gamma: size: %d\n", g.size());
	printf("b: size: %d\n", b.size());

	std::vector<size_t> row;
	std::vector<size_t> col;
	std::vector<double> val;

	ConvertSpMat(row, col, val, D_T);
	vex::SpMat<double> _D_T(ctx, D_T.rows(), D_T.columns(), row.data(), col.data(), val.data());

	ConvertSpMat(row, col, val, M_invD);
	vex::SpMat<double> _M_invD(ctx, M_invD.rows(), M_invD.columns(), row.data(), col.data(), val.data());

	blaze::DynamicVector<double> gamma(g.size()),rhs(g.size());

	for(int i=0; i<g.size(); i++){
		gamma[i] = g[i];
		rhs[i] = b[i];
	}
	blaze::DynamicVector<double> res_cpu(g.size());
	double start_cpu = omp_get_wtime();
	res_cpu = M_invD*gamma;
	res_cpu = D_T*res_cpu;
	double end_cpu = omp_get_wtime();

	vex::profiler<> prof;

	vex::vector<double> gamma_gpu(ctx,g.size());
	vex::vector<double> b_gpu(ctx,b.size());
	vex::copy(g,gamma_gpu);
	vex::copy(b,b_gpu);
	vex::vector<double> tmp_gpu(ctx,g.size());
	vex::vector<double> res_gpu(ctx,g.size());
	prof.tic_cpu("GPU");
	double start_gpu = omp_get_wtime();
	tmp_gpu  = _M_invD*gamma_gpu;
	res_gpu  = _D_T*tmp_gpu;
	double end_gpu = omp_get_wtime();
	double tot_time = prof.toc("GPU");
	printf("CPU took %f sec. time.\n", end_cpu-start_cpu);
	printf("GPU took %f sec. time, %f sec time.\n", end_gpu-start_gpu, tot_time);
	printf("Speedup: %f\n", (end_cpu-start_cpu) /(end_gpu-start_gpu));

	//std::vector<double> res_host(g.size());

	//vex::copy(res_gpu,res_host);

	//printf("copy\n");
	// for(int i=0; i<g.size(); i++){
	// 	if(res_host[i]!=res_cpu[i]){
	// 		printf("%f\n",res_host[i]-res_cpu[i]);
	// 	}
	// }

	return 0;
}<commit_msg>do more runs and average time<commit_after>#include <vexcl/devlist.hpp>
#include <vexcl/spmat.hpp>
#include <vexcl/vector.hpp>

#include <blaze/math/CompressedMatrix.h>
#include <blaze/math/DynamicVector.h>
#include <blaze/math/DenseSubvector.h>

#include <blaze/util/serialization/Archive.h>
#include <blaze/math/serialization/MatrixSerializer.h>
#include <blaze/math/serialization/VectorSerializer.h>

#include <vector>
#include <sstream>
#include <string>
#include <iostream>

void ConvertSpMat(std::vector<size_t>& row, std::vector<size_t>& col, std::vector<double>& val, blaze::CompressedMatrix<double>& mat) {
	uint non_zeros = mat.nonZeros();
	row.clear();
	col.clear();
	val.clear();
	uint count = 0;
	for (int i = 0; i < mat.rows(); ++i) {
		row.push_back(count);
		for (blaze::CompressedMatrix<double>::Iterator it = mat.begin(i); it != mat.end(i); ++it) {
			col.push_back(it->index());
			val.push_back(it->value());
			count++;
		}
	}
	row.push_back(count);
}

std::string slurp(std::string fname){
	std::ifstream file(fname.c_str());
	std::string buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>());
	return buffer;
}

void readSPMAT(std::string & data, blaze::CompressedMatrix<double> & mat){
	std::stringstream ss(data);

	uint rows, cols, nonzeros;
	ss>>rows>>cols>>nonzeros;
	//printf("INFO: rows: %d, columns: %d, non zeros: %d\n",rows, cols, nonzeros);
	mat.resize(rows,cols);
	mat.reserve(nonzeros);
	uint row_nonzeros;
	uint colval;
	double v;

	for(int i=0; i<rows; i++){
		if(i%1000000==0){printf("%d, ",i);}

		ss>>row_nonzeros;

		for(int j=0; j<row_nonzeros; j++){
			ss>>colval>>v;
			mat.append(i,colval,v);
		}
		mat.finalize(i);
	}
	printf("\n");
}
void readVector(std::string & data, std::vector<double> & vec){
	std::stringstream ss(data);

	uint size;
	ss>>size;
	vec.resize(size);

	//printf("INFO: size: %d\n",size);
	double v;
	for(int i=0; i<size; i++){
		ss>>v;
		vec[i] = v;
	}
}
int main(){
	printf("start execution \n");
	vex::Context ctx(vex::Filter::Env && vex::Filter::DoublePrecision);
	std::cout<<ctx<<std::endl;
	printf("create context \n");

	blaze::CompressedMatrix<double> D_T, M_invD;
	std::vector<double> g,b;
	printf("read D^T \n");
	{
		std::string data = slurp("D_T.mat");
		readSPMAT(data, D_T);
	}

	{
		std::string data = slurp("M_invD.mat");
		readSPMAT(data, M_invD);
	}
	{
		std::string data = slurp("gamma.vec");
		readVector(data, g);
	}

	{
		std::string data = slurp("b.vec");
		readVector(data, b);
	}

	printf("D_T: rows: %d, columns: %d, non zeros: %d\n", D_T.rows(), D_T.columns(), D_T.nonZeros());
	printf("M_invD: rows: %d, columns: %d, non zeros: %d\n", M_invD.rows(), M_invD.columns(), M_invD.nonZeros());
	printf("gamma: size: %d\n", g.size());
	printf("b: size: %d\n", b.size());

	std::vector<size_t> row;
	std::vector<size_t> col;
	std::vector<double> val;

	ConvertSpMat(row, col, val, D_T);
	vex::SpMat<double> _D_T(ctx, D_T.rows(), D_T.columns(), row.data(), col.data(), val.data());

	ConvertSpMat(row, col, val, M_invD);
	vex::SpMat<double> _M_invD(ctx, M_invD.rows(), M_invD.columns(), row.data(), col.data(), val.data());

	blaze::DynamicVector<double> gamma(g.size()),rhs(g.size());

	for(int i=0; i<g.size(); i++){
		gamma[i] = g[i];
		rhs[i] = b[i];
	}
	blaze::DynamicVector<double> tmp_cpu(g.size());
	blaze::DynamicVector<double> res_cpu(g.size());
	double start_cpu = omp_get_wtime();
	for(size_t i = 0; i < 100; i++){
		tmp_cpu = M_invD*gamma;
		res_cpu += D_T*tmp_cpu;
	}
	double end_cpu = omp_get_wtime();

	vex::profiler<> prof;

	vex::vector<double> gamma_gpu(ctx,g.size());
	vex::vector<double> b_gpu(ctx,b.size());
	vex::copy(g,gamma_gpu);
	vex::copy(b,b_gpu);
	vex::vector<double> tmp_gpu(ctx,g.size());
	vex::vector<double> res_gpu(ctx,g.size());

	tmp_gpu += _M_invD*gamma_gpu;
	tmp_gpu = 0;
	res_gpu += _D_T*tmp_gpu;
	res_gpu = 0;
	prof.tic_cpu("GPU");
	double start_gpu = omp_get_wtime();
	for(size_t i = 0; i < 100; i++){
		tmp_gpu  = _M_invD*gamma_gpu;
		res_gpu  += _D_T*tmp_gpu;
	}
	ctx.finish();
	double end_gpu = omp_get_wtime();
	double tot_time = prof.toc("GPU");
	printf("CPU took %f sec. time.\n", (end_cpu-start_cpu)/100.0);
	printf("GPU took %f sec. time, %f sec time.\n", (end_gpu-start_gpu)/100.0, tot_time/100.0);
	printf("Speedup: %f\n", (end_cpu-start_cpu) /(end_gpu-start_gpu));

	//std::vector<double> res_host(g.size());

	//vex::copy(res_gpu,res_host);

	//printf("copy\n");
	// for(int i=0; i<g.size(); i++){
	// 	if(res_host[i]!=res_cpu[i]){
	// 		printf("%f\n",res_host[i]-res_cpu[i]);
	// 	}
	// }

	return 0;
}<|endoftext|>


<commit_before><commit_msg>Prediction: update pytorch API to latest to mute warning (#9566)<commit_after><|endoftext|>