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

using namespace fapi2;

constexpr uint64_t literal_0x0B = 0x0B;
constexpr uint64_t literal_0x0 = 0x0;
constexpr uint64_t literal_0xF = 0xF;
constexpr uint64_t literal_0b0000000 = 0b0000000;

fapi2::ReturnCode p9_fbc_ioo_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& TGT0,
                                     const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec));
        fapi2::ATTR_OPTICS_CONFIG_MODE_Type l_TGT0_ATTR_OPTICS_CONFIG_MODE;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_OPTICS_CONFIG_MODE, TGT0, l_TGT0_ATTR_OPTICS_CONFIG_MODE));
        uint64_t l_def_OBUS_NV_ENABLED = (l_TGT0_ATTR_OPTICS_CONFIG_MODE == fapi2::ENUM_ATTR_OPTICS_CONFIG_MODE_NV);
        uint64_t l_def_OBUS_FBC_ENABLED = (l_TGT0_ATTR_OPTICS_CONFIG_MODE == fapi2::ENUM_ATTR_OPTICS_CONFIG_MODE_SMP);
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x901080aull, l_scom_buffer ));

            constexpr auto l_PB_IOO_LL0_CONFIG_LINK_PAIR_ON = 0x1;
            l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK_PAIR_ON );

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                l_scom_buffer.insert<12, 4, 60, uint64_t>(literal_0x0B );
            }
            else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21))
                     || ((l_chip_id == 0x5) && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) )
            {
                l_scom_buffer.insert<11, 5, 59, uint64_t>(literal_0x0B );
            }

            l_scom_buffer.insert<28, 4, 60, uint64_t>(literal_0x0 );

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) )
            {
                l_scom_buffer.insert<32, 4, 60, uint64_t>(literal_0x0 );
            }

            constexpr auto l_PB_IOO_LL0_CONFIG_CRC_LANE_ID_ON = 0x1;
            l_scom_buffer.insert<2, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_CRC_LANE_ID_ON );
            constexpr auto l_PB_IOO_LL0_CONFIG_SL_UE_CRC_ERR_ON = 0x1;
            l_scom_buffer.insert<4, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_SL_UE_CRC_ERR_ON );
            FAPI_TRY(fapi2::putScom(TGT0, 0x901080aull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x901080cull, l_scom_buffer ));

            if (l_def_OBUS_NV_ENABLED)
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_NV0_NPU_ENABLED_ON = 0x1;
                l_scom_buffer.insert<61, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV0_NPU_ENABLED_ON );
                constexpr auto l_PB_IOO_LL0_CONFIG_NV1_NPU_ENABLED_ON = 0x1;
                l_scom_buffer.insert<62, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV1_NPU_ENABLED_ON );
                constexpr auto l_PB_IOO_LL0_CONFIG_NV2_NPU_ENABLED_ON = 0x1;
                l_scom_buffer.insert<63, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV2_NPU_ENABLED_ON );
            }

            if (l_def_OBUS_FBC_ENABLED)
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_LINK0_OLL_ENABLED_ON = 0x1;
                l_scom_buffer.insert<58, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK0_OLL_ENABLED_ON );
                constexpr auto l_PB_IOO_LL0_CONFIG_LINK1_OLL_ENABLED_ON = 0x1;
                l_scom_buffer.insert<59, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK1_OLL_ENABLED_ON );
            }

            l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0xF );
            FAPI_TRY(fapi2::putScom(TGT0, 0x901080cull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x901080full, l_scom_buffer ));

            if (l_def_OBUS_NV_ENABLED)
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_NV0_NPU_ENABLED_ON = 0x1;
                l_scom_buffer.insert<61, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV0_NPU_ENABLED_ON );
                constexpr auto l_PB_IOO_LL0_CONFIG_NV1_NPU_ENABLED_ON = 0x1;
                l_scom_buffer.insert<62, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV1_NPU_ENABLED_ON );
                constexpr auto l_PB_IOO_LL0_CONFIG_NV2_NPU_ENABLED_ON = 0x1;
                l_scom_buffer.insert<63, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV2_NPU_ENABLED_ON );
            }

            if (l_def_OBUS_FBC_ENABLED)
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_LINK0_OLL_ENABLED_ON = 0x1;
                l_scom_buffer.insert<58, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK0_OLL_ENABLED_ON );
                constexpr auto l_PB_IOO_LL0_CONFIG_LINK1_OLL_ENABLED_ON = 0x1;
                l_scom_buffer.insert<59, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK1_OLL_ENABLED_ON );
            }

            l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0x0 );
            l_scom_buffer.insert<9, 7, 57, uint64_t>(literal_0b0000000 );
            constexpr auto l_PB_IOO_LL0_CONFIG_ELEVEN_LANE_MODE_ON = 0x1;
            l_scom_buffer.insert<37, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_ELEVEN_LANE_MODE_ON );

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) )
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_FAST_ASYNC_CROSS_ON = 0x1;
                l_scom_buffer.insert<59, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_FAST_ASYNC_CROSS_ON );
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) )
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_LINK_FAIL_CRC_ERROR_ON = 0x1;
                l_scom_buffer.insert<3, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK_FAIL_CRC_ERROR_ON );
            }

            l_scom_buffer.insert<20, 4, 60, uint64_t>(literal_0x0 );
            l_scom_buffer.insert<25, 7, 57, uint64_t>(literal_0b0000000 );

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) )
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_LINK_FAIL_NO_SPARE_ON = 0x1;
                l_scom_buffer.insert<2, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK_FAIL_NO_SPARE_ON );
            }

            constexpr auto l_PB_IOO_LL0_CONFIG_REPLAY_BUFFER_SIZE_REPLAY_255 = 0x2;
            l_scom_buffer.insert<56, 2, 62, uint64_t>(l_PB_IOO_LL0_CONFIG_REPLAY_BUFFER_SIZE_REPLAY_255 );
            constexpr auto l_PB_IOO_LL0_LINK1_ELEVEN_LANE_SHIFT_ON = 0x1;
            l_scom_buffer.insert<39, 1, 63, uint64_t>(l_PB_IOO_LL0_LINK1_ELEVEN_LANE_SHIFT_ON );

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) )
            {
                constexpr auto l_PB_IOO_LL0_LINK1_RX_LANE_SWAP_ON = 0x1;
                l_scom_buffer.insert<42, 1, 63, uint64_t>(l_PB_IOO_LL0_LINK1_RX_LANE_SWAP_ON );
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) )
            {
                constexpr auto l_PB_IOO_LL0_LINK1_TX_LANE_SWAP_ON = 0x1;
                l_scom_buffer.insert<43, 1, 63, uint64_t>(l_PB_IOO_LL0_LINK1_TX_LANE_SWAP_ON );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x901080full, l_scom_buffer));
        }

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

using namespace fapi2;

constexpr uint64_t literal_0x0B = 0x0B;
constexpr uint64_t literal_0x0 = 0x0;
constexpr uint64_t literal_0xF = 0xF;
constexpr uint64_t literal_0b0000000 = 0b0000000;

fapi2::ReturnCode p9_fbc_ioo_dl_scom(const fapi2::Target<fapi2::TARGET_TYPE_OBUS>& TGT0,
                                     const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& TGT1)
{
    {
        fapi2::ATTR_EC_Type   l_chip_ec;
        fapi2::ATTR_NAME_Type l_chip_id;
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_NAME, TGT1, l_chip_id));
        FAPI_TRY(FAPI_ATTR_GET_PRIVILEGED(fapi2::ATTR_EC, TGT1, l_chip_ec));
        fapi2::ATTR_OPTICS_CONFIG_MODE_Type l_TGT0_ATTR_OPTICS_CONFIG_MODE;
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_OPTICS_CONFIG_MODE, TGT0, l_TGT0_ATTR_OPTICS_CONFIG_MODE));
        uint64_t l_def_OBUS_NV_ENABLED = (l_TGT0_ATTR_OPTICS_CONFIG_MODE == fapi2::ENUM_ATTR_OPTICS_CONFIG_MODE_NV);
        uint64_t l_def_OBUS_FBC_ENABLED = (l_TGT0_ATTR_OPTICS_CONFIG_MODE == fapi2::ENUM_ATTR_OPTICS_CONFIG_MODE_SMP);
        fapi2::buffer<uint64_t> l_scom_buffer;
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x901080aull, l_scom_buffer ));

            constexpr auto l_PB_IOO_LL0_CONFIG_LINK_PAIR_ON = 0x1;
            l_scom_buffer.insert<0, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK_PAIR_ON );

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x10)) )
            {
                l_scom_buffer.insert<12, 4, 60, uint64_t>(literal_0x0B );
            }
            else if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21))
                     || ((l_chip_id == 0x5) && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x6)
                             && (l_chip_ec == 0x11)) )
            {
                l_scom_buffer.insert<11, 5, 59, uint64_t>(literal_0x0B );
            }

            l_scom_buffer.insert<28, 4, 60, uint64_t>(literal_0x0 );

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) )
            {
                l_scom_buffer.insert<32, 4, 60, uint64_t>(literal_0x0 );
            }

            constexpr auto l_PB_IOO_LL0_CONFIG_CRC_LANE_ID_ON = 0x1;
            l_scom_buffer.insert<2, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_CRC_LANE_ID_ON );
            constexpr auto l_PB_IOO_LL0_CONFIG_SL_UE_CRC_ERR_ON = 0x1;
            l_scom_buffer.insert<4, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_SL_UE_CRC_ERR_ON );
            FAPI_TRY(fapi2::putScom(TGT0, 0x901080aull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x901080cull, l_scom_buffer ));

            if (l_def_OBUS_NV_ENABLED)
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_NV0_NPU_ENABLED_ON = 0x1;
                l_scom_buffer.insert<61, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV0_NPU_ENABLED_ON );
                constexpr auto l_PB_IOO_LL0_CONFIG_NV1_NPU_ENABLED_ON = 0x1;
                l_scom_buffer.insert<62, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV1_NPU_ENABLED_ON );
                constexpr auto l_PB_IOO_LL0_CONFIG_NV2_NPU_ENABLED_ON = 0x1;
                l_scom_buffer.insert<63, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV2_NPU_ENABLED_ON );
            }

            if (l_def_OBUS_FBC_ENABLED)
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_LINK0_OLL_ENABLED_ON = 0x1;
                l_scom_buffer.insert<58, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK0_OLL_ENABLED_ON );
                constexpr auto l_PB_IOO_LL0_CONFIG_LINK1_OLL_ENABLED_ON = 0x1;
                l_scom_buffer.insert<59, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK1_OLL_ENABLED_ON );
            }

            l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0xF );
            FAPI_TRY(fapi2::putScom(TGT0, 0x901080cull, l_scom_buffer));
        }
        {
            FAPI_TRY(fapi2::getScom( TGT0, 0x901080full, l_scom_buffer ));

            if (l_def_OBUS_NV_ENABLED)
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_NV0_NPU_ENABLED_ON = 0x1;
                l_scom_buffer.insert<61, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV0_NPU_ENABLED_ON );
                constexpr auto l_PB_IOO_LL0_CONFIG_NV1_NPU_ENABLED_ON = 0x1;
                l_scom_buffer.insert<62, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV1_NPU_ENABLED_ON );
                constexpr auto l_PB_IOO_LL0_CONFIG_NV2_NPU_ENABLED_ON = 0x1;
                l_scom_buffer.insert<63, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_NV2_NPU_ENABLED_ON );
            }

            if (l_def_OBUS_FBC_ENABLED)
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_LINK0_OLL_ENABLED_ON = 0x1;
                l_scom_buffer.insert<58, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK0_OLL_ENABLED_ON );
                constexpr auto l_PB_IOO_LL0_CONFIG_LINK1_OLL_ENABLED_ON = 0x1;
                l_scom_buffer.insert<59, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK1_OLL_ENABLED_ON );
            }

            l_scom_buffer.insert<4, 4, 60, uint64_t>(literal_0x0 );
            l_scom_buffer.insert<9, 7, 57, uint64_t>(literal_0b0000000 );
            constexpr auto l_PB_IOO_LL0_CONFIG_ELEVEN_LANE_MODE_ON = 0x1;
            l_scom_buffer.insert<37, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_ELEVEN_LANE_MODE_ON );

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) )
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_FAST_ASYNC_CROSS_ON = 0x1;
                l_scom_buffer.insert<59, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_FAST_ASYNC_CROSS_ON );
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) )
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_LINK_FAIL_CRC_ERROR_ON = 0x1;
                l_scom_buffer.insert<3, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK_FAIL_CRC_ERROR_ON );
            }

            l_scom_buffer.insert<20, 4, 60, uint64_t>(literal_0x0 );
            l_scom_buffer.insert<25, 7, 57, uint64_t>(literal_0b0000000 );

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x11)) )
            {
                constexpr auto l_PB_IOO_LL0_CONFIG_LINK_FAIL_NO_SPARE_ON = 0x1;
                l_scom_buffer.insert<2, 1, 63, uint64_t>(l_PB_IOO_LL0_CONFIG_LINK_FAIL_NO_SPARE_ON );
            }

            constexpr auto l_PB_IOO_LL0_CONFIG_REPLAY_BUFFER_SIZE_REPLAY_255 = 0x2;
            l_scom_buffer.insert<56, 2, 62, uint64_t>(l_PB_IOO_LL0_CONFIG_REPLAY_BUFFER_SIZE_REPLAY_255 );
            constexpr auto l_PB_IOO_LL0_LINK1_ELEVEN_LANE_SHIFT_ON = 0x1;
            l_scom_buffer.insert<39, 1, 63, uint64_t>(l_PB_IOO_LL0_LINK1_ELEVEN_LANE_SHIFT_ON );

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) )
            {
                constexpr auto l_PB_IOO_LL0_LINK1_RX_LANE_SWAP_ON = 0x1;
                l_scom_buffer.insert<42, 1, 63, uint64_t>(l_PB_IOO_LL0_LINK1_RX_LANE_SWAP_ON );
            }

            if (((l_chip_id == 0x5) && (l_chip_ec == 0x20)) || ((l_chip_id == 0x5) && (l_chip_ec == 0x21)) || ((l_chip_id == 0x5)
                    && (l_chip_ec == 0x22)) || ((l_chip_id == 0x6) && (l_chip_ec == 0x10)) )
            {
                constexpr auto l_PB_IOO_LL0_LINK1_TX_LANE_SWAP_ON = 0x1;
                l_scom_buffer.insert<43, 1, 63, uint64_t>(l_PB_IOO_LL0_LINK1_TX_LANE_SWAP_ON );
            }

            FAPI_TRY(fapi2::putScom(TGT0, 0x901080full, l_scom_buffer));
        }

    };
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/memory/lib/eff_config/timing.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
#include <fapi2.H>
#include <mss.H>
#include <lib/utils/find.H>
#include <lib/eff_config/timing.H>

namespace mss
{

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TREFI_BASE =
{
    // { density in GBs, tREFI(base) in nanoseconds }
    {2, 7800},
    {4, 7800},
    {8, 7800},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC1_MIN =
{
    // { density in GBs, tRFC1(min) in nanoseconds }
    {2, 160},
    {4, 260},
    {8, 350},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC2_MIN =
{
    // { density in GBs, tRFC2(min) in nanoseconds }
    {2, 110},
    {4, 160},
    {8, 260},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC4_MIN =
{
    // { density in GBs, tRFC4(min) in nanoseconds }
    {2, 90},
    {4, 110},
    {8, 160},
    // 16Gb - TBD
};

// Proposed DDR4 3DS Addendum
// Item No. 1727.58A
// pg. 69 - 71
// Table 42 - Refresh parameters by logical rank density
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR1 =
{
    // { density in GBs, tRFC4(min) in nanoseconds }
    {4, 90},
    {8, 120},
    // 16Gb - TBD
};

// Proposed DDR4 3DS Addendum
// Item No. 1727.58A
// pg. 69 - 71
// Table 42 - Refresh parameters by logical rank density
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR2 =
{
    // { density in GBs, tRFC4(min) in nanoseconds }
    {4, 55},
    {8, 90}
    // 16Gb - TBD
};

// Proposed DDR4 3DS Addendum
// Item No. 1727.58A
// pg. 69 - 71
// Table 42 - Refresh parameters by logical rank density
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR4 =
{
    // { density in GBs, tRFC4(min) in nanoseconds }
    {4, 40},
    {8, 55}
    // 16Gb - TBD
};

/// @brief Calculates refresh interval time 1 (tREFI 1)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi1(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                              uint64_t& o_value)
{
    uint8_t  l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_ref_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY( mss::eff_dram_density(i_target, l_dram_density) );
    FAPI_TRY( mss::mrw_temp_ref_range(l_temp_ref_range) );

    switch(l_temp_ref_range)
    {
        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_NORMAL:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "normal temp_ref_range.") );
            break;

        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_EXTEND:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "extended temp_ref_range.") );
            l_quotient = l_output / 2;
            l_remainder = l_output % 2;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // l_temp_ref_range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_ref_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_ref_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Calculates refresh interval time 2 (tREFI 2)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi2(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                              uint64_t& o_value)
{
    uint8_t l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_ref_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY( mss::mrw_temp_ref_range(l_temp_ref_range) );
    FAPI_TRY( mss::eff_dram_density(i_target, l_dram_density) );

    switch(l_temp_ref_range)
    {
        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_NORMAL:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "normal temp_ref_range.") );

            l_remainder = l_output % 2;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_EXTEND:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "extended temp_ref_range.") );
            l_quotient = l_output / 4;
            l_remainder = l_output % 4;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // l_temp_ref_range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_ref_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_ref_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Calculates refresh interval time 4 (tREFI 4)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi4( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                               uint64_t& o_value)
{
    uint8_t l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_ref_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY( mss::mrw_temp_ref_range(l_temp_ref_range) );
    FAPI_TRY( mss::eff_dram_density(i_target, l_dram_density) );

    switch(l_temp_ref_range)
    {
        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_NORMAL:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "normal temp_ref_range.") );
            l_quotient = l_output / 4;
            l_remainder = l_output % 4;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        case fapi2::ENUM_ATTR_MRW_TEMP_REF_RANGE_EXTEND:
            l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_ref_range,
                                                  "Could not find sdram density given"
                                                  "extended temp_ref_range.") );
            l_quotient = l_output / 8;
            l_remainder = l_output % 8;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // l_temp_ref_range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_ref_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_ref_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

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

namespace mss
{

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TREFI_BASE =
{
    // { density in GBs, tREFI(base) in picoseconds }
    {2, 7800000},
    {4, 7800000},
    {8, 7800000},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC1_MIN =
{
    // { density in GBs, tRFC1(min) in picoseconds }
    {2, 160000},
    {4, 260000},
    {8, 350000},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC2_MIN =
{
    // { density in GBs, tRFC2(min) in picoseconds }
    {2, 110000},
    {4, 160000},
    {8, 260000},
    // 16Gb - TBD
};

// Proposed DDR4 Full spec update(79-4A)
// Item No. 1716.78C
// pg.46
// Table 24 - tREFI and tRFC parameters
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC4_MIN =
{
    // { density in GBs, tRFC4(min) in picoseconds }
    {2, 90000},
    {4, 110000},
    {8, 160000},
    // 16Gb - TBD
};

// Proposed DDR4 3DS Addendum
// Item No. 1727.58A
// pg. 69 - 71
// Table 42 - Refresh parameters by logical rank density
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR1 =
{
    // { density in GBs, tRFC4(min) in picoseconds }
    {4, 90000},
    {8, 120000},
    // 16Gb - TBD
};

// Proposed DDR4 3DS Addendum
// Item No. 1727.58A
// pg. 69 - 71
// Table 42 - Refresh parameters by logical rank density
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR2 =
{
    // { density in GBs, tRFC4(min) in picoseconds }
    {4, 55000},
    {8, 90000}
    // 16Gb - TBD
};

// Proposed DDR4 3DS Addendum
// Item No. 1727.58A
// pg. 69 - 71
// Table 42 - Refresh parameters by logical rank density
static const std::vector<std::pair<uint8_t, uint64_t> > TRFC_DLR4 =
{
    // { density in GBs, tRFC4(min) in picoseconds }
    {4, 40000},
    {8, 55000}
    // 16Gb - TBD
};

/// @brief Calculates refresh interval time 1 (tREFI 1)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi1(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                              uint64_t& o_value)
{
    uint8_t  l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_refresh_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY( mss::eff_dram_density(i_target, l_dram_density) );
    FAPI_TRY( mss::mrw_temp_refresh_range(l_temp_refresh_range) );

    l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);

    switch(l_temp_refresh_range)
    {
        case fapi2::ENUM_ATTR_MRW_TEMP_REFRESH_RANGE_NORMAL:
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_refresh_range,
                                                  "Could not find sdram density given "
                                                  "normal temp_refresh_range.") );
            break;

        case fapi2::ENUM_ATTR_MRW_TEMP_REFRESH_RANGE_EXTEND:
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_refresh_range,
                                                  "Could not find sdram density given "
                                                  "extended temp_refresh_range.") );
            l_quotient = l_output / 2;
            l_remainder = l_output % 2;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // Temperature Refresh Range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_refresh_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_refresh_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Calculates refresh interval time 2 (tREFI 2)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi2(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                              uint64_t& o_value)
{
    uint8_t l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_refresh_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY( mss::mrw_temp_refresh_range(l_temp_refresh_range) );
    FAPI_TRY( mss::eff_dram_density(i_target, l_dram_density) );

    l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);

    switch(l_temp_refresh_range)
    {
        case fapi2::ENUM_ATTR_MRW_TEMP_REFRESH_RANGE_NORMAL:
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_refresh_range,
                                                  "Could not find sdram density given "
                                                  "normal temp_refresh_range.") );

            l_remainder = l_output % 2;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        case fapi2::ENUM_ATTR_MRW_TEMP_REFRESH_RANGE_EXTEND:
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_refresh_range,
                                                  "Could not find sdram density given "
                                                  "extended temp_refresh_range.") );
            l_quotient = l_output / 4;
            l_remainder = l_output % 4;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // Temperature Refresh Range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_refresh_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_refresh_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

/// @brief Calculates refresh interval time 4 (tREFI 4)
/// @param[in] i_target FAPI2 target
/// @param[out] o_value timing val in ps
/// @return fapi2::ReturnCode
///
fapi2::ReturnCode calc_trefi4( const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                               uint64_t& o_value)
{
    uint8_t l_quotient = 0;
    uint8_t l_remainder = 0;
    uint64_t l_output = 0;
    uint8_t l_temp_refresh_range = 0;
    uint8_t l_dram_density = 0;
    bool l_found_value = true;

    FAPI_TRY( mss::mrw_temp_refresh_range(l_temp_refresh_range) );
    FAPI_TRY( mss::eff_dram_density(i_target, l_dram_density) );

    l_found_value = mss::find_value_from_key(TREFI_BASE, l_dram_density, l_output);

    switch(l_temp_refresh_range)
    {
        case fapi2::ENUM_ATTR_MRW_TEMP_REFRESH_RANGE_NORMAL:
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_refresh_range,
                                                  "Could not find sdram density given "
                                                  "normal temp_refresh_range.") );
            l_quotient = l_output / 4;
            l_remainder = l_output % 4;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        case fapi2::ENUM_ATTR_MRW_TEMP_REFRESH_RANGE_EXTEND:
            FAPI_TRY( check::fail_for_invalid_map(i_target,
                                                  l_found_value,
                                                  l_dram_density,
                                                  l_temp_refresh_range,
                                                  "Could not find sdram density given "
                                                  "extended temp_refresh_range.") );
            l_quotient = l_output / 8;
            l_remainder = l_output % 8;
            o_value = l_quotient + (l_remainder == 0 ? 0 : 1);
            break;

        default:
            // Temperature Refresh Range will be a platform attribute set by the MRW,
            // which they "shouldn't" mess up as long as use "attribute" enums.
            // if openpower messes this up we can at least catch it
            FAPI_ASSERT(false,
                        fapi2::MSS_INVALID_TEMP_REF_RANGE().
                        set_TEMP_REF_RANGE(l_temp_refresh_range),
                        "%s Incorrect Temperature Ref. Range received: %d ",
                        mss::c_str(i_target),
                        l_temp_refresh_range);

            break;
    }

fapi_try_exit:
    return fapi2::current_err;
}

}// mss
<|endoftext|>


<commit_before>#include "GMCommand.h"
#include "map"

typedef void (*PTRFUN)(GameGrail*, PlayerEntity*, vector<string>&);
map<string, PTRFUN> cmd_mapping;

/*
energy: ýɫ2ʯˮ
*/
void setEnergy(GameGrail* engine, PlayerEntity* player, vector<string>& ss)
{
	player->setGem(atoi(ss[1].c_str()));
	player->setCrystal(stoi(ss[2].c_str()));

	GameInfo game_info;
	Coder::energyNotice(player->getID(), player->getGem(), player->getCrystal(), game_info);
	engine->sendMessage(-1, MSG_GAME, game_info);
}

/*
card: ƣΪӵid
*/
void addCard(GameGrail* engine, PlayerEntity* player, vector<string>& ss)
{
	int howmany;
	vector<int> cards;
	for (int i = 1; i < ss.size(); ++i)
		cards.push_back(atoi(ss[i].c_str()));
	howmany = ss.size() - 1;
	player->addHandCards(howmany, cards);

	GameInfo game_info;
	Coder::handNotice(player->getID(), player->getHandCards(), game_info);
	engine->sendMessage(-1, MSG_GAME, game_info);
}

/*
cross:
*/
void setCross(GameGrail* engine, PlayerEntity* player, vector<string>& ss)
{
	int howmany = atoi(ss[1].c_str());
	player->addCrossNum(howmany-player->getCrossNum(), -2);   // 1000

	GameInfo game_info;
	Coder::crossNotice(player->getID(), player->getCrossNum(), game_info);
	engine->sendMessage(-1, MSG_GAME, game_info);
}

/*
¼gmָgmָcmd_mappingУkeyΪgmָʽַvalueǴָ
*/
void initialize_gm_command()
{
	cmd_mapping["!`energy"] = setEnergy;  //
	cmd_mapping["!`card"] = addCard;      //
	cmd_mapping["!`cross"] = setCross;    //
}

/*
ַָи
*/
void split(const string& src, const string& separator, vector<string>& dest)
{
    string str = src;
    string substring;
    string::size_type start = 0, index;

    do
    {
        index = str.find_first_of(separator,start);
        if (index != string::npos)
        {
            substring = str.substr(start,index-start);
            dest.push_back(substring);
            start = str.find_first_not_of(separator,index);
            if (start == string::npos) return;
        }
    }while(index != string::npos);

    //the last token
    substring = str.substr(start);
    dest.push_back(substring);
}

void gm_cmd(GameGrail* engine, PlayerEntity* player, string cmd)
{
	vector<string> ss;
	split(cmd, " ", ss);
	// ָöӦgmûжӦֱָ
	if (cmd_mapping.find(ss[0]) == cmd_mapping.end())
	{
		return;
	}
	PTRFUN func = cmd_mapping[ss[0]];
	func(engine, player, ss);
}
<commit_msg>添加盖牌gm指令（!`covercard num）<commit_after>#include "GMCommand.h"
#include "map"

typedef void (*PTRFUN)(GameGrail*, PlayerEntity*, vector<string>&);
map<string, PTRFUN> cmd_mapping;

/*
energy: ýɫ2ʯˮ
*/
void setEnergy(GameGrail* engine, PlayerEntity* player, vector<string>& ss)
{
	player->setGem(atoi(ss[1].c_str()));
	player->setCrystal(stoi(ss[2].c_str()));

	GameInfo game_info;
	Coder::energyNotice(player->getID(), player->getGem(), player->getCrystal(), game_info);
	engine->sendMessage(-1, MSG_GAME, game_info);
}

/*
card: ƣΪӵid
*/
void addCard(GameGrail* engine, PlayerEntity* player, vector<string>& ss)
{
	int howmany;
	vector<int> cards;
	for (int i = 1; i < ss.size(); ++i)
		cards.push_back(atoi(ss[i].c_str()));
	howmany = ss.size() - 1;
	player->addHandCards(howmany, cards);

	GameInfo game_info;
	Coder::handNotice(player->getID(), player->getHandCards(), game_info);
	engine->sendMessage(-1, MSG_GAME, game_info);
}

/*
card: ӸƣΪӵid
*/
void addCoverCard(GameGrail* engine, PlayerEntity* player, vector<string>& ss)
{
	int howmany;
	vector<int> cards;
	for (int i = 1; i < ss.size(); ++i)
		cards.push_back(atoi(ss[i].c_str()));
	howmany = ss.size() - 1;
	player->addCoverCards(howmany, cards);  //

	GameInfo game_info;
	Coder::coverNotice(player->getID(), player->getCoverCards(), game_info);
	engine->sendMessage(-1, MSG_GAME, game_info);
}

/*
cross:
*/
void setCross(GameGrail* engine, PlayerEntity* player, vector<string>& ss)
{
	int howmany = atoi(ss[1].c_str());
	player->addCrossNum(howmany-player->getCrossNum(), -2);   // 1000

	GameInfo game_info;
	Coder::crossNotice(player->getID(), player->getCrossNum(), game_info);
	engine->sendMessage(-1, MSG_GAME, game_info);
}

/*
¼gmָgmָcmd_mappingУkeyΪgmָʽַvalueǴָ
*/
void initialize_gm_command()
{
	cmd_mapping["!`energy"] = setEnergy;            //
	cmd_mapping["!`card"] = addCard;                //
	cmd_mapping["!`cross"] = setCross;              //
	cmd_mapping["!`covercard"] = addCoverCard;      // Ӹ
}

/*
ַָи
*/
void split(const string& src, const string& separator, vector<string>& dest)
{
    string str = src;
    string substring;
    string::size_type start = 0, index;

    do
    {
        index = str.find_first_of(separator,start);
        if (index != string::npos)
        {
            substring = str.substr(start,index-start);
            dest.push_back(substring);
            start = str.find_first_not_of(separator,index);
            if (start == string::npos) return;
        }
    }while(index != string::npos);

    //the last token
    substring = str.substr(start);
    dest.push_back(substring);
}

void gm_cmd(GameGrail* engine, PlayerEntity* player, string cmd)
{
	vector<string> ss;
	split(cmd, " ", ss);
	// ָöӦgmûжӦֱָ
	if (cmd_mapping.find(ss[0]) == cmd_mapping.end())
	{
		return;
	}
	PTRFUN func = cmd_mapping[ss[0]];
	func(engine, player, ss);
}
<|endoftext|>


<commit_before>#include "Neohuman.h"
#include <iostream>

#include "BWEM/bwem.h"

using namespace BWAPI;
using namespace Filter;

using namespace BWEM;
using namespace BWEM::BWAPI_ext;
using namespace BWEM::utils;

#define MIN(a, b) (((a) < (b) ? (a) : (b)))
#define MAX(a, b) (((a) < (b) ? (b) : (a)))

#define SATRUATION_RADIUS 350
#define WORKERAGGRORADIUS 200

#define SHOWTHINGS

namespace { auto & BWEMMap = Map::Instance(); }

bool Neohuman::doBuild(Unit u, UnitType building, TilePosition at) {
	_buildingQueue.push_back(Triple<int, UnitType, TilePosition>{u->getID(), building, at});
}

std::pair <int, int> Neohuman::getQueuedResources() {
	std::pair <int, int> resources;
	for (auto &o : _buildingQueue)
		resources.first  += o.second.mineralPrice(),
		resources.second += o.second.gasPrice();
	return resources;
}

std::pair <int, int> Neohuman::getSpendableResources() {
	std::pair <int, int> result = { Broodwar->self()->minerals(), Broodwar->self()->gas() };
	auto queued = this->getQueuedResources();
	result.first -= queued.first, result.second -= queued.second;
	return result;
}

void Neohuman::onStart() {
	Broodwar << "The map is totally not " << Broodwar->mapName() << "!" << std::endl;

	//Broodwar->enableFlag(Flag::UserInput);

	// Uncomment the following line and the bot will know about everything through the fog of war (cheat).
	//Broodwar->enableFlag(Flag::CompleteMapInformation);

	// Set the command optimization level so that common commands can be grouped
	// and reduce the bot's APM (Actions Per Minute).
	Broodwar->setCommandOptimizationLevel(2);

	// Check if this is a replay
	if (!Broodwar->isReplay()) {
		if (Broodwar->enemy())
			Broodwar << "The matchup is me (" << Broodwar->self()->getRace() << ") vs " << Broodwar->enemy()->getRace() << std::endl;
		for (auto u: Broodwar->self()->getUnits()) {
			//this->onUnitComplete(u);
		}
	}

	BWEMMap.Initialize();
	BWEMMap.EnableAutomaticPathAnalysis();

}

void Neohuman::onEnd(bool didWin) {
	// Called when the game ends
	if (didWin) {

	} else {

	}
}

int Neohuman::randint(int min, int max) {
	std::uniform_int_distribution<int> dist(min, max);
	return dist(_rand);
}

template <typename T>
T Neohuman::randele(std::vector <T> &v) {
	return v[randint(0, v.size())];
}

void Neohuman::onFrame() {
	// Called once every game frame
	int constructingLine = 0;
	int availableMinerals = Broodwar->self()->minerals();

#ifdef SHOWTHINGS

	// Display the game frame rate as text in the upper left area of the screen
	Broodwar->drawTextScreen(200, 0,  "FPS: %d", Broodwar->getFPS());
	Broodwar->drawTextScreen(200, 12, "Average FPS: %f", Broodwar->getAverageFPS());
	Broodwar->drawTextScreen(200, 24, "I want %d more supply (%d queued, %d in production)", _wantedExtraSupply, _queuedSupply, _supplyBeingMade);
	Broodwar->drawTextScreen(200, 36, "I have %d barracks!", _nBarracks);

#endif

	try {
		//BWEM::utils::gridMapExample(BWEMMap);
		//BWEM::utils::drawMap(BWEMMap);
	} catch (const std::exception & e) {
		Broodwar << "EXCEPTION: " << e.what() << std::endl;
	}

	// Return if the game is a replay or is paused
	if (Broodwar->isReplay() || Broodwar->isPaused() || !Broodwar->self())
		return;

	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->exists() && u->isBeingConstructed()) {
			Broodwar->drawTextScreen(0, constructingLine, "%s", u->getType().c_str());
			constructingLine += 12;
		}
	}

#ifdef SHOWTHINGS

	// Show worker info
	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->getType().isResourceDepot()) {
			Broodwar->drawCircleMap(u->getPosition(), SATRUATION_RADIUS, Colors::Blue);
			auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
			auto refineries = u->getUnitsInRadius(SATRUATION_RADIUS, (IsRefinery));
			auto gasGeysers = u->getUnitsInRadius(SATRUATION_RADIUS);
			auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
			Broodwar->drawTextMap(u->getPosition() + Position(0, 30), "%cWorkers: %d/%d", Text::White, workers.size(), 2*mineralFields.size());
		}
	}

#endif

	// Prevent spamming by only running our onFrame once every number of latency frames.
	// Latency frames are the number of frames before commands are processed.
	if (Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0)
		return;

	_supplyBeingMade = 0;
	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->isConstructing() && u->getType().getRace().getSupplyProvider() == u->getType())
			_supplyBeingMade += 8;
	}

	availableMinerals -= 100*_queuedSupply/8;

	if (Broodwar->elapsedTime() - _timeLastQueuedSupply > 5) {
		_queuedSupply = 0;
		_timeLastQueuedSupply = Broodwar->elapsedTime();
	}

	_nSupplyOverhead = 2 + MAX((Broodwar->self()->supplyUsed() - 10) / 8, 0);
	_wantedExtraSupply = (Broodwar->self()->supplyUsed() - (Broodwar->self()->supplyTotal() + _supplyBeingMade + _queuedSupply)) / 2 + _nSupplyOverhead;

	_nBarracks = 0;
	for (auto &u : Broodwar->self()->getUnits()) {
		// If a cc is under construction
		if (u->isConstructing() && u->getType() == u->getType().getRace().getCenter() && _isExpanding)
			availableMinerals += 400;
		// If a barracks is under construction
		if (u->isConstructing() && u->getType() == UnitTypes::Terran_Barracks && _isBuildingBarracks)
			availableMinerals += 150;

		if (u->getType() == UnitTypes::Terran_Barracks) {
			++_nBarracks;
		}
	}

	if (_isExpanding) {
		availableMinerals -= 400;
	}

	if (_isBuildingBarracks) {
		availableMinerals -= 150;
	}

	// Check if supply should be increased
	if (_wantedExtraSupply > 0 && availableMinerals >= 100 && Broodwar->self()->supplyTotal() < 400) {
		// Find unit to build our supply!
		for (auto &unit : Broodwar->self()->getUnits()) {
			if (unit->exists() && unit->isGatheringMinerals() && unit->isMoving() && !unit->isCarryingMinerals()) {
				// We have found our candidate!
				auto supplyType = unit->getType().getRace().getSupplyProvider();
				auto buildPos = Broodwar->getBuildLocation(supplyType, unit->getTilePosition());

				if (unit->build(supplyType, buildPos)) {
					_queuedSupply += 8;
					_timeLastQueuedSupply = Broodwar->elapsedTime();
					break;
				}
			}
		}
	}

	if (availableMinerals >= 150 && !_isBuildingBarracks && _nBarracks < 20) {
		// Build barracks!
		for (auto &u : Broodwar->self()->getUnits()) {
			if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
				auto buildingType = UnitTypes::Terran_Barracks;
				auto buildingPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());

				if (u->build(buildingType, buildingPos)) {
					_isBuildingBarracks = true;
					availableMinerals -= 150;
					break;
				}
			}
		}
	}

	/*if (!_isExpanding && availableMinerals >= 400){
		// Expand!
		for (auto &u : Broodwar->self()->getUnits()) {
			if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
				// Builder found!
				auto buildingType = u->getType().getRace().getCenter();
				auto buildPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());

				if (u->build(buildingType, buildPos)) {
					_isExpanding = true;
					availableMinerals -= 400;
					break;
				}
			}
		}
	}*/

	// Iterate through all the units that we own
	for (auto &u : Broodwar->self()->getUnits()) {
		// Ignore the unit if it no longer exists
		// Make sure to include this block when handling any Unit pointer!
		if (!u->exists())
			continue;

		// Ignore the unit if it has one of the following status ailments
		if (u->isLockedDown() || u->isMaelstrommed() || u->isStasised())
			continue;

		// Ignore the unit if it is in one of the following states
		if (u->isLoaded() || !u->isPowered() || u->isStuck())
			continue;

		// Ignore the unit if it is incomplete or busy constructing
		if (!u->isCompleted() || u->isConstructing())
			continue;

		// If the unit is a worker unit
		if (u->getType().isWorker()) {
			auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking, WORKERAGGRORADIUS);
			if (enemyUnit)
				u->attack(enemyUnit);

			// if our worker is idle
			if (u->isIdle()) {
				// Order workers carrying a resource to return them to the center,
				// otherwise find a mineral patch to harvest.
				if (u->isCarryingGas() || u->isCarryingMinerals())
					u->returnCargo();

				else if (!u->getPowerUp()) {
					// Probably need to set up some better logic for this
					auto preferredMiningLocation = u->getClosestUnit(IsMineralField);
					u->gather(preferredMiningLocation);
				}
			}
		} else if (u->getType().isResourceDepot()) {
			auto nearbyGeysers = u->getUnitsInRadius(SATRUATION_RADIUS, (GetType == UnitTypes::Resource_Vespene_Geyser));
			if (u->isIdle()) {
				auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
				if (nWorkers >= 70)
					continue;
				auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
				if (workers.size() < mineralFields.size() * 2 && availableMinerals >= 50) {
					if (u->train(u->getType().getRace().getWorker())) {
						Position pos = u->getPosition();
						Error lastErr = Broodwar->getLastError();
						Broodwar->registerEvent([pos, lastErr](Game*){ Broodwar->drawTextMap(pos + Position(0, -10), "%c%s", Text::Red, lastErr.c_str()); },   // action
							nullptr,    // condition
							Broodwar->getLatencyFrames());  // frames to run
					} else {
						availableMinerals -= 50;
					}
				}
			}
		} else if (u->getType() == UnitTypes::Terran_Barracks) {
			if (u->isIdle() && availableMinerals >= 50)
				if (!u->train(UnitTypes::Terran_Marine))
					availableMinerals -= 50;
		} else if (u->getType() == UnitTypes::Terran_Marine && Broodwar->getFrameCount() % 20 == 0) {
			auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking);
			if (enemyUnit) {
				u->attack(enemyUnit->getPosition());
				continue;
			}
			enemyUnit = u->getClosestUnit(IsEnemy);
			if (enemyUnit) {
				u->attack(enemyUnit->getPosition());
				continue;
			}
			auto closestMarine = u->getClosestUnit(GetType == UnitTypes::Terran_Marine);
			if (closestMarine) {
				auto walk = u->getPosition() - closestMarine->getPosition();
				u->move(u->getPosition() + walk);
			}
		}
	}
}

void Neohuman::onSendText(std::string text) {
	Broodwar->sendText("%s", text.c_str());
}

void Neohuman::onReceiveText(Player player, std::string text) {
	Broodwar << player->getName() << " said \"" << text << "\"" << std::endl;
}

void Neohuman::onPlayerLeft(Player player) {
	Broodwar->sendText("Goodbye %s!", player->getName().c_str());
}

void Neohuman::onNukeDetect(Position target) {
	if (target) {
		Broodwar << "Nuclear Launch Detected at " << target << std::endl;
	} else {
		Broodwar->sendText("Where's the nuke?");
	}
	// You can also retrieve all the nuclear missile targets using Broodwar->getNukeDots()!
}

void Neohuman::onUnitDiscover(Unit unit) {
}

void Neohuman::onUnitEvade(Unit unit) {
}

void Neohuman::onUnitShow(Unit unit) {
}

void Neohuman::onUnitHide(Unit unit) {
}

void Neohuman::onUnitCreate(Unit unit) {
}

void Neohuman::onUnitDestroy(Unit unit) {
}

void Neohuman::onUnitMorph(Unit unit) {
	this->onUnitComplete(unit);
}

void Neohuman::onUnitRenegade(Unit unit){
}

void Neohuman::onSaveGame(std::string gameName){
}

void Neohuman::onUnitComplete(Unit unit){
	if (unit->getType() == unit->getType().getRace().getCenter())
		_isExpanding = false;
	if (unit->getType() == UnitTypes::Terran_Barracks)
		_isBuildingBarracks = false;
}
<commit_msg>Minor cleanup<commit_after>#include "Neohuman.h"
#include <iostream>

#include "BWEM/bwem.h"

using namespace BWAPI;
using namespace Filter;

using namespace BWEM;
using namespace BWEM::BWAPI_ext;
using namespace BWEM::utils;

#define MIN(a, b) (((a) < (b) ? (a) : (b)))
#define MAX(a, b) (((a) < (b) ? (b) : (a)))

#define SATRUATION_RADIUS 350
#define WORKERAGGRORADIUS 200

#define SHOWTHINGS

namespace { auto & BWEMMap = Map::Instance(); }

bool Neohuman::doBuild(Unit u, UnitType building, TilePosition at) {
	_buildingQueue.push_back(Triple<int, UnitType, TilePosition>{u->getID(), building, at});
}

std::pair <int, int> Neohuman::getQueuedResources() {
	std::pair <int, int> resources;
	for (auto &o : _buildingQueue)
		resources.first  += o.second.mineralPrice(),
		resources.second += o.second.gasPrice();
	return resources;
}

std::pair <int, int> Neohuman::getSpendableResources() {
	std::pair <int, int> result = { Broodwar->self()->minerals(), Broodwar->self()->gas() };
	auto queued = this->getQueuedResources();
	result.first -= queued.first, result.second -= queued.second;
	return result;
}

void Neohuman::onStart() {
	Broodwar << "The map is totally not " << Broodwar->mapName() << "!" << std::endl;

	//Broodwar->enableFlag(Flag::UserInput);

	// Uncomment the following line and the bot will know about everything through the fog of war (cheat).
	//Broodwar->enableFlag(Flag::CompleteMapInformation);

	// Set the command optimization level so that common commands can be grouped
	// and reduce the bot's APM (Actions Per Minute).
	Broodwar->setCommandOptimizationLevel(2);

	// Check if this is a replay
	if (!Broodwar->isReplay()) {
		if (Broodwar->enemy())
			Broodwar << "The matchup is me (" << Broodwar->self()->getRace() << ") vs " << Broodwar->enemy()->getRace() << std::endl;
	}

	BWEMMap.Initialize();
	BWEMMap.EnableAutomaticPathAnalysis();

}

void Neohuman::onEnd(bool didWin) {
	// Called when the game ends
	if (didWin) {

	} else {

	}
}

int Neohuman::randint(int min, int max) {
	std::uniform_int_distribution<int> dist(min, max);
	return dist(_rand);
}

template <typename T>
T Neohuman::randele(std::vector <T> &v) {
	return v[randint(0, v.size())];
}

void Neohuman::onFrame() {
	// Called once every game frame
	int constructingLine = 0;
	int availableMinerals = Broodwar->self()->minerals();

#ifdef SHOWTHINGS

	// Display the game frame rate as text in the upper left area of the screen
	Broodwar->drawTextScreen(200, 0,  "FPS: %d", Broodwar->getFPS());
	Broodwar->drawTextScreen(200, 12, "Average FPS: %f", Broodwar->getAverageFPS());
	Broodwar->drawTextScreen(200, 24, "I want %d more supply (%d queued, %d in production)", _wantedExtraSupply, _queuedSupply, _supplyBeingMade);
	Broodwar->drawTextScreen(200, 36, "I have %d barracks!", _nBarracks);

#endif

	try {
		//BWEM::utils::gridMapExample(BWEMMap);
		//BWEM::utils::drawMap(BWEMMap);
	} catch (const std::exception & e) {
		Broodwar << "EXCEPTION: " << e.what() << std::endl;
	}

	// Return if the game is a replay or is paused
	if (Broodwar->isReplay() || Broodwar->isPaused() || !Broodwar->self())
		return;

	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->exists() && u->isBeingConstructed()) {
			Broodwar->drawTextScreen(0, constructingLine, "%s", u->getType().c_str());
			constructingLine += 12;
		}
	}

#ifdef SHOWTHINGS

	// Show worker info
	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->getType().isResourceDepot()) {
			Broodwar->drawCircleMap(u->getPosition(), SATRUATION_RADIUS, Colors::Blue);
			auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
			auto refineries = u->getUnitsInRadius(SATRUATION_RADIUS, (IsRefinery));
			auto gasGeysers = u->getUnitsInRadius(SATRUATION_RADIUS);
			auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
			Broodwar->drawTextMap(u->getPosition() + Position(0, 30), "%cWorkers: %d/%d", Text::White, workers.size(), 2*mineralFields.size());
		}
	}

#endif

	// Prevent spamming by only running our onFrame once every number of latency frames.
	// Latency frames are the number of frames before commands are processed.
	if (Broodwar->getFrameCount() % Broodwar->getLatencyFrames() != 0)
		return;

	_supplyBeingMade = 0;
	for (auto &u : Broodwar->self()->getUnits()) {
		if (u->isConstructing() && u->getType().getRace().getSupplyProvider() == u->getType())
			_supplyBeingMade += 8;
	}

	availableMinerals -= 100*_queuedSupply/8;

	if (Broodwar->elapsedTime() - _timeLastQueuedSupply > 5) {
		_queuedSupply = 0;
		_timeLastQueuedSupply = Broodwar->elapsedTime();
	}

	_nSupplyOverhead = 2 + MAX((Broodwar->self()->supplyUsed() - 10) / 8, 0);
	_wantedExtraSupply = (Broodwar->self()->supplyUsed() - (Broodwar->self()->supplyTotal() + _supplyBeingMade + _queuedSupply)) / 2 + _nSupplyOverhead;

	_nBarracks = 0;
	for (auto &u : Broodwar->self()->getUnits()) {
		// If a cc is under construction
		if (u->isConstructing() && u->getType() == u->getType().getRace().getCenter() && _isExpanding)
			availableMinerals += 400;
		// If a barracks is under construction
		if (u->isConstructing() && u->getType() == UnitTypes::Terran_Barracks && _isBuildingBarracks)
			availableMinerals += 150;

		if (u->getType() == UnitTypes::Terran_Barracks) {
			++_nBarracks;
		}
	}

	if (_isExpanding) {
		availableMinerals -= 400;
	}

	if (_isBuildingBarracks) {
		availableMinerals -= 150;
	}

	// Check if supply should be increased
	if (_wantedExtraSupply > 0 && availableMinerals >= 100 && Broodwar->self()->supplyTotal() < 400) {
		// Find unit to build our supply!
		for (auto &unit : Broodwar->self()->getUnits()) {
			if (unit->exists() && unit->isGatheringMinerals() && unit->isMoving() && !unit->isCarryingMinerals()) {
				// We have found our candidate!
				auto supplyType = unit->getType().getRace().getSupplyProvider();
				auto buildPos = Broodwar->getBuildLocation(supplyType, unit->getTilePosition());

				if (unit->build(supplyType, buildPos)) {
					_queuedSupply += 8;
					_timeLastQueuedSupply = Broodwar->elapsedTime();
					break;
				}
			}
		}
	}

	if (availableMinerals >= 150 && !_isBuildingBarracks && _nBarracks < 20) {
		// Build barracks!
		for (auto &u : Broodwar->self()->getUnits()) {
			if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
				auto buildingType = UnitTypes::Terran_Barracks;
				auto buildingPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());

				if (u->build(buildingType, buildingPos)) {
					_isBuildingBarracks = true;
					availableMinerals -= 150;
					break;
				}
			}
		}
	}

	/*if (!_isExpanding && availableMinerals >= 400){
		// Expand!
		for (auto &u : Broodwar->self()->getUnits()) {
			if (u->exists() && u->isGatheringMinerals() && u->isMoving() && !u->isCarryingMinerals()) {
				// Builder found!
				auto buildingType = u->getType().getRace().getCenter();
				auto buildPos = Broodwar->getBuildLocation(buildingType, u->getTilePosition());

				if (u->build(buildingType, buildPos)) {
					_isExpanding = true;
					availableMinerals -= 400;
					break;
				}
			}
		}
	}*/

	// Iterate through all the units that we own
	for (auto &u : Broodwar->self()->getUnits()) {
		// Ignore the unit if it no longer exists
		// Make sure to include this block when handling any Unit pointer!
		if (!u->exists())
			continue;

		// Ignore the unit if it has one of the following status ailments
		if (u->isLockedDown() || u->isMaelstrommed() || u->isStasised())
			continue;

		// Ignore the unit if it is in one of the following states
		if (u->isLoaded() || !u->isPowered() || u->isStuck())
			continue;

		// Ignore the unit if it is incomplete or busy constructing
		if (!u->isCompleted() || u->isConstructing())
			continue;

		// If the unit is a worker unit
		if (u->getType().isWorker()) {
			auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking, WORKERAGGRORADIUS);
			if (enemyUnit)
				u->attack(enemyUnit);

			// if our worker is idle
			if (u->isIdle()) {
				// Order workers carrying a resource to return them to the center,
				// otherwise find a mineral patch to harvest.
				if (u->isCarryingGas() || u->isCarryingMinerals())
					u->returnCargo();

				else if (!u->getPowerUp()) {
					// Probably need to set up some better logic for this
					auto preferredMiningLocation = u->getClosestUnit(IsMineralField);
					u->gather(preferredMiningLocation);
				}
			}
		} else if (u->getType().isResourceDepot()) {
			auto nearbyGeysers = u->getUnitsInRadius(SATRUATION_RADIUS, (GetType == UnitTypes::Resource_Vespene_Geyser));
			if (u->isIdle()) {
				auto workers = u->getUnitsInRadius(SATRUATION_RADIUS, (IsGatheringMinerals));
				if (nWorkers >= 70)
					continue;
				auto mineralFields = u->getUnitsInRadius(SATRUATION_RADIUS, (IsMineralField));
				if (workers.size() < mineralFields.size() * 2 && availableMinerals >= 50) {
					if (u->train(u->getType().getRace().getWorker())) {
						Position pos = u->getPosition();
						Error lastErr = Broodwar->getLastError();
						Broodwar->registerEvent([pos, lastErr](Game*){ Broodwar->drawTextMap(pos + Position(0, -10), "%c%s", Text::Red, lastErr.c_str()); },   // action
							nullptr,    // condition
							Broodwar->getLatencyFrames());  // frames to run
					} else {
						availableMinerals -= 50;
					}
				}
			}
		} else if (u->getType() == UnitTypes::Terran_Barracks) {
			if (u->isIdle() && availableMinerals >= 50)
				if (!u->train(UnitTypes::Terran_Marine))
					availableMinerals -= 50;
		} else if (u->getType() == UnitTypes::Terran_Marine && Broodwar->getFrameCount() % 20 == 0) {
			auto enemyUnit = u->getClosestUnit(IsEnemy && IsAttacking);
			if (enemyUnit) {
				u->attack(enemyUnit->getPosition());
				continue;
			}
			enemyUnit = u->getClosestUnit(IsEnemy);
			if (enemyUnit) {
				u->attack(enemyUnit->getPosition());
				continue;
			}
			auto closestMarine = u->getClosestUnit(GetType == UnitTypes::Terran_Marine);
			if (closestMarine) {
				auto walk = u->getPosition() - closestMarine->getPosition();
				u->move(u->getPosition() + walk);
			}
		}
	}
}

void Neohuman::onSendText(std::string text) {
	Broodwar->sendText("%s", text.c_str());
}

void Neohuman::onReceiveText(Player player, std::string text) {
	Broodwar << player->getName() << " said \"" << text << "\"" << std::endl;
}

void Neohuman::onPlayerLeft(Player player) {
	Broodwar->sendText("Goodbye %s!", player->getName().c_str());
}

void Neohuman::onNukeDetect(Position target) {
	if (target) {
		Broodwar << "Nuclear Launch Detected at " << target << std::endl;
	} else {
		Broodwar->sendText("Where's the nuke?");
	}
	// You can also retrieve all the nuclear missile targets using Broodwar->getNukeDots()!
}

void Neohuman::onUnitDiscover(Unit unit) {
}

void Neohuman::onUnitEvade(Unit unit) {
}

void Neohuman::onUnitShow(Unit unit) {
}

void Neohuman::onUnitHide(Unit unit) {
}

void Neohuman::onUnitCreate(Unit unit) {
}

void Neohuman::onUnitDestroy(Unit unit) {
}

void Neohuman::onUnitMorph(Unit unit) {
	this->onUnitComplete(unit);
}

void Neohuman::onUnitRenegade(Unit unit){
}

void Neohuman::onSaveGame(std::string gameName){
}

void Neohuman::onUnitComplete(Unit unit){
	if (unit->getType() == unit->getType().getRace().getCenter())
		_isExpanding = false;
	if (unit->getType() == UnitTypes::Terran_Barracks)
		_isBuildingBarracks = false;
}
<|endoftext|>


<commit_before>#include <GL\glew.h>
#include <GL\freeglut.h>
#include <iostream>

void DrawCircle(float cx, float cy, float r, int num_segments)
{
	glBegin(GL_LINE_LOOP);
		for(int i = 0; i < num_segments; i++)
		{
			float theta = 2.0f * 3.1415926f * float(i) / float(num_segments);

			float x = r * cosf(theta);
			float y = r * sinf(theta);

			glVertex2f(x + cx, y + cy);
		}
	glEnd();
}

void render()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	DrawCircle(0.0f, 0.0f, 0.5f, 25);

	glutSwapBuffers( );
}

int main (int argc, char** argv) {
	//Init GLUT & create windows
	glutInit(&argc, argv);
	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);
	glutInitWindowSize(600,600);
	glutInitWindowPosition (500, 100);
	glutCreateWindow("Ola Circular");

	glutDisplayFunc(render);
	//glutReshapeFunc(changeViewport);

	glutMainLoop();
	return 0;
}<commit_msg>Visualizacion de la ola. Amplitud y Frecuencia<commit_after>#include <GL\glew.h>
#include <GL\freeglut.h>
#include <iostream>

using namespace std;

#define DEF_floorGridScale	1.0
#define DEF_floorGridXSteps	10.0
#define DEF_floorGridZSteps	10.0

int angle = 90,
	Xpos = 10,
	Ypos = 10,
	k = 1;
double Zpos = 3.0,
		t = 0.0;

float amplitud = 1.0,
	frecuencia = 1.0;

GLfloat ctlpoints[21][21][3];

GLUnurbsObj *theNurb;

void ejesCoordenada() {

	glLineWidth(2.5);
	glBegin(GL_LINES);
		glColor3f(1.0,0.0,0.0);
		glVertex2f(0,10);
		glVertex2f(0,-10);
		glColor3f(0.0,0.0,1.0);
		glVertex2f(10,0);
		glVertex2f(-10,0);
	glEnd();

	glLineWidth(1.5);
	int i;
	glColor3f(0.0,1.0,0.0);
	glBegin(GL_LINES);
		for(i = -10; i <=10; i++){
			if (i!=0) {
				if ((i%2)==0){
					glVertex2f(i,0.4);
					glVertex2f(i,-0.4);

					glVertex2f(0.4,i);
					glVertex2f(-0.4,i);
				}else{
					glVertex2f(i,0.2);
					glVertex2f(i,-0.2);

					glVertex2f(0.2,i);
					glVertex2f(-0.2,i);

				}
			}
		}

	glEnd();

	glLineWidth(1.0);
}

void changeViewport(int w, int h) {

	float aspectratio;

	if (h==0)
		h=1;

   glViewport (0, 0, (GLsizei) w, (GLsizei) h);
   glMatrixMode (GL_PROJECTION);
   glLoadIdentity ();
   gluPerspective(30, (GLfloat) w/(GLfloat) h, 1.0, 200.0);
   glMatrixMode (GL_MODELVIEW);

}

float direction(int x, int y, int cx, int cy) {
	float l = sqrt(((x - cx)*(x - cx)) + ((y - cy)*(y - cy)));
	return l;
}

void init_surface() {
	int u, v;

    for (u = 0; u < 21; u++) {
		for (v = 0; v < 21; v++) {
			ctlpoints[u][v][0] = ((GLfloat)u - 10.0f);
			ctlpoints[u][v][1] = ((GLfloat)v - 10.0f);
			ctlpoints[u][v][2] = amplitud*(pow(sin(direction(u,v,Xpos,Ypos)*frecuencia - t), k));
		}
    }
}

void init(){

	//GLfloat mat_diffuse[] = { 0.7, 0.7, 0.7, 1.0 };
    //GLfloat mat_specular[] = { 1.0, 1.0, 1.0, 1.0 };
    //GLfloat mat_shininess[] = { 100.0 };

    //glClearColor (0.0, 0.0, 0.0, 1.0);
    //glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
    //glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
    //glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);

	glEnable(GL_LIGHTING);
	glEnable(GL_LIGHT0);
	//glDepthFunc(GL_LESS);
	glEnable(GL_DEPTH_TEST);
	glEnable(GL_AUTO_NORMAL);
	glEnable(GL_NORMALIZE);

	init_surface();

	theNurb = gluNewNurbsRenderer();
	gluNurbsProperty(theNurb, GLU_SAMPLING_TOLERANCE, 15.0); //25.0
	gluNurbsProperty(theNurb, GLU_DISPLAY_MODE, GLU_FILL);
}

void Keyboard(unsigned char key, int x, int y)
{
  switch (key)
  {
	case 27:
		exit (0);
		break;
	case 'a':
		amplitud += 0.1;
		break;
	case 'q':
		amplitud -= 0.1;
		break;
	case 's':
		frecuencia += 0.1;
		break;
	case 'w':
		frecuencia -= 0.1;
		break;
	case 'd':
		k += 1;
		break;
	case 'e':
		if (k > 1)
			k -= 1;
		break;
  }
}

void specialKey (int key, int x, int y) {
	switch (key)
	{
		case GLUT_KEY_UP:
			Xpos += 1;
			break;
		case GLUT_KEY_DOWN:
			Xpos -= 1;
			break;
		case GLUT_KEY_LEFT:
			Ypos -= 1;
			break;
		case GLUT_KEY_RIGHT:
			Ypos += 1;
			break;
	}
}

GLfloat * knotVector(int k) {
	static GLfloat r[25];

	for (int i = 0; i < k; ++i) {
		r[i] = 0.0f;
	}

	for (int i = k; i < (25-k); ++i) {
		r[i] = float(i-3)/18.0;
	}

	for (int i = (25-k); i < 25; ++i) {
		r[i] = 1.0f;
	}

	return r;
}

void curva() {

	GLfloat *knots;

	knots = knotVector(4);

	gluBeginSurface(theNurb);

		gluNurbsSurface(theNurb,
						25,	knots,
						25, knots,
						21 * 3,
						3,
						&ctlpoints[0][0][0],
						4, 4,
						GL_MAP2_VERTEX_3);
	/*

		No cambien los numeros de la funcion,
		solo deben de poner los nombres de las variables correspondiente.

	*/

		gluEndSurface(theNurb);

	/* Muestra los puntos de control */

	/*	int i,j;
		glPointSize(5.0);
		glDisable(GL_LIGHTING);
		glColor3f(1.0, 1.0, 0.0);
		glBegin(GL_POINTS);
		for (i = 0; i <21; i++) {
			for (j = 0; j < 21; j++) {
	            glVertex3f(ctlpoints[i][j][0], 	ctlpoints[i][j][1], ctlpoints[i][j][2]);
			}
		}
		glEnd();*/
		glEnable(GL_LIGHTING);
}

void render(){

	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

	glClearColor(0.0, 0.0, 0.0, 0.0);

	GLfloat zExtent, xExtent, xLocal, zLocal;
    int loopX, loopZ;

	glLoadIdentity ();
	gluLookAt (25.0, 12.0, 4.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0);

	// Luz y material

	GLfloat mat_diffuse[] = { 0.6, 0.6, 0.9, 1.0 };
	GLfloat mat_specular[] = { 0.8, 0.8, 1.0, 1.0 };
	GLfloat mat_shininess[] = { 60.0 };

	glMaterialfv(GL_FRONT, GL_DIFFUSE, mat_diffuse);
	glMaterialfv(GL_FRONT, GL_SPECULAR, mat_specular);
	glMaterialfv(GL_FRONT, GL_SHININESS, mat_shininess);

    GLfloat light_ambient[] = { 0.0, 0.0, 0.2, 1.0 };
	GLfloat light_diffuse[] = { 0.8, 0.8, 0.8, 1.0 };
	GLfloat light_specular[] = { 0.6, 0.6, 0.6, 1.0 };
	GLfloat light_position[] = { -10.0, 5.0, 0.0, 1.0 };

	glLightfv(GL_LIGHT0, GL_AMBIENT, light_ambient);
	glLightfv(GL_LIGHT0, GL_DIFFUSE, light_diffuse);
	glLightfv(GL_LIGHT0, GL_SPECULAR, light_specular);
	glLightfv(GL_LIGHT0, GL_POSITION, light_position);

	// Render Grid

	//glDisable(GL_LIGHTING);
	//glLineWidth(1.0);
	//glPushMatrix();
	//	glRotatef(angle,1.0,0.0,0.0);
	//	glColor3f( 0.0, 0.7, 0.7 );
	//	glBegin( GL_LINES );
	//		zExtent = DEF_floorGridScale * DEF_floorGridZSteps;
	//		for(loopX = -DEF_floorGridXSteps; loopX <= DEF_floorGridXSteps; loopX++ )
	//		{
	//			xLocal = DEF_floorGridScale * loopX;
	//			glVertex3f( xLocal, -zExtent, 0.0 );
	//			glVertex3f( xLocal, zExtent,  0.0 );
	//		}
	//		xExtent = DEF_floorGridScale * DEF_floorGridXSteps;
	//	    for(loopZ = -DEF_floorGridZSteps; loopZ <= DEF_floorGridZSteps; loopZ++ )
	//		{
	//			zLocal = DEF_floorGridScale * loopZ;
	//			glVertex3f( -xExtent, zLocal, 0.0 );
	//			glVertex3f(  xExtent, zLocal, 0.0 );
	//		}
	//	glEnd();
	//	ejesCoordenada();
 //   glPopMatrix();

	//glEnable(GL_LIGHTING);

	// Fin Grid

	//Suaviza las lineas
	glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glEnable( GL_LINE_SMOOTH );

	glPushMatrix();
		glRotatef(angle,-1.0,0.0,0.0);
		//glTranslated(0.0,0.0,Zpos);
		curva();

	glPopMatrix();

	glDisable(GL_BLEND);
	glDisable(GL_LINE_SMOOTH);

	glutSwapBuffers();
}

void animacion(int value) {

	init_surface();
	t += 0.1;
	glutTimerFunc(10,animacion,1);
    glutPostRedisplay();

}

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

	glutInit(&argc, argv);

	glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH);

	glutInitWindowSize(960,540);

	glutCreateWindow("Test Opengl");

	init ();

	glutReshapeFunc(changeViewport);
	glutDisplayFunc(render);
	glutKeyboardFunc(Keyboard);
	glutSpecialFunc(specialKey);

	GLenum err = glewInit();
	if (GLEW_OK != err) {
		fprintf(stderr, "GLEW error");
		return 1;
	}

	glutTimerFunc(10,animacion,1);
	glutMainLoop();
	return 0;

}
<|endoftext|>