<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/include/usr/ipmi/ipmiif.H $                               */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,2017                        */
/* [+] 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 __IPMI_IPMIIF_H
#define __IPMI_IPMIIF_H

#include <sys/msg.h>
#include <errl/errlentry.H>
#include <map>

namespace IPMI
{
    // Message types which travel on the IPMI message queues
    enum msg_type
    {
        // Sent when the interface goes idle *and* we had write which
        // was told the interface was busy. We won't get notified of
        // the general idle state.
        MSG_STATE_IDLE,

        // Ready to read a response
        MSG_STATE_RESP,

        // Ready to read an event/sms
        MSG_STATE_EVNT,

        // A message which needs to be sent
        MSG_STATE_SEND,

        MSG_STATE_SHUTDOWN,

        MSG_STATE_SHUTDOWN_SEL,

        MSG_STATE_GRACEFUL_SHUTDOWN,

        // initiate a reboot request
        MSG_STATE_INITIATE_POWER_CYCLE,

        // Used to check range. Leave as last.
        MSG_LAST_TYPE = MSG_STATE_INITIATE_POWER_CYCLE,
    };

    /**
     *  @brief Returns whether IPMI message type is related to
     *    system shutdown/reboot or not
     *
     *  @param[in] i_msgType IPMI message type in question
     *
     *  @return bool True or false value indicating whether requested IPMI
     *     message type is related to system shutdown/reboot or not
     */
    inline bool validShutdownRebootMsgType(const msg_type i_msgType)
    {
        return (   (i_msgType == MSG_STATE_SHUTDOWN)
                || (i_msgType == MSG_STATE_SHUTDOWN_SEL)
                || (i_msgType == MSG_STATE_GRACEFUL_SHUTDOWN)
                || (i_msgType == MSG_STATE_INITIATE_POWER_CYCLE));
    }

    // chassis power off request types
    enum power_request_type
    {
        CHASSIS_POWER_OFF = 0x00,
        CHASSIS_POWER_SOFT_RESET = 0x01,
        CHASSIS_POWER_CYCLE = 0x02,
        CHASSIS_POWER_RESET = 0x03,
    };

    // Used in the factory for creating the proper subclass.
    enum message_type
    {
        TYPE_SYNC = 0,
        TYPE_ASYNC = 1,
        TYPE_EVENT = 2,
    };

    // IPMI network functions
    enum network_function
    {
        // These are the command network functions, the response
        // network functions are the function + 1. So to determine
        // the proper network function which issued the command
        // associated with a response, subtract 1.
        // Note: these are also shifted left to make room for the LUN.
        NETFUN_CHASSIS  = (0x00 << 2),
        NETFUN_BRIDGE   = (0x02 << 2),
        NETFUN_SENSOR   = (0x04 << 2),
        NETFUN_APP      = (0x06 << 2),
        NETFUN_FIRMWARE = (0x08 << 2),
        NETFUN_STORAGE  = (0x0a << 2),
        NETFUN_TRANPORT = (0x0c << 2),
        NETFUN_GRPEXT   = (0x2c << 2),
        NETFUN_AMI =      (0x32 << 2),
        NETFUN_IBM =      (0x3a << 2),

        // Overload the OEM netfun for a "none" netfun. We use this as a
        // default for objects which will have their netfun filled in
        NETFUN_NONE     = (0x30 << 2),
    };

    // SMS_ATN OEM Event constants
    enum oem_event
    {
        OEM_VALID_NETFUN      = 0x3a,
        OEM_VALID_SEL_ID      = 0x5555,
        OEM_VALID_RECORD_TYPE = 0xC0,
    };

    // IPMI Completion Codes
    enum completion_code
    {
        CC_OK        = 0x00,
        CC_CMDSPC1   = 0x80, // command specific completion code
        CC_CMDSPC2   = 0x81, // command specific completion code
        CC_BUSY      = 0xc0,
        CC_INVALID   = 0xc1,
        CC_CMDLUN    = 0xc2,
        CC_TIMEOUT   = 0xc3,
        CC_NOSPACE   = 0xc4,
        CC_BADRESV   = 0xc5,
        CC_TRUNC     = 0xc6,
        CC_BADLEN    = 0xc7,
        CC_TOOLONG   = 0xc8,
        CC_OORANGE   = 0xc9,
        CC_LONGREPLY = 0xca,
        CC_BADSENSOR = 0xcb,
        CC_REQINVAL  = 0xcc,
        CC_CMDSENSOR = 0xcd,
        CC_CANTREPLY = 0xce,
        CC_DUPREQ    = 0xcf,
        CC_SDRUPDATE = 0xd0,
        CC_FMWUPDATE = 0xd1,
        CC_BMCINIT   = 0xd2,
        CC_BADDEST   = 0xd3,
        CC_NOPERM    = 0xd4,
        CC_BADSTATE  = 0xd5,
        CC_ILLPARAM  = 0xd6,
        CC_UNKBAD    = 0xff
    };

    // per IPMI Spec, section 32.2 OEM SEL Event Records
    struct oemSEL {

        enum Constants
        {
            MANUF_LENGTH = 3,
            CMD_LENGTH = 5,
            LENGTH = 16,
        };

        // ID used for SEL Record access. The Record ID values 0000h and FFFFh
        // have special meaning in the Event Access commands and must not be
        // used as Record ID values for stored SEL Event Records.
        uint16_t iv_record;

        // [7:0] - Record Type
        //  02h     = system event record
        //  C0h-DFh = OEM timestamped, bytes 8-16 OEM defined
        //  E0h-FFh = OEM non-timestamped, bytes 4-16 OEM defined
        uint8_t iv_record_type;

        // Time when event was logged. LS byte first.
        uint32_t iv_timestamp;

        // 3 bytes for the manuf id
        uint8_t iv_manufacturer[MANUF_LENGTH];

        // Presently 0x3A for IBM
        uint8_t iv_netfun;

        // Current command and arguments
        uint8_t iv_cmd[CMD_LENGTH];

        // @brief Populate a selRecord from the wire representation of an event
        // @param[in] i_raw_event_data, pointer to the raw data
        void populateFromEvent(uint8_t const* i_raw_event_data);

        // ctor
        oemSEL():
            iv_record(0),
            iv_record_type(0),
            iv_timestamp(0),
            iv_netfun(0)
            {
                memset(iv_manufacturer, 0, MANUF_LENGTH);
                memset(iv_cmd, 0, CMD_LENGTH);
            };

        // @Brief Create a selRecord from the wire representation of an event
        // @param[in] i_event_data, pointer to the event data
        oemSEL( uint8_t const* i_event_data )
            { populateFromEvent( i_event_data ); }

    };

    //
    // Network function, command pairs.
    //
    typedef std::pair<network_function, uint8_t> command_t;

    // Application messages
    inline const command_t get_device_id(void)
    { return std::make_pair(NETFUN_APP, 0x01); }

    inline const command_t set_acpi_power_state(void)
    { return std::make_pair(NETFUN_APP, 0x06); }

    inline const command_t set_watchdog(void)
    { return std::make_pair(NETFUN_APP, 0x24); }

    inline const command_t reset_watchdog(void)
    { return std::make_pair(NETFUN_APP, 0x22); }

    inline const command_t read_event(void)
    { return std::make_pair(NETFUN_APP, 0x35); }

    inline const command_t get_capabilities(void)
    { return std::make_pair(NETFUN_APP, 0x36); }

    // Chassis messages
    inline const command_t chassis_power_off(void)
    { return std::make_pair(NETFUN_CHASSIS, 0x02); }

    // Storage messages
    inline const command_t set_sel_time(void)
    { return std::make_pair(NETFUN_STORAGE, 0x49); }

    inline const command_t write_fru_data(void)
    { return std::make_pair(NETFUN_STORAGE, 0x12); }

    inline const command_t get_sel_info(void)
    { return std::make_pair(NETFUN_STORAGE, 0x40); }

    inline const command_t reserve_sel(void)
    { return std::make_pair(NETFUN_STORAGE, 0x42); }

    inline const command_t add_sel(void)
    { return std::make_pair(NETFUN_STORAGE, 0x44); }

    //AMI-specific storage messages
    inline const command_t partial_add_esel(void)
    { return std::make_pair(NETFUN_AMI, 0xf0); }

    // event messages
    inline const command_t platform_event(void)
    { return std::make_pair(NETFUN_SENSOR, 0x02); }

    // Sensor messages
    inline const command_t set_sensor_reading(void)
    { return std::make_pair(NETFUN_SENSOR, 0x30); }

    inline const command_t get_sensor_reading(void)
    { return std::make_pair(NETFUN_SENSOR, 0x2D); }

    inline const command_t get_sensor_type(void)
    { return std::make_pair(NETFUN_SENSOR, 0x2F); }

    // OEM Messages
    inline const command_t power_off(void)
    { return std::make_pair(NETFUN_IBM, 0x04); }

    inline const command_t pnor_request(void)
    { return std::make_pair(NETFUN_IBM, 0x07); }

    inline const command_t pnor_response(void)
    { return std::make_pair(NETFUN_IBM, 0x08); }

    // $TODO RTC:123256 - need to add code to get dcmi capabilities
    // This is a dcmi message used to request the
    // user defined power limit from the BMC.
    inline const command_t get_power_limit(void)
    { return std::make_pair(NETFUN_GRPEXT, 0x03); }

    // Some helper messages
    // Used to create an empty message for reception
    inline const command_t no_command(void)
    { return std::make_pair(NETFUN_NONE, 0x00); }

    // This is a message used only for testing. The ipmid responder
    // will drop this message so we can test timeouts.
    inline const command_t test_drop(void)
    { return std::make_pair(NETFUN_APP, 0x3e); }

    /**
     * Send message asynchronously
     * @param[in] i_cmd, the network function and command
     * @param[in] i_len, the length of the buffer
     * @param[in] i_data, the buffer - must be new'd
     * @param[in] i_type, the message type EVENT/ASYNC- defaults to ASYNC
     * @example uint8_t* data = new uint8_t[length];
     * @warning do *not* delete data, the resource provider will do that.
     *
     * @return errlHndl_t, NULL on success
     */
    errlHndl_t send(const command_t& i_cmd,
                    const size_t i_len,
                    uint8_t* i_data,
                    message_type i_type = TYPE_ASYNC);

    /**
     * Send message synchronously
     * @param[in] i_cmd, the command and network function
     * @param[out] o_completion_code,  the completion code
     * @param[in,out] io_len, the length of the buffer
     * @param[in] i_data, the buffer - must be new'd
     * @example uint8_t* data = new uint8_t[length];
     * @example delete[] data;
     *
     * @return errlHndl_t, NULL on success
     */
    errlHndl_t sendrecv(const command_t& i_cmd,
                        completion_code& o_completion_code,
                        size_t& io_len, uint8_t*& io_data);

    /**
     * Synchronously send an event
     * @param[in] i_sensor_type, the sensor type
     * @param[in] i_sensor_num, the sensor number
     * @param[in] i_assertion, bool true is assert, false is deassert.
     * @param[in] i_type, event type
     * @param[out] o_completion_code, completion code
     * @param[in] i_len, number of data bytes (1-3)
     * @param[in] i_data, data bytes
     *
     * @return errlHndl_t, NULL on success
     */
    errlHndl_t send_event(const uint8_t i_sensor_type,
                          const uint8_t i_sensor_number,
                          const bool i_assertion,
                          const uint8_t i_type,
                          completion_code& o_completion_code,
                          const size_t i_len,
                          uint8_t* i_data);

    /**
     * Get the max buffer size
     * @param void
     *
     * @return the maximum space allowed for data, per message
     * (max message for the transport - the header size)
     */
    size_t max_buffer(void);

    /**
     *  @brief Initiate a graceful reboot sequence via the IPMI resource
     *    provider
     */
    void initiateReboot();

    /**
     *  @brief Initiate a power off sequence via the IPMI resource provider
     */
    void initiatePowerOff();

    /**
     * Structure to return BMC/IPMI information in
     */
    struct BmcInfo_t
    {
        uint64_t bulkTransferLpcBaseAddr; //< Base address of the bulk transfer
                            //  LPC bus. Relative to the IO space on the LPC
        uint32_t bulkTransferSize; //< Size of bulk transfer device address
                                   //  space on the LPC bus
        uint8_t chipVersion; //< ML2 chip version
        uint8_t smsAttnInterrupt; //< SMS attention interrupt number
        uint8_t bmcToHostInterrupt; //< BMC to Host response interrupt
        char bmcVendor[32]; //< BMC vendor string. AMI, Aten or OpenBmc
    };

    /**
     * Retrieve some information about the BMC and the connection
     * we have to it.
     *
     * @return Structure of BMC data
     */
    BmcInfo_t getBmcInfo(void);

}; // end namespace IPMI

#endif
<commit_msg>Remove NETFUN_AMI from ipmiif.H<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/include/usr/ipmi/ipmiif.H $                               */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,2017                        */
/* [+] 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 __IPMI_IPMIIF_H
#define __IPMI_IPMIIF_H

#include <sys/msg.h>
#include <errl/errlentry.H>
#include <map>

namespace IPMI
{
    // Message types which travel on the IPMI message queues
    enum msg_type
    {
        // Sent when the interface goes idle *and* we had write which
        // was told the interface was busy. We won't get notified of
        // the general idle state.
        MSG_STATE_IDLE,

        // Ready to read a response
        MSG_STATE_RESP,

        // Ready to read an event/sms
        MSG_STATE_EVNT,

        // A message which needs to be sent
        MSG_STATE_SEND,

        MSG_STATE_SHUTDOWN,

        MSG_STATE_SHUTDOWN_SEL,

        MSG_STATE_GRACEFUL_SHUTDOWN,

        // initiate a reboot request
        MSG_STATE_INITIATE_POWER_CYCLE,

        // Used to check range. Leave as last.
        MSG_LAST_TYPE = MSG_STATE_INITIATE_POWER_CYCLE,
    };

    /**
     *  @brief Returns whether IPMI message type is related to
     *    system shutdown/reboot or not
     *
     *  @param[in] i_msgType IPMI message type in question
     *
     *  @return bool True or false value indicating whether requested IPMI
     *     message type is related to system shutdown/reboot or not
     */
    inline bool validShutdownRebootMsgType(const msg_type i_msgType)
    {
        return (   (i_msgType == MSG_STATE_SHUTDOWN)
                || (i_msgType == MSG_STATE_SHUTDOWN_SEL)
                || (i_msgType == MSG_STATE_GRACEFUL_SHUTDOWN)
                || (i_msgType == MSG_STATE_INITIATE_POWER_CYCLE));
    }

    // chassis power off request types
    enum power_request_type
    {
        CHASSIS_POWER_OFF = 0x00,
        CHASSIS_POWER_SOFT_RESET = 0x01,
        CHASSIS_POWER_CYCLE = 0x02,
        CHASSIS_POWER_RESET = 0x03,
    };

    // Used in the factory for creating the proper subclass.
    enum message_type
    {
        TYPE_SYNC = 0,
        TYPE_ASYNC = 1,
        TYPE_EVENT = 2,
    };

    // IPMI network functions
    enum network_function
    {
        // These are the command network functions, the response
        // network functions are the function + 1. So to determine
        // the proper network function which issued the command
        // associated with a response, subtract 1.
        // Note: these are also shifted left to make room for the LUN.
        NETFUN_CHASSIS  = (0x00 << 2),
        NETFUN_BRIDGE   = (0x02 << 2),
        NETFUN_SENSOR   = (0x04 << 2),
        NETFUN_APP      = (0x06 << 2),
        NETFUN_FIRMWARE = (0x08 << 2),
        NETFUN_STORAGE  = (0x0a << 2),
        NETFUN_TRANPORT = (0x0c << 2),
        NETFUN_GRPEXT   = (0x2c << 2),
        NETFUN_IBM =      (0x3a << 2),

        // Overload the OEM netfun for a "none" netfun. We use this as a
        // default for objects which will have their netfun filled in
        NETFUN_NONE     = (0x30 << 2),
    };

    // SMS_ATN OEM Event constants
    enum oem_event
    {
        OEM_VALID_NETFUN      = 0x3a,
        OEM_VALID_SEL_ID      = 0x5555,
        OEM_VALID_RECORD_TYPE = 0xC0,
    };

    // IPMI Completion Codes
    enum completion_code
    {
        CC_OK        = 0x00,
        CC_CMDSPC1   = 0x80, // command specific completion code
        CC_CMDSPC2   = 0x81, // command specific completion code
        CC_BUSY      = 0xc0,
        CC_INVALID   = 0xc1,
        CC_CMDLUN    = 0xc2,
        CC_TIMEOUT   = 0xc3,
        CC_NOSPACE   = 0xc4,
        CC_BADRESV   = 0xc5,
        CC_TRUNC     = 0xc6,
        CC_BADLEN    = 0xc7,
        CC_TOOLONG   = 0xc8,
        CC_OORANGE   = 0xc9,
        CC_LONGREPLY = 0xca,
        CC_BADSENSOR = 0xcb,
        CC_REQINVAL  = 0xcc,
        CC_CMDSENSOR = 0xcd,
        CC_CANTREPLY = 0xce,
        CC_DUPREQ    = 0xcf,
        CC_SDRUPDATE = 0xd0,
        CC_FMWUPDATE = 0xd1,
        CC_BMCINIT   = 0xd2,
        CC_BADDEST   = 0xd3,
        CC_NOPERM    = 0xd4,
        CC_BADSTATE  = 0xd5,
        CC_ILLPARAM  = 0xd6,
        CC_UNKBAD    = 0xff
    };

    // per IPMI Spec, section 32.2 OEM SEL Event Records
    struct oemSEL {

        enum Constants
        {
            MANUF_LENGTH = 3,
            CMD_LENGTH = 5,
            LENGTH = 16,
        };

        // ID used for SEL Record access. The Record ID values 0000h and FFFFh
        // have special meaning in the Event Access commands and must not be
        // used as Record ID values for stored SEL Event Records.
        uint16_t iv_record;

        // [7:0] - Record Type
        //  02h     = system event record
        //  C0h-DFh = OEM timestamped, bytes 8-16 OEM defined
        //  E0h-FFh = OEM non-timestamped, bytes 4-16 OEM defined
        uint8_t iv_record_type;

        // Time when event was logged. LS byte first.
        uint32_t iv_timestamp;

        // 3 bytes for the manuf id
        uint8_t iv_manufacturer[MANUF_LENGTH];

        // Presently 0x3A for IBM
        uint8_t iv_netfun;

        // Current command and arguments
        uint8_t iv_cmd[CMD_LENGTH];

        // @brief Populate a selRecord from the wire representation of an event
        // @param[in] i_raw_event_data, pointer to the raw data
        void populateFromEvent(uint8_t const* i_raw_event_data);

        // ctor
        oemSEL():
            iv_record(0),
            iv_record_type(0),
            iv_timestamp(0),
            iv_netfun(0)
            {
                memset(iv_manufacturer, 0, MANUF_LENGTH);
                memset(iv_cmd, 0, CMD_LENGTH);
            };

        // @Brief Create a selRecord from the wire representation of an event
        // @param[in] i_event_data, pointer to the event data
        oemSEL( uint8_t const* i_event_data )
            { populateFromEvent( i_event_data ); }

    };

    //
    // Network function, command pairs.
    //
    typedef std::pair<network_function, uint8_t> command_t;

    // Application messages
    inline const command_t get_device_id(void)
    { return std::make_pair(NETFUN_APP, 0x01); }

    inline const command_t set_acpi_power_state(void)
    { return std::make_pair(NETFUN_APP, 0x06); }

    inline const command_t set_watchdog(void)
    { return std::make_pair(NETFUN_APP, 0x24); }

    inline const command_t reset_watchdog(void)
    { return std::make_pair(NETFUN_APP, 0x22); }

    inline const command_t read_event(void)
    { return std::make_pair(NETFUN_APP, 0x35); }

    inline const command_t get_capabilities(void)
    { return std::make_pair(NETFUN_APP, 0x36); }

    // Chassis messages
    inline const command_t chassis_power_off(void)
    { return std::make_pair(NETFUN_CHASSIS, 0x02); }

    // Storage messages
    inline const command_t set_sel_time(void)
    { return std::make_pair(NETFUN_STORAGE, 0x49); }

    inline const command_t write_fru_data(void)
    { return std::make_pair(NETFUN_STORAGE, 0x12); }

    inline const command_t get_sel_info(void)
    { return std::make_pair(NETFUN_STORAGE, 0x40); }

    inline const command_t reserve_sel(void)
    { return std::make_pair(NETFUN_STORAGE, 0x42); }

    inline const command_t add_sel(void)
    { return std::make_pair(NETFUN_STORAGE, 0x44); }

    inline const command_t partial_add_esel(void)
    { return std::make_pair(NETFUN_IBM, 0xf0); }

    // event messages
    inline const command_t platform_event(void)
    { return std::make_pair(NETFUN_SENSOR, 0x02); }

    // Sensor messages
    inline const command_t set_sensor_reading(void)
    { return std::make_pair(NETFUN_SENSOR, 0x30); }

    inline const command_t get_sensor_reading(void)
    { return std::make_pair(NETFUN_SENSOR, 0x2D); }

    inline const command_t get_sensor_type(void)
    { return std::make_pair(NETFUN_SENSOR, 0x2F); }

    // OEM Messages
    inline const command_t power_off(void)
    { return std::make_pair(NETFUN_IBM, 0x04); }

    inline const command_t pnor_request(void)
    { return std::make_pair(NETFUN_IBM, 0x07); }

    inline const command_t pnor_response(void)
    { return std::make_pair(NETFUN_IBM, 0x08); }

    // $TODO RTC:123256 - need to add code to get dcmi capabilities
    // This is a dcmi message used to request the
    // user defined power limit from the BMC.
    inline const command_t get_power_limit(void)
    { return std::make_pair(NETFUN_GRPEXT, 0x03); }

    // Some helper messages
    // Used to create an empty message for reception
    inline const command_t no_command(void)
    { return std::make_pair(NETFUN_NONE, 0x00); }

    // This is a message used only for testing. The ipmid responder
    // will drop this message so we can test timeouts.
    inline const command_t test_drop(void)
    { return std::make_pair(NETFUN_APP, 0x3e); }

    /**
     * Send message asynchronously
     * @param[in] i_cmd, the network function and command
     * @param[in] i_len, the length of the buffer
     * @param[in] i_data, the buffer - must be new'd
     * @param[in] i_type, the message type EVENT/ASYNC- defaults to ASYNC
     * @example uint8_t* data = new uint8_t[length];
     * @warning do *not* delete data, the resource provider will do that.
     *
     * @return errlHndl_t, NULL on success
     */
    errlHndl_t send(const command_t& i_cmd,
                    const size_t i_len,
                    uint8_t* i_data,
                    message_type i_type = TYPE_ASYNC);

    /**
     * Send message synchronously
     * @param[in] i_cmd, the command and network function
     * @param[out] o_completion_code,  the completion code
     * @param[in,out] io_len, the length of the buffer
     * @param[in] i_data, the buffer - must be new'd
     * @example uint8_t* data = new uint8_t[length];
     * @example delete[] data;
     *
     * @return errlHndl_t, NULL on success
     */
    errlHndl_t sendrecv(const command_t& i_cmd,
                        completion_code& o_completion_code,
                        size_t& io_len, uint8_t*& io_data);

    /**
     * Synchronously send an event
     * @param[in] i_sensor_type, the sensor type
     * @param[in] i_sensor_num, the sensor number
     * @param[in] i_assertion, bool true is assert, false is deassert.
     * @param[in] i_type, event type
     * @param[out] o_completion_code, completion code
     * @param[in] i_len, number of data bytes (1-3)
     * @param[in] i_data, data bytes
     *
     * @return errlHndl_t, NULL on success
     */
    errlHndl_t send_event(const uint8_t i_sensor_type,
                          const uint8_t i_sensor_number,
                          const bool i_assertion,
                          const uint8_t i_type,
                          completion_code& o_completion_code,
                          const size_t i_len,
                          uint8_t* i_data);

    /**
     * Get the max buffer size
     * @param void
     *
     * @return the maximum space allowed for data, per message
     * (max message for the transport - the header size)
     */
    size_t max_buffer(void);

    /**
     *  @brief Initiate a graceful reboot sequence via the IPMI resource
     *    provider
     */
    void initiateReboot();

    /**
     *  @brief Initiate a power off sequence via the IPMI resource provider
     */
    void initiatePowerOff();

    /**
     * Structure to return BMC/IPMI information in
     */
    struct BmcInfo_t
    {
        uint64_t bulkTransferLpcBaseAddr; //< Base address of the bulk transfer
                            //  LPC bus. Relative to the IO space on the LPC
        uint32_t bulkTransferSize; //< Size of bulk transfer device address
                                   //  space on the LPC bus
        uint8_t chipVersion; //< ML2 chip version
        uint8_t smsAttnInterrupt; //< SMS attention interrupt number
        uint8_t bmcToHostInterrupt; //< BMC to Host response interrupt
        char bmcVendor[32]; //< BMC vendor string. AMI, Aten or OpenBmc
    };

    /**
     * Retrieve some information about the BMC and the connection
     * we have to it.
     *
     * @return Structure of BMC data
     */
    BmcInfo_t getBmcInfo(void);

}; // end namespace IPMI

#endif
<|endoftext|>


<commit_before>/****************************************************************************

    ui_features.hpp - Support file for writing LV2 plugins in C++

    Copyright (C) 2013 Michael Fisher <mfisher31@gmail.com>

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

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307  USA

 ****************************************************************************/

#ifndef LVTK_UI_FEATURES_HPP
#define LVTK_UI_FEATURES_HPP

#include <lv2/lv2plug.in/ns/extensions/ui/ui.h>

namespace lvtk {

    /** The PortSubscribe Mixin.
        @ingroup guimixins
        @see The internal struct I for details.
     */
    template<bool Required = false>
    struct PortSubscribe
    {
        template<class Derived>
        struct I : Extension<Required>
        {
            I() { memset (&m_pmap, 0, sizeof (LV2UI_Port_Map)); }

            /** @internal */
            static void
            map_feature_handlers (FeatureHandlerMap& hmap)
            {
                hmap[LV2_UI__portSubscribe] = &I<Derived>::handle_feature;
            }

            /** @internal */
            static void
            handle_feature (void* instance, FeatureData* data)
            {
                Derived* d = reinterpret_cast<Derived*>(instance);
                I<Derived>* mixin = static_cast<I<Derived>*>(d);

                LV2UI_Port_Subscribe* ps (reinterpret_cast<LV2UI_Port_Subscribe*> (data));
                memcpy (&mixin->m_subscribe, ps, sizeof (LV2UI_Port_Subscribe));
                mixin->m_ok = (ps->handle      != NULL &&
                               ps->subscribe   != NULL &&
                               ps->unsubscribe != NULL);
            }

            bool
            check_ok()
            {
                if (! Required)
                    this->m_ok = true;

                if (LVTK_DEBUG)
                {
                    std::clog << "    [PortSubscribe] Validation "
                              << (this->m_ok ? "succeeded" : "failed")
                              << "." << std::endl;
                }

                return this->m_ok;
            }

        protected:

            bool
            subscribe (uint32_t port, uint32_t protocol, const Feature* const* features)
            {
                if (portsubscribe_is_valid())
                    return (0 == m_subscribe.subscribe (m_subscribe.handle, port, protocol, features));
                return false;
            }

            bool
            unsubscribe (uint32_t port, uint32_t protocol, const Feature* const* features)
            {
                if (portsubscribe_is_valid())
                    return (0 == m_subscribe.unsubscribe (m_subscribe.handle, port, protocol, features));
                return false;
            }

        private:
            LV2UI_Port_Subscribe m_subscribe;

            /** @internal */
            bool portsubscribe_is_valid() const
            {
                return (m_subscribe.handle      != NULL &&
                        m_subscribe.subscribe   != NULL &&
                        m_subscribe.unsubscribe != NULL);
            }
        };
    };

    /** The PortMap Mixin.
        @ingroup guimixins
        @see The internal struct I for details.
     */
    template<bool Required = false>
    struct PortMap
    {
        template<class Derived>
        struct I : Extension<Required>
        {
            I() { memset (&m_pmap, 0, sizeof (LV2UI_Port_Map)); }

            /** @internal */
            static void
            map_feature_handlers (FeatureHandlerMap& hmap)
            {
                hmap[LV2_UI__portIndex] = &I<Derived>::handle_feature;
                //hmap[LV2_UI__portMap]   = &I<Derived>::handle_feature;
            }

            /** @internal */
            static void
            handle_feature (void* instance, FeatureData* data)
            {
                Derived* d = reinterpret_cast<Derived*>(instance);
                I<Derived>* mixin = static_cast<I<Derived>*>(d);

                LV2UI_Port_Map* pm (reinterpret_cast<LV2UI_Port_Map*> (data));
                mixin->m_pmap.handle      = pm->handle;
                mixin->m_pmap.port_index  = pm->port_index;
                mixin->m_ok = (pm->handle != NULL && pm->port_index != NULL);
            }

            bool
            check_ok()
            {
                if (! Required)
                    this->m_ok = true;

                if (LVTK_DEBUG)
                {
                    std::clog << "    [PortMap] Validation "
                              << (this->m_ok ? "succeeded" : "failed")
                              << "." << std::endl;
                }

                return this->m_ok;
            }

        protected:

            uint32_t
            port_index (const char* symbol)
            {
                if (portmap_is_valid())
                    return m_pmap.port_index (m_pmap.handle, symbol);
                return LV2UI_INVALID_PORT_INDEX;
            }

        private:
            LV2UI_Port_Map m_pmap;

            /** @internal */
            bool portmap_is_valid() const
            {
                return (m_pmap.handle     != NULL &&
                        m_pmap.port_index != NULL);
            }

        };
    };

    /** The Touch Mixin.
        @ingroup guimixins
        @see The internal struct I for details.
     */
    template<bool Required = false>
    struct Touch
    {
        template<class Derived>
        struct I : Extension<Required>
        {
            I() { memset (&m_touch, 0, sizeof (LV2UI_Touch)); }

            /** @internal */
            static void
            map_feature_handlers (FeatureHandlerMap& hmap)
            {
                hmap[LV2_UI__touch] = &I<Derived>::handle_feature;
            }

            /** @internal */
            static void
            handle_feature (void* instance, void* data)
            {
                Derived* d = reinterpret_cast<Derived*>(instance);
                I<Derived>* mixin = static_cast<I<Derived>*>(d);

                LV2UI_Touch* t (reinterpret_cast<LV2UI_Touch*> (data));
                mixin->m_touch.handle = t->handle;
                mixin->m_touch.touch  = t->touch;
                mixin->m_ok = (mixin->m_touch.handle != NULL &&
                               mixin->m_touch.touch  != NULL);
            }

            bool
            check_ok()
            {
                if (! Required)
                    this->m_ok = true;

                if (LVTK_DEBUG)
                {
                    std::clog << "    [Touch] Validation "
                              << (this->m_ok ? "succeeded" : "failed")
                              << "." << std::endl;
                }

                return this->m_ok;
            }

        protected:

            void
            touch (uint32_t port, bool grabbed)
            {
                if (touch_is_valid())
                    m_touch.touch (m_touch.handle, port, grabbed);
            }

        private:
            LV2UI_Touch m_touch;

            /** @internal */
            bool touch_is_valid() const
            {
                return m_touch.handle != NULL &&
                       m_touch.touch  != NULL;
            }

        };
    };

    /** The Parent Mixin.
        @ingroup guimixins
        @see The internal struct I for details.
     */
    template<bool Required = false>
    struct Parent
    {
        template<class Derived>
        struct I : Extension<Required>
        {
            I() : p_parent (NULL) { }

            /** @internal */
            static void
            map_feature_handlers(FeatureHandlerMap& hmap)
            {
                hmap[LV2_UI__parent] = &I<Derived>::handle_feature;
            }

            /** @internal */
            static void
            handle_feature(void* instance, void* data)
            {
                Derived* d = reinterpret_cast<Derived*>(instance);
                I<Derived>* mixin = static_cast<I<Derived>*>(d);

                mixin->p_parent = reinterpret_cast<LV2UI_Widget*> (data);
                mixin->m_ok = mixin->p_parent != NULL;
            }

            bool
            check_ok()
            {
                if (! Required)
                    this->m_ok = true;

                if (LVTK_DEBUG)
                {
                    std::clog << "    [Parent] Validation "
                            << (this->m_ok ? "succeeded" : "failed")
                            << "." << std::endl;
                }
                return this->m_ok;
            }

        protected:

            /** Get the parent widget if any

                @return The parent LV2_Widget or NULL if not provided
            */
            LV2UI_Widget*
            get_parent()
            {
               return p_parent;
            }

        private:

            LV2UI_Widget* p_parent;

        };
    };

    /** The UIResize Mixin.
        @ingroup guimixins
        @see The internal struct I for details.
     */
    template<bool Required = true>
    struct UIResize
    {
        template<class Derived>
        struct I : Extension<Required>
        {
            I()
            {
                m_resize.handle    = NULL;
                m_resize.ui_resize = NULL;
            }

            /** @internal */
            static void
            map_feature_handlers(FeatureHandlerMap& hmap)
            {
                hmap[LV2_UI__resize] = &I<Derived>::handle_feature;
            }

            /** @internal */
            static void
            handle_feature(void* instance, void* data)
            {
                Derived* d = reinterpret_cast<Derived*>(instance);
                I<Derived>* mixin = static_cast<I<Derived>*>(d);

                LV2UI_Resize* rz (reinterpret_cast<LV2UI_Resize*> (data));
                mixin->m_resize.handle    = rz->handle;
                mixin->m_resize.ui_resize = rz->ui_resize;
                mixin->m_ok = true;
            }

            bool
            check_ok()
            {
                if (! Required) {
                   this->m_ok = true;
                } else {
                   this->m_ok = rsz_is_valid();
                }

                if (LVTK_DEBUG)
                {
                    std::clog << "    [UIResize] Validation "
                              << (this->m_ok ? "succeeded" : "failed")
                              << "." << std::endl;
                }
                return this->m_ok;
            }

        protected:

            /** */

            bool
            ui_resize(int width, int height)
            {
                if (rsz_is_valid())
                   return (0 == m_resize.ui_resize (m_resize.handle, width, height));

                return false;
            }

        private:
            LV2UI_Resize m_resize;
            bool rsz_is_valid() const { return m_resize.ui_resize != NULL && m_resize.handle != NULL; }

        };
    };

}

#endif /* LVTK_UI_FEATURES_HPP */
<commit_msg>Fixed a typo in PortSubscribe mixin<commit_after>/****************************************************************************

    ui_features.hpp - Support file for writing LV2 plugins in C++

    Copyright (C) 2013 Michael Fisher <mfisher31@gmail.com>

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

    This program 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 General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 01222-1307  USA

 ****************************************************************************/

#ifndef LVTK_UI_FEATURES_HPP
#define LVTK_UI_FEATURES_HPP

#include <lv2/lv2plug.in/ns/extensions/ui/ui.h>

namespace lvtk {

    /** The PortSubscribe Mixin.
        @ingroup guimixins
        @see The internal struct I for details.
     */
    template<bool Required = false>
    struct PortSubscribe
    {
        template<class Derived>
        struct I : Extension<Required>
        {
            I() { memset (&m_subscribe, 0, sizeof (LV2UI_Port_Subscribe)); }

            /** @internal */
            static void
            map_feature_handlers (FeatureHandlerMap& hmap)
            {
                hmap[LV2_UI__portSubscribe] = &I<Derived>::handle_feature;
            }

            /** @internal */
            static void
            handle_feature (void* instance, FeatureData* data)
            {
                Derived* d = reinterpret_cast<Derived*>(instance);
                I<Derived>* mixin = static_cast<I<Derived>*>(d);

                LV2UI_Port_Subscribe* ps (reinterpret_cast<LV2UI_Port_Subscribe*> (data));
                memcpy (&mixin->m_subscribe, ps, sizeof (LV2UI_Port_Subscribe));
                mixin->m_ok = (ps->handle      != NULL &&
                               ps->subscribe   != NULL &&
                               ps->unsubscribe != NULL);
            }

            bool
            check_ok()
            {
                if (! Required)
                    this->m_ok = true;

                if (LVTK_DEBUG)
                {
                    std::clog << "    [PortSubscribe] Validation "
                              << (this->m_ok ? "succeeded" : "failed")
                              << "." << std::endl;
                }

                return this->m_ok;
            }

        protected:

            bool
            subscribe (uint32_t port, uint32_t protocol, const Feature* const* features)
            {
                if (portsubscribe_is_valid())
                    return (0 == m_subscribe.subscribe (m_subscribe.handle, port, protocol, features));
                return false;
            }

            bool
            unsubscribe (uint32_t port, uint32_t protocol, const Feature* const* features)
            {
                if (portsubscribe_is_valid())
                    return (0 == m_subscribe.unsubscribe (m_subscribe.handle, port, protocol, features));
                return false;
            }

        private:
            LV2UI_Port_Subscribe m_subscribe;

            /** @internal */
            bool portsubscribe_is_valid() const
            {
                return (m_subscribe.handle      != NULL &&
                        m_subscribe.subscribe   != NULL &&
                        m_subscribe.unsubscribe != NULL);
            }
        };
    };

    /** The PortMap Mixin.
        @ingroup guimixins
        @see The internal struct I for details.
     */
    template<bool Required = false>
    struct PortMap
    {
        template<class Derived>
        struct I : Extension<Required>
        {
            I() { memset (&m_pmap, 0, sizeof (LV2UI_Port_Map)); }

            /** @internal */
            static void
            map_feature_handlers (FeatureHandlerMap& hmap)
            {
                hmap[LV2_UI__portIndex] = &I<Derived>::handle_feature;
                //hmap[LV2_UI__portMap]   = &I<Derived>::handle_feature;
            }

            /** @internal */
            static void
            handle_feature (void* instance, FeatureData* data)
            {
                Derived* d = reinterpret_cast<Derived*>(instance);
                I<Derived>* mixin = static_cast<I<Derived>*>(d);

                LV2UI_Port_Map* pm (reinterpret_cast<LV2UI_Port_Map*> (data));
                mixin->m_pmap.handle      = pm->handle;
                mixin->m_pmap.port_index  = pm->port_index;
                mixin->m_ok = (pm->handle != NULL && pm->port_index != NULL);
            }

            bool
            check_ok()
            {
                if (! Required)
                    this->m_ok = true;

                if (LVTK_DEBUG)
                {
                    std::clog << "    [PortMap] Validation "
                              << (this->m_ok ? "succeeded" : "failed")
                              << "." << std::endl;
                }

                return this->m_ok;
            }

        protected:

            uint32_t
            port_index (const char* symbol)
            {
                if (portmap_is_valid())
                    return m_pmap.port_index (m_pmap.handle, symbol);
                return LV2UI_INVALID_PORT_INDEX;
            }

        private:
            LV2UI_Port_Map m_pmap;

            /** @internal */
            bool portmap_is_valid() const
            {
                return (m_pmap.handle     != NULL &&
                        m_pmap.port_index != NULL);
            }

        };
    };

    /** The Touch Mixin.
        @ingroup guimixins
        @see The internal struct I for details.
     */
    template<bool Required = false>
    struct Touch
    {
        template<class Derived>
        struct I : Extension<Required>
        {
            I() { memset (&m_touch, 0, sizeof (LV2UI_Touch)); }

            /** @internal */
            static void
            map_feature_handlers (FeatureHandlerMap& hmap)
            {
                hmap[LV2_UI__touch] = &I<Derived>::handle_feature;
            }

            /** @internal */
            static void
            handle_feature (void* instance, void* data)
            {
                Derived* d = reinterpret_cast<Derived*>(instance);
                I<Derived>* mixin = static_cast<I<Derived>*>(d);

                LV2UI_Touch* t (reinterpret_cast<LV2UI_Touch*> (data));
                mixin->m_touch.handle = t->handle;
                mixin->m_touch.touch  = t->touch;
                mixin->m_ok = (mixin->m_touch.handle != NULL &&
                               mixin->m_touch.touch  != NULL);
            }

            bool
            check_ok()
            {
                if (! Required)
                    this->m_ok = true;

                if (LVTK_DEBUG)
                {
                    std::clog << "    [Touch] Validation "
                              << (this->m_ok ? "succeeded" : "failed")
                              << "." << std::endl;
                }

                return this->m_ok;
            }

        protected:

            void
            touch (uint32_t port, bool grabbed)
            {
                if (touch_is_valid())
                    m_touch.touch (m_touch.handle, port, grabbed);
            }

        private:
            LV2UI_Touch m_touch;

            /** @internal */
            bool touch_is_valid() const
            {
                return m_touch.handle != NULL &&
                       m_touch.touch  != NULL;
            }

        };
    };

    /** The Parent Mixin.
        @ingroup guimixins
        @see The internal struct I for details.
     */
    template<bool Required = false>
    struct Parent
    {
        template<class Derived>
        struct I : Extension<Required>
        {
            I() : p_parent (NULL) { }

            /** @internal */
            static void
            map_feature_handlers(FeatureHandlerMap& hmap)
            {
                hmap[LV2_UI__parent] = &I<Derived>::handle_feature;
            }

            /** @internal */
            static void
            handle_feature(void* instance, void* data)
            {
                Derived* d = reinterpret_cast<Derived*>(instance);
                I<Derived>* mixin = static_cast<I<Derived>*>(d);

                mixin->p_parent = reinterpret_cast<LV2UI_Widget*> (data);
                mixin->m_ok = mixin->p_parent != NULL;
            }

            bool
            check_ok()
            {
                if (! Required)
                    this->m_ok = true;

                if (LVTK_DEBUG)
                {
                    std::clog << "    [Parent] Validation "
                            << (this->m_ok ? "succeeded" : "failed")
                            << "." << std::endl;
                }
                return this->m_ok;
            }

        protected:

            /** Get the parent widget if any

                @return The parent LV2_Widget or NULL if not provided
            */
            LV2UI_Widget*
            get_parent()
            {
               return p_parent;
            }

        private:

            LV2UI_Widget* p_parent;

        };
    };

    /** The UIResize Mixin.
        @ingroup guimixins
        @see The internal struct I for details.
     */
    template<bool Required = true>
    struct UIResize
    {
        template<class Derived>
        struct I : Extension<Required>
        {
            I()
            {
                m_resize.handle    = NULL;
                m_resize.ui_resize = NULL;
            }

            /** @internal */
            static void
            map_feature_handlers(FeatureHandlerMap& hmap)
            {
                hmap[LV2_UI__resize] = &I<Derived>::handle_feature;
            }

            /** @internal */
            static void
            handle_feature(void* instance, void* data)
            {
                Derived* d = reinterpret_cast<Derived*>(instance);
                I<Derived>* mixin = static_cast<I<Derived>*>(d);

                LV2UI_Resize* rz (reinterpret_cast<LV2UI_Resize*> (data));
                mixin->m_resize.handle    = rz->handle;
                mixin->m_resize.ui_resize = rz->ui_resize;
                mixin->m_ok = true;
            }

            bool
            check_ok()
            {
                if (! Required) {
                   this->m_ok = true;
                } else {
                   this->m_ok = rsz_is_valid();
                }

                if (LVTK_DEBUG)
                {
                    std::clog << "    [UIResize] Validation "
                              << (this->m_ok ? "succeeded" : "failed")
                              << "." << std::endl;
                }
                return this->m_ok;
            }

        protected:

            /** */

            bool
            ui_resize(int width, int height)
            {
                if (rsz_is_valid())
                   return (0 == m_resize.ui_resize (m_resize.handle, width, height));

                return false;
            }

        private:
            LV2UI_Resize m_resize;
            bool rsz_is_valid() const { return m_resize.ui_resize != NULL && m_resize.handle != NULL; }

        };
    };

}

#endif /* LVTK_UI_FEATURES_HPP */
<|endoftext|>


<commit_before>/*
  MusicXML Library
  Copyright (C) Grame 2006-2013

  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at http://mozilla.org/MPL/2.0/.

  Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France
  research@grame.fr
*/

#include <vector>

#include "libmusicxml.h"
#include "musicxmlfactory.h"
#include "versions.h"

using namespace std;
namespace MusicXML2
{

EXP float		musicxmllibVersion()			{ return versions::libVersion(); }
EXP const char* musicxmllibVersionStr()			{ return versions::libVersionStr(); }
EXP float		musicxml2guidoVersion()			{ return versions::xml2guidoVersion(); }
EXP	const char* musicxml2guidoVersionStr()		{ return versions::xml2guidoVersionStr(); }
//EXP int			musicxml2antescofoVersion()			{ return versions::xml2antescofoVersion(); }
//EXP	const char* musicxml2antescofoVersionStr()		{ return versions::xml2antescofoVersionStr(); }

//------------------------------------------------------------------------
EXP TFactory factoryOpen  ()            { return new musicxmlfactory(); }
EXP void  factoryClose (TFactory f)     { delete f; }
EXP void  factoryPrint (TFactory f, ostream& out) { f->print(out); }

//------------------------------------------------------------------------
static TElement   __retainElt  (Sxmlelement elt)    { elt->addReference(); return (TElement)elt; }
static TAttribute __retainAttr (Sxmlattribute attr) { attr->addReference(); return (TAttribute)attr; }
static Sxmlelement    __releaseElt  (TElement elt)          { Sxmlelement xml(elt); elt->removeReference(); return xml; }
static Sxmlattribute  __releaseAttr (TAttribute attr)         { Sxmlattribute xml(attr); attr->removeReference(); return xml; }

//------------------------------------------------------------------------
// high level operations
//------------------------------------------------------------------------
EXP void  factoryHeader (TFactory f, const char* wn, const char* wt, const char* mn, const char* mt)
  { f->header(wn, wt, mn, mt); }
EXP void  factoryCreator  (TFactory f, const char* c, const char* type)
  { f->creator(c, type); }
EXP void  factoryRights (TFactory f, const char* c, const char* type)
  { f->rights(c, type); }
EXP void  factoryEncoding (TFactory f, const char* soft)
  { f->encoding(soft); }

EXP void factoryAddGroup (TFactory f, int number, const char* name, const char* abbrev, bool groupbarline, TElement* parts)
{
  vector<Sxmlelement> list;
  while (*parts) {
    list.push_back(__releaseElt(*parts));
    parts++;
  }
  f->addgroup (number, name, abbrev, groupbarline, list);
}

EXP void    factoryAddPart (TFactory f, TElement part)
  { f->addpart (__releaseElt(part)); }

EXP TElement  factoryScorepart (TFactory f, const char* id, const char* name, const char* abbrev)
  { return __retainElt (f->scorepart (id, name, abbrev)); }
EXP TElement  factoryPart (TFactory f, const char* id)
  { return __retainElt (f->part (id)); }

EXP TElement  factoryMeasure (TFactory f, int number)
  { return __retainElt (f->newmeasure (number)); }
EXP TElement  factoryMeasureWithAttributes (TFactory f, int number, const char* time, const char* clef, int line, int key, int division)
  { return __retainElt (f->newmeasure (number, time, clef, line, key, division)); }

EXP TElement  factoryNote (TFactory f, const char* step, float alter, int octave, int duration, const char* type)
  { return __retainElt (f->newnote (step, alter, octave, duration, type)); }
EXP TElement  factoryRest (TFactory f, int duration, const char* type)
  { return __retainElt (f->newrest (duration, type)); }
EXP TElement  factoryDynamic  (TFactory f, int type, const char* placement)
  { return __retainElt (f->newdynamics (type, placement)); }
EXP TElement  factoryBarline  (TFactory f, const char* location, const char* barstyle, const char *repeat)
  { return __retainElt (f->newbarline (location, barstyle, repeat)); }

EXP void    factoryTuplet (TFactory f, int actual, int normal, TElement * notes)
{
  vector<Sxmlelement> list;
  while (*notes) {
    list.push_back(*notes);
    notes++;
  }
  f->maketuplet (actual, normal, list);
}

EXP void    factoryTie  (TFactory f, TElement from, TElement to)
  { f->tie (from, to); }
EXP void    factoryNotation (TFactory f, TElement elt, TElement notation)
  { f->addnotation (elt, __releaseElt(notation)); }
EXP void    factoryArticulation (TFactory f, TElement elt, TElement articulation)
  { f->addarticulation (elt, __releaseElt(articulation)); }

EXP void    factoryChord (TFactory f, TElement * notes)
{
  vector<Sxmlelement> list;
  while (*notes) {
    list.push_back(*notes);
    notes++;
  }
  f->makechord (list);
}

//------------------------------------------------------------------------
EXP void    factoryAddElement (TFactory f, TElement elt, TElement subelt)
  { f->add (elt, __releaseElt(subelt)); }
EXP void    factoryAddAttribute (TFactory f, TElement elt, TAttribute attr)
  { f->add (elt, __releaseAttr(attr)); }

EXP void    factoryAddElements  (TFactory f, TElement elt, TElement* subelts)
{
  vector<Sxmlelement> list;
  while (*subelts) {
    list.push_back(*subelts);
    subelts++;
  }
  f->add (elt, list);
}

//------------------------------------------------------------------------
// elements creation
//------------------------------------------------------------------------
template <typename T> TElement  __factoryElement (TFactory f, int type, T value)
  { return __retainElt (f->element (type, value)); }

EXP TElement  factoryElement    (TFactory f, int type)
  { return __factoryElement (f, type, (char*)0); }
EXP TElement  factoryStrElement (TFactory f, int type, const char * value)
  { return __factoryElement (f, type, value); }
EXP TElement  factoryIntElement (TFactory f, int type, int value)
  { return __factoryElement (f, type, value); }
EXP TElement  factoryFloatElement (TFactory f, int type, float value)
  { return __factoryElement (f, type, value); }

//------------------------------------------------------------------------
// attributes creation
//------------------------------------------------------------------------
template <typename T> TAttribute  __factoryAttribute (TFactory f, const char * name, T value)
  { return __retainAttr (f->attribute (name, value)); }

EXP TAttribute  factoryStrAttribute   (TFactory f, const char * name, const char* value)
  { return __factoryAttribute (f, name, value); }
EXP TAttribute  factoryIntAttribute   (TFactory f, const char * name, int value)
  { return __factoryAttribute (f, name, value); }
EXP TAttribute  factoryFloatAttribute (TFactory f, const char * name, float value)
  { return __factoryAttribute (f, name, value); }

//------------------------------------------------------------------------
EXP void    factoryFreeElement    (TFactory f, TElement elt)    { elt->removeReference(); }
EXP void    factoryFreeAttribute  (TFactory f, TAttribute attr) { attr->removeReference(); }

}
<commit_msg>back to previous version and layout<commit_after>/*
  MusicXML Library
  Copyright (C) Grame 2006-2013

  This Source Code Form is subject to the terms of the Mozilla Public
  License, v. 2.0. If a copy of the MPL was not distributed with this
  file, You can obtain one at http://mozilla.org/MPL/2.0/.

  Grame Research Laboratory, 11, cours de Verdun Gensoul 69002 Lyon - France
  research@grame.fr
*/

#include <vector>

#include "libmusicxml.h"
#include "musicxmlfactory.h"
#include "versions.h"

using namespace std;
namespace MusicXML2
{

EXP float		musicxmllibVersion()			{ return versions::libVersion(); }
EXP const char* musicxmllibVersionStr()			{ return versions::libVersionStr(); }
EXP float		musicxml2guidoVersion()			{ return versions::xml2guidoVersion(); }
EXP	const char* musicxml2guidoVersionStr()		{ return versions::xml2guidoVersionStr(); }
//EXP int			musicxml2antescofoVersion()			{ return versions::xml2antescofoVersion(); }
//EXP	const char* musicxml2antescofoVersionStr()		{ return versions::xml2antescofoVersionStr(); }

//------------------------------------------------------------------------
EXP TFactory factoryOpen  ()						{ return new musicxmlfactory(); }
EXP void	factoryClose (TFactory f)				{ delete f; }
EXP void	factoryPrint (TFactory f, ostream& out)	{ f->print(out); }

//------------------------------------------------------------------------
static TElement		__retainElt  (Sxmlelement elt)		{ elt->addReference(); return (TElement)elt; }
static TAttribute	__retainAttr (Sxmlattribute attr)	{ attr->addReference(); return (TAttribute)attr; }
static Sxmlelement		__releaseElt  (TElement elt)					{ Sxmlelement xml(elt); elt->removeReference(); return xml; }
static Sxmlattribute	__releaseAttr (TAttribute attr)					{ Sxmlattribute xml(attr); attr->removeReference(); return xml; }

//------------------------------------------------------------------------
// high level operations
//------------------------------------------------------------------------
EXP void	factoryHeader	(TFactory f, const char* wn, const char* wt, const char* mn, const char* mt)
	{ f->header(wn, wt, mn, mt); }
EXP void	factoryCreator	(TFactory f, const char* c, const char* type)
	{ f->creator(c, type); }
EXP void	factoryRights	(TFactory f, const char* c, const char* type)
	{ f->rights(c, type); }
EXP void	factoryEncoding (TFactory f, const char* soft)
	{ f->encoding(soft); }

EXP void factoryAddGroup (TFactory f, int number, const char* name, const char* abbrev, bool groupbarline, TElement* parts)
{
	vector<Sxmlelement> list;
	while (*parts) {
		list.push_back(__releaseElt(*parts));
		parts++;
	}
	f->addgroup (number, name, abbrev, groupbarline, list);
}

EXP void		factoryAddPart (TFactory f, TElement part)
	{ f->addpart (__releaseElt(part)); }

EXP TElement	factoryScorepart (TFactory f, const char* id, const char* name, const char* abbrev)
	{ return __retainElt (f->scorepart (id, name, abbrev)); }
EXP TElement	factoryPart (TFactory f, const char* id)
	{ return __retainElt (f->part (id)); }

EXP TElement	factoryMeasure (TFactory f, int number)
	{ return __retainElt (f->newmeasure (number)); }
EXP TElement	factoryMeasureWithAttributes (TFactory f, int number, const char* time, const char* clef, int line, int key, int division)
	{ return __retainElt (f->newmeasure (number, time, clef, line, key, division)); }

EXP TElement	factoryNote	(TFactory f, const char* step, float alter, int octave, int duration, const char* type)
	{ return __retainElt (f->newnote (step, alter, octave, duration, type)); }
EXP TElement	factoryRest	(TFactory f, int duration, const char* type)
	{ return __retainElt (f->newrest (duration, type)); }
EXP TElement	factoryDynamic	(TFactory f, int type, const char* placement)
	{ return __retainElt (f->newdynamics (type, placement)); }
EXP TElement	factoryBarline	(TFactory f, const char* location, const char* barstyle, const char *repeat)
	{ return __retainElt (f->newbarline (location, barstyle, repeat)); }

EXP void		factoryTuplet (TFactory f, int actual, int normal, TElement * notes)
{
	vector<Sxmlelement> list;
	while (*notes) {
		list.push_back(*notes);
		notes++;
	}
	f->maketuplet (actual, normal, list);
}

EXP void		factoryTie	(TFactory f, TElement from, TElement to)
	{ f->tie (from, to); }
EXP void		factoryNotation	(TFactory f, TElement elt, TElement notation)
	{ f->addnotation (elt, __releaseElt(notation)); }
EXP void		factoryArticulation	(TFactory f, TElement elt, TElement articulation)
	{ f->addarticulation (elt, __releaseElt(articulation)); }

EXP void		factoryChord (TFactory f, TElement * notes)
{
	vector<Sxmlelement> list;
	while (*notes) {
		list.push_back(*notes);
		notes++;
	}
	f->makechord (list);
}

//------------------------------------------------------------------------
EXP void		factoryAddElement	(TFactory f, TElement elt, TElement subelt)
	{ f->add (elt, __releaseElt(subelt)); }
EXP void		factoryAddAttribute	(TFactory f, TElement elt, TAttribute attr)
	{ f->add (elt, __releaseAttr(attr)); }

EXP void		factoryAddElements	(TFactory f, TElement elt, TElement* subelts)
{
	vector<Sxmlelement> list;
	while (*subelts) {
		list.push_back(*subelts);
		subelts++;
	}
	f->add (elt, list);
}

//------------------------------------------------------------------------
// elements creation
//------------------------------------------------------------------------
template <typename T> TElement	__factoryElement (TFactory f, int type, T value)
	{ return __retainElt (f->element (type, value)); }

EXP TElement	factoryElement		(TFactory f, int type)
	{ return __factoryElement (f, type, (char*)0); }
EXP TElement	factoryStrElement	(TFactory f, int type, const char * value)
	{ return __factoryElement (f, type, value); }
EXP TElement	factoryIntElement	(TFactory f, int type, int value)
	{ return __factoryElement (f, type, value); }
EXP TElement	factoryFloatElement	(TFactory f, int type, float value)
	{ return __factoryElement (f, type, value); }

//------------------------------------------------------------------------
// attributes creation
//------------------------------------------------------------------------
template <typename T> TAttribute	__factoryAttribute (TFactory f, const char * name, T value)
	{ return __retainAttr (f->attribute (name, value)); }

EXP TAttribute	factoryStrAttribute		(TFactory f, const char * name, const char* value)
	{ return __factoryAttribute (f, name, value); }
EXP TAttribute	factoryIntAttribute		(TFactory f, const char * name, int value)
	{ return __factoryAttribute (f, name, value); }
EXP TAttribute	factoryFloatAttribute	(TFactory f, const char * name, float value)
	{ return __factoryAttribute (f, name, value); }

//------------------------------------------------------------------------
EXP void		factoryFreeElement		(TFactory f, TElement elt)		{ elt->removeReference(); }
EXP void		factoryFreeAttribute	(TFactory f, TAttribute attr)	{ attr->removeReference(); }

}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "itkExceptionObject.h"
#include "itkFixedArray.h"
#include "otbLandsatTMIndices.h"
#include <vector>
#include <algorithm>

int otbLandsatTMKernelSpectralRules(int argc, char * argv[])
{

  typedef double PrecisionType;
  typedef itk::FixedArray< PrecisionType, 8 >     InputPixelType;

  double TM1 = (::atof(argv[1]));
  double TM2 = (::atof(argv[2]));
  double TM3 = (::atof(argv[3]));
  double TM4 = (::atof(argv[4]));
  double TM5 = (::atof(argv[5]));
  double TM61 = (::atof(argv[6]));
  double TM62 = (::atof(argv[7]));
  double TM7 = (::atof(argv[8]));

  InputPixelType pixel;
  pixel[0] = TM1;
  pixel[1] = TM2;
  pixel[2] = TM3;
  pixel[3] = TM4;
  pixel[4] = TM5;
  pixel[5] = TM61;
  pixel[6] = TM62;
  pixel[7] = TM7;

  std::vector< PrecisionType > v123;
  v123.push_back(TM1);
  v123.push_back(TM2);
  v123.push_back(TM3);

  PrecisionType max123 = *(max_element ( v123.begin(), v123.end() ));
  PrecisionType min123 = *(min_element ( v123.begin(), v123.end() ));

  PrecisionType TV1 = 0.7;
  PrecisionType TV2 = 0.5;

  typedef otb::Functor::LandsatTM::ThickCloudsSpectralRule<InputPixelType> R1FunctorType;
  R1FunctorType r1Funct = R1FunctorType();
  bool result = r1Funct(pixel);
  bool goodResult = (min123 >= (TV1 * max123))
    and (max123 <= TV1 * TM4)
    and (TM5 <= TV1 * TM4)
    and (TM5 >= TV1 * max123)
    and (TM7 <= TV1 * TM4);

  std::cout << "Rule 1 " << goodResult << " " << result << std::endl;
  if( result!=goodResult ) return EXIT_FAILURE;

  typedef otb::Functor::LandsatTM::ThinCloudsSpectralRule<InputPixelType> R2FunctorType;
  R2FunctorType r2Funct = R2FunctorType();
  result = r2Funct(pixel);
  goodResult = (min123 >= (TV1 * max123))
    and (TM4 >= max123)
    and !((TM1<=TM2 and TM2<=TM3 and TM3<=TM4) and TM3 >= TV1*TM4)
    and (TM4 >= TV1*TM5) and (TM5 >= TV1*TM4)
    and (TM5 >= TV1*max123) and (TM5 >= TV1*TM7);

  std::cout << "Rule 2 " << goodResult << " " << result << std::endl;
  if( result!=goodResult ) return EXIT_FAILURE;

  typedef otb::Functor::LandsatTM::SnowOrIceSpectralRule<InputPixelType> R3FunctorType;
  R3FunctorType r3Funct = R3FunctorType();
  result = r3Funct(pixel);
  goodResult = (min123 >= (TV1 * max123))
    and (TM4 >= TV1 * max123)
    and (TM5 <= TV2 * TM4)
    and (TM5 <= TV1* min123)
    and (TM7 <= TV2 * TM4)
    and (TM7 <= TV1*min123);

  std::cout << "Rule 3 " << goodResult << " " << result << std::endl;
  if( result!=goodResult ) return EXIT_FAILURE;

  typedef otb::Functor::LandsatTM::WaterOrShadowSpectralRule<InputPixelType> R4FunctorType;
  R4FunctorType r4Funct = R4FunctorType();
  result = r4Funct(pixel);
  goodResult = (TM1 >= TM2) and (TM2 >= TM3) and (TM3 >= TM4) and (TM4 >= TM5) and (TM4 >= TM7);

  std::cout << "Rule 4 " << goodResult << " " << result << std::endl;
  if( result!=goodResult ) return EXIT_FAILURE;

  typedef otb::Functor::LandsatTM::PitbogOrGreenhouseSpectralRule<InputPixelType> R5FunctorType;
  R5FunctorType r5Funct = R5FunctorType();
  result = r5Funct(pixel);
  goodResult = (TM3 >= TV1 * TM1)
    and (TM1 >= TV1 * TM3)
    and (max123 <= TV1 * TM4)
    and (TM5 <= TV1 * TM4)
    and (TM3 >= TV2 TM5)
    and (min123 >= TV1 * TM7);

  std::cout << "Rule 5 " << goodResult << " " << result << std::endl;
  if( result!=goodResult ) return EXIT_FAILURE;

  return EXIT_SUCCESS;
}
<commit_msg>TEST: small correction<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#include "itkExceptionObject.h"
#include "itkFixedArray.h"
#include "otbLandsatTMIndices.h"
#include <vector>
#include <algorithm>

int otbLandsatTMKernelSpectralRules(int argc, char * argv[])
{

  typedef double PrecisionType;
  typedef itk::FixedArray< PrecisionType, 8 >     InputPixelType;

  double TM1 = (::atof(argv[1]));
  double TM2 = (::atof(argv[2]));
  double TM3 = (::atof(argv[3]));
  double TM4 = (::atof(argv[4]));
  double TM5 = (::atof(argv[5]));
  double TM61 = (::atof(argv[6]));
  double TM62 = (::atof(argv[7]));
  double TM7 = (::atof(argv[8]));

  InputPixelType pixel;
  pixel[0] = TM1;
  pixel[1] = TM2;
  pixel[2] = TM3;
  pixel[3] = TM4;
  pixel[4] = TM5;
  pixel[5] = TM61;
  pixel[6] = TM62;
  pixel[7] = TM7;

  std::vector< PrecisionType > v123;
  v123.push_back(TM1);
  v123.push_back(TM2);
  v123.push_back(TM3);

  PrecisionType max123 = *(max_element ( v123.begin(), v123.end() ));
  PrecisionType min123 = *(min_element ( v123.begin(), v123.end() ));

  PrecisionType TV1 = 0.7;
  PrecisionType TV2 = 0.5;

  typedef otb::Functor::LandsatTM::ThickCloudsSpectralRule<InputPixelType> R1FunctorType;
  R1FunctorType r1Funct = R1FunctorType();
  bool result = r1Funct(pixel);
  bool goodResult = (min123 >= (TV1 * max123))
    and (max123 <= TV1 * TM4)
    and (TM5 <= TV1 * TM4)
    and (TM5 >= TV1 * max123)
    and (TM7 <= TV1 * TM4);

  std::cout << "Rule 1 " << goodResult << " " << result << std::endl;
  if( result!=goodResult ) return EXIT_FAILURE;

  typedef otb::Functor::LandsatTM::ThinCloudsSpectralRule<InputPixelType> R2FunctorType;
  R2FunctorType r2Funct = R2FunctorType();
  result = r2Funct(pixel);
  goodResult = (min123 >= (TV1 * max123))
    and (TM4 >= max123)
    and !((TM1<=TM2 and TM2<=TM3 and TM3<=TM4) and TM3 >= TV1*TM4)
    and (TM4 >= TV1*TM5) and (TM5 >= TV1*TM4)
    and (TM5 >= TV1*max123) and (TM5 >= TV1*TM7);

  std::cout << "Rule 2 " << goodResult << " " << result << std::endl;
  if( result!=goodResult ) return EXIT_FAILURE;

  typedef otb::Functor::LandsatTM::SnowOrIceSpectralRule<InputPixelType> R3FunctorType;
  R3FunctorType r3Funct = R3FunctorType();
  result = r3Funct(pixel);
  goodResult = (min123 >= (TV1 * max123))
    and (TM4 >= TV1 * max123)
    and (TM5 <= TV2 * TM4)
    and (TM5 <= TV1* min123)
    and (TM7 <= TV2 * TM4)
    and (TM7 <= TV1*min123);

  std::cout << "Rule 3 " << goodResult << " " << result << std::endl;
  if( result!=goodResult ) return EXIT_FAILURE;

  typedef otb::Functor::LandsatTM::WaterOrShadowSpectralRule<InputPixelType> R4FunctorType;
  R4FunctorType r4Funct = R4FunctorType();
  result = r4Funct(pixel);
  goodResult = (TM1 >= TM2) and (TM2 >= TM3) and (TM3 >= TM4) and (TM4 >= TM5) and (TM4 >= TM7);

  std::cout << "Rule 4 " << goodResult << " " << result << std::endl;
  if( result!=goodResult ) return EXIT_FAILURE;

  typedef otb::Functor::LandsatTM::PitbogOrGreenhouseSpectralRule<InputPixelType> R5FunctorType;
  R5FunctorType r5Funct = R5FunctorType();
  result = r5Funct(pixel);
  goodResult = (TM3 >= TV1 * TM1)
    and (TM1 >= TV1 * TM3)
    and (max123 <= TV1 * TM4)
    and (TM5 <= TV1 * TM4)
    and (TM3 >= TV2 * TM5)
    and (min123 >= TV1 * TM7);

  std::cout << "Rule 5 " << goodResult << " " << result << std::endl;
  if( result!=goodResult ) return EXIT_FAILURE;

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  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.                                   */
/*                                                                                */
/*  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 HOLDER 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.                      */
/*                                                                                */
/**************************************************************************************/

#include "../3rdparty/tristripper/tri_stripper.cpp"
#include "../3rdparty/tristripper/policy.cpp"
#include "../3rdparty/tristripper/connectivity_graph.cpp"

using namespace triangle_stripper;

#include <vl/TriangleStripGenerator.hpp>
#include <vl/Geometry.hpp>
#include <vl/DoubleVertexRemover.hpp>
#include <vl/Log.hpp>
#include <vl/Say.hpp>

using namespace vl;

namespace
{
  void fillIndices(std::vector<unsigned int>& indices, const DrawCall* dc, bool substitute_quads)
  {
    indices.clear();
    switch(dc->primitiveType())
    {
      case PT_TRIANGLES:
      {
        indices.reserve(dc->indexCount());
        for(unsigned j=0; j<dc->indexCount(); j+=3)
        {
          int a = dc->index(j+0);
          int b = dc->index(j+1);
          int c = dc->index(j+2);
          // skip degenerate triangles
          if (a != b && b != c)
          {
            indices.push_back(a);
            indices.push_back(b);
            indices.push_back(c);
          }
        }
      }
      break;

      case PT_QUADS:
      {
        if (substitute_quads)
        {
          indices.reserve(dc->indexCount()/4*6);
          for(unsigned q=0; q<dc->indexCount(); q+=4)
          {
            int a = dc->index(q+0);
            int b = dc->index(q+1);
            int c = dc->index(q+2);
            int d = dc->index(q+3);
            if (a != b && a != c)
            {
              indices.push_back(a);
              indices.push_back(b);
              indices.push_back(c);
            }
            if (c!=d && d!=a)
            {
              indices.push_back(c);
              indices.push_back(d);
              indices.push_back(a);
            }
          }
          break;
        }
        else
          return;
      }

      default:
        return;
    }
  }
} // namespace vl

void TriangleStripGenerator::stripfy(Geometry* geom, int cache_size, bool merge_strips, bool remove_doubles, bool substitute_quads)
{
  if (remove_doubles)
  {
    DoubleVertexRemover dvr;
    dvr.removeDoubles(geom);
  }

  for( int idraw=geom->drawCalls()->size(); idraw--; )
  {
    DrawCall* dc = geom->drawCalls()->at(idraw);

    triangle_stripper::indices indices;

    fillIndices(indices, dc, substitute_quads);

    std::vector<unsigned int> algo2_strip;
    std::vector<unsigned int> algo2_tris;
    // stripfyAlgo2(algo2_strip, algo2_tris, indices, cache_size);

    tri_stripper striper(indices);
    striper.SetCacheSize(cache_size);
    striper.SetMinStripSize(4);
    primitive_vector out;
    striper.Strip(&out);

    // install new strip
    if (out.size())
    {
      geom->drawCalls()->erase(idraw,1);
      algo2_strip.reserve(indices.size());
      for(unsigned s=0; s<out.size(); ++s)
      {
        if (out[s].Type == TRIANGLE_STRIP)
        {
          algo2_strip.clear();
          for(unsigned p=0; p<out[s].Indices.size(); ++p)
            algo2_strip.push_back(out[s].Indices[p]);

          ref<DrawElementsUInt> draw_elems = new DrawElementsUInt(PT_TRIANGLE_STRIP);
          draw_elems->indices()->resize(algo2_strip.size());
          memcpy(draw_elems->indices()->ptr(), &algo2_strip[0], sizeof(unsigned int)*algo2_strip.size());
          geom->drawCalls()->push_back(draw_elems.get());
        }
        else // TRIANGLES
        {
          algo2_tris.clear();
          for(unsigned p=0; p<out[s].Indices.size(); ++p)
            algo2_tris.push_back(out[s].Indices[p]);

          ref<DrawElementsUInt> draw_elems = new DrawElementsUInt(PT_TRIANGLES);
          draw_elems->indices()->resize(algo2_tris.size());
          memcpy(draw_elems->indices()->ptr(), &algo2_tris[0], sizeof(unsigned int)*algo2_tris.size());
          geom->drawCalls()->push_back(draw_elems.get());
        }
      }
    }
  }

  if (merge_strips)
    geom->mergeTriangleStrips();

  geom->shrinkDrawElements();
}

<commit_msg>use universal TriangleIterator<commit_after>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  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.                                   */
/*                                                                                */
/*  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 HOLDER 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.                      */
/*                                                                                */
/**************************************************************************************/

#include "../3rdparty/tristripper/tri_stripper.cpp"
#include "../3rdparty/tristripper/policy.cpp"
#include "../3rdparty/tristripper/connectivity_graph.cpp"

using namespace triangle_stripper;

#include <vl/TriangleStripGenerator.hpp>
#include <vl/Geometry.hpp>
#include <vl/DoubleVertexRemover.hpp>
#include <vl/Log.hpp>
#include <vl/Say.hpp>

using namespace vl;

namespace
{
  void fillIndices(std::vector<unsigned int>& indices, const DrawCall* dc, bool substitute_quads)
  {
    indices.clear();

    if ( dc->primitiveType() == PT_QUADS && !substitute_quads )
      return;

    indices.reserve( 1000 );

    for(TriangleIterator trit = dc->triangleIterator(); !trit.isEnd(); trit.next())
    {
      int a = trit.a();
      int b = trit.b();
      int c = trit.c();
      // skip degenerate triangles
      if (a != b && b != c)
      {
        indices.push_back(a);
        indices.push_back(b);
        indices.push_back(c);
      }
    }
  }
}

void TriangleStripGenerator::stripfy(Geometry* geom, int cache_size, bool merge_strips, bool remove_doubles, bool substitute_quads)
{
  if (remove_doubles)
  {
    DoubleVertexRemover dvr;
    dvr.removeDoubles(geom);
  }

  for( int idraw=geom->drawCalls()->size(); idraw--; )
  {
    DrawCall* dc = geom->drawCalls()->at(idraw);

    triangle_stripper::indices indices;

    fillIndices(indices, dc, substitute_quads);

    std::vector<unsigned int> algo2_strip;
    std::vector<unsigned int> algo2_tris;
    // stripfyAlgo2(algo2_strip, algo2_tris, indices, cache_size);

    tri_stripper striper(indices);
    striper.SetCacheSize(cache_size);
    striper.SetMinStripSize(4);
    primitive_vector out;
    striper.Strip(&out);

    // install new strip
    if (out.size())
    {
      geom->drawCalls()->erase(idraw,1);
      algo2_strip.reserve(indices.size());
      for(unsigned s=0; s<out.size(); ++s)
      {
        if (out[s].Type == TRIANGLE_STRIP)
        {
          algo2_strip.clear();
          for(unsigned p=0; p<out[s].Indices.size(); ++p)
            algo2_strip.push_back(out[s].Indices[p]);

          ref<DrawElementsUInt> draw_elems = new DrawElementsUInt(PT_TRIANGLE_STRIP);
          draw_elems->indices()->resize(algo2_strip.size());
          memcpy(draw_elems->indices()->ptr(), &algo2_strip[0], sizeof(unsigned int)*algo2_strip.size());
          geom->drawCalls()->push_back(draw_elems.get());
        }
        else // TRIANGLES
        {
          algo2_tris.clear();
          for(unsigned p=0; p<out[s].Indices.size(); ++p)
            algo2_tris.push_back(out[s].Indices[p]);

          ref<DrawElementsUInt> draw_elems = new DrawElementsUInt(PT_TRIANGLES);
          draw_elems->indices()->resize(algo2_tris.size());
          memcpy(draw_elems->indices()->ptr(), &algo2_tris[0], sizeof(unsigned int)*algo2_tris.size());
          geom->drawCalls()->push_back(draw_elems.get());
        }
      }
    }
  }

  if (merge_strips)
    geom->mergeTriangleStrips();
}

<|endoftext|>


<commit_before>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012       Dennis Nienhüser <earthwings@gentoo.org>
// Copyright 2012       Bernhard Beschow <bbeschow@cs.tu-berlin.de>
//

#include "SearchInputWidget.h"

#include "MarblePlacemarkModel.h"

#include <QtGui/QCompleter>

namespace Marble {

SearchInputWidget::SearchInputWidget( QWidget *parent ) :
    MarbleLineEdit( parent ),
    m_completer( new QCompleter( this ) )
{
    setPlaceholderText( tr( "Search" ) );
    QPixmap const decorator = QPixmap( ":/icons/16x16/edit-find.png" );
    Q_ASSERT( !decorator.isNull() );
    setDecorator( decorator );

    connect( this, SIGNAL( clearButtonClicked() ), this, SLOT( search() ) );
    connect( this, SIGNAL( returnPressed() ), this, SLOT( search() ) );
    connect( this, SIGNAL( decoratorButtonClicked() ), this, SLOT( search() ) );

    m_sortFilter.setSortRole( MarblePlacemarkModel::PopularityIndexRole );
    m_sortFilter.sort( 0, Qt::DescendingOrder );
    m_sortFilter.setDynamicSortFilter( true );

    m_completer->setCompletionRole( Qt::DisplayRole );
    m_completer->setCaseSensitivity( Qt::CaseInsensitive );
    m_completer->setModel( &m_sortFilter );
    setCompleter( m_completer );
    connect( m_completer, SIGNAL( activated( QModelIndex ) ), this, SLOT( centerOnSearchSuggestion( QModelIndex ) ) );
}

void SearchInputWidget::setCompletionModel( QAbstractItemModel *completionModel )
{
    m_sortFilter.setSourceModel( completionModel );
}

void SearchInputWidget::search()
{
    QString const searchTerm = text();
    if ( !searchTerm.isEmpty() ) {
        setBusy( true );
    }
    emit search( searchTerm );
}

void SearchInputWidget::disableSearchAnimation()
{
    setBusy( false );
}

void SearchInputWidget::centerOnSearchSuggestion(const QModelIndex &index )
{
    QAbstractItemModel const * model = completer()->completionModel();
    QVariant const value = model->data( index, MarblePlacemarkModel::CoordinateRole );
    GeoDataCoordinates const coordinates = qVariantValue<GeoDataCoordinates>( value );
    emit centerOn( coordinates );
}

}

#include "SearchInputWidget.moc"
<commit_msg>setPlaceholderText was introduced in Qt 4.7<commit_after>//
// This file is part of the Marble Virtual Globe.
//
// This program is free software licensed under the GNU LGPL. You can
// find a copy of this license in LICENSE.txt in the top directory of
// the source code.
//
// Copyright 2012       Dennis Nienhüser <earthwings@gentoo.org>
// Copyright 2012       Bernhard Beschow <bbeschow@cs.tu-berlin.de>
//

#include "SearchInputWidget.h"

#include "MarblePlacemarkModel.h"

#include <QtGui/QCompleter>

namespace Marble {

SearchInputWidget::SearchInputWidget( QWidget *parent ) :
    MarbleLineEdit( parent ),
    m_completer( new QCompleter( this ) )
{
#if QT_VERSION >= 0x40700
    setPlaceholderText( tr( "Search" ) );
#endif
    QPixmap const decorator = QPixmap( ":/icons/16x16/edit-find.png" );
    Q_ASSERT( !decorator.isNull() );
    setDecorator( decorator );

    connect( this, SIGNAL( clearButtonClicked() ), this, SLOT( search() ) );
    connect( this, SIGNAL( returnPressed() ), this, SLOT( search() ) );
    connect( this, SIGNAL( decoratorButtonClicked() ), this, SLOT( search() ) );

    m_sortFilter.setSortRole( MarblePlacemarkModel::PopularityIndexRole );
    m_sortFilter.sort( 0, Qt::DescendingOrder );
    m_sortFilter.setDynamicSortFilter( true );

    m_completer->setCompletionRole( Qt::DisplayRole );
    m_completer->setCaseSensitivity( Qt::CaseInsensitive );
    m_completer->setModel( &m_sortFilter );
    setCompleter( m_completer );
    connect( m_completer, SIGNAL( activated( QModelIndex ) ), this, SLOT( centerOnSearchSuggestion( QModelIndex ) ) );
}

void SearchInputWidget::setCompletionModel( QAbstractItemModel *completionModel )
{
    m_sortFilter.setSourceModel( completionModel );
}

void SearchInputWidget::search()
{
    QString const searchTerm = text();
    if ( !searchTerm.isEmpty() ) {
        setBusy( true );
    }
    emit search( searchTerm );
}

void SearchInputWidget::disableSearchAnimation()
{
    setBusy( false );
}

void SearchInputWidget::centerOnSearchSuggestion(const QModelIndex &index )
{
    QAbstractItemModel const * model = completer()->completionModel();
    QVariant const value = model->data( index, MarblePlacemarkModel::CoordinateRole );
    GeoDataCoordinates const coordinates = qVariantValue<GeoDataCoordinates>( value );
    emit centerOn( coordinates );
}

}

#include "SearchInputWidget.moc"
<|endoftext|>