hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
sequencelengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
sequencelengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
sequencelengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
2685a4686c01fb7cd7e7de44f972cbef3a02f9be
4,790
hh
C++
neb/inc/com/centreon/engine/configuration/hostescalation.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
neb/inc/com/centreon/engine/configuration/hostescalation.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
neb/inc/com/centreon/engine/configuration/hostescalation.hh
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
/* ** Copyright 2011-2013,2017 Centreon ** ** This file is part of Centreon Engine. ** ** Centreon Engine is free software: you can redistribute it and/or ** modify it under the terms of the GNU General Public License version 2 ** as published by the Free Software Foundation. ** ** Centreon Engine 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 Centreon Engine. If not, see ** <http://www.gnu.org/licenses/>. */ #ifndef CCE_CONFIGURATION_HOSTESCALATION_HH # define CCE_CONFIGURATION_HOSTESCALATION_HH # include <memory> # include <set> # include "com/centreon/engine/configuration/group.hh" # include "com/centreon/engine/configuration/object.hh" # include "com/centreon/engine/opt.hh" # include "com/centreon/engine/namespace.hh" # include "com/centreon/engine/shared.hh" CCE_BEGIN() namespace configuration { class hostescalation : public object { public: enum action_on { none = 0, down = (1 << 0), unreachable = (1 << 1), recovery = (1 << 2) }; typedef hostescalation key_type; hostescalation(); hostescalation(hostescalation const& right); ~hostescalation() throw () override; hostescalation& operator=(hostescalation const& right); bool operator==( hostescalation const& right) const throw (); bool operator!=( hostescalation const& right) const throw (); bool operator<( hostescalation const& right) const; void check_validity() const override; key_type const& key() const throw (); void merge(object const& obj) override; bool parse(char const* key, char const* value) override; set_string& contactgroups() throw (); set_string const& contactgroups() const throw (); bool contactgroups_defined() const throw (); void escalation_options( unsigned short options) throw (); unsigned short escalation_options() const throw (); void escalation_period(std::string const& period); std::string const& escalation_period() const throw (); bool escalation_period_defined() const throw (); void first_notification(unsigned int n) throw (); uint32_t first_notification() const throw (); set_string& hostgroups() throw (); set_string const& hostgroups() const throw (); set_string& hosts() throw (); set_string const& hosts() const throw (); void last_notification(unsigned int n) throw (); unsigned int last_notification() const throw (); void notification_interval(unsigned int interval); unsigned int notification_interval() const throw (); bool notification_interval_defined() const throw (); Uuid const& uuid() const; private: typedef bool (*setter_func)(hostescalation&, char const*); bool _set_contactgroups(std::string const& value); bool _set_escalation_options(std::string const& value); bool _set_escalation_period(std::string const& value); bool _set_first_notification(unsigned int value); bool _set_hostgroups(std::string const& value); bool _set_hosts(std::string const& value); bool _set_last_notification(unsigned int value); bool _set_notification_interval(unsigned int value); group<set_string> _contactgroups; opt<unsigned short> _escalation_options; opt<std::string> _escalation_period; opt<unsigned int> _first_notification; group<set_string> _hostgroups; group<set_string> _hosts; opt<unsigned int> _last_notification; opt<unsigned int> _notification_interval; static std::unordered_map<std::string, setter_func> const _setters; Uuid _uuid; }; typedef std::shared_ptr<hostescalation> hostescalation_ptr; typedef std::set<hostescalation> set_hostescalation; } CCE_END() #endif // !CCE_CONFIGURATION_HOSTESCALATION_HH
42.767857
78
0.602088
sdelafond
268612881e134b8543e320a3a65b6bc505944e36
407
cpp
C++
mine/49-group_anagrams.cpp
Junlin-Yin/myLeetCode
8a33605d3d0de9faa82b5092a8e9f56b342c463f
[ "MIT" ]
null
null
null
mine/49-group_anagrams.cpp
Junlin-Yin/myLeetCode
8a33605d3d0de9faa82b5092a8e9f56b342c463f
[ "MIT" ]
null
null
null
mine/49-group_anagrams.cpp
Junlin-Yin/myLeetCode
8a33605d3d0de9faa82b5092a8e9f56b342c463f
[ "MIT" ]
null
null
null
class Solution { public: vector<vector<string>> groupAnagrams(vector<string>& strs) { vector<vector<string>> ans; map<string, vector<string>> m; for(auto s: strs){ string key = s; sort(key.begin(), key.end()); m[key].push_back(s); } for(auto v: m) ans.push_back(v.second); return ans; } };
27.133333
65
0.4914
Junlin-Yin
26870717ca42ee947e4d83fb9bb16c4aa5d0ffed
4,489
cpp
C++
tests/shared/src/MovingPercentileTests.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
1
2015-03-11T19:49:20.000Z
2015-03-11T19:49:20.000Z
tests/shared/src/MovingPercentileTests.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
tests/shared/src/MovingPercentileTests.cpp
ey6es/hifi
23f9c799dde439e4627eef45341fb0d53feff80b
[ "Apache-2.0" ]
null
null
null
// // MovingPercentileTests.cpp // tests/shared/src // // Created by Yixin Wang on 6/4/2014 // Copyright 2014 High Fidelity, Inc. // // Distributed under the Apache License, Version 2.0. // See the accompanying file LICENSE or http://www.apache.org/licenses/LICENSE-2.0.html // #include "MovingPercentileTests.h" #include "SharedUtil.h" #include "MovingPercentile.h" #include <qqueue.h> float MovingPercentileTests::random() { return rand() / (float)RAND_MAX; } void MovingPercentileTests::runAllTests() { QVector<int> valuesForN; valuesForN.append(1); valuesForN.append(2); valuesForN.append(3); valuesForN.append(4); valuesForN.append(5); valuesForN.append(10); valuesForN.append(100); QQueue<float> lastNSamples; for (int i=0; i<valuesForN.size(); i++) { int N = valuesForN.at(i); qDebug() << "testing moving percentile with N =" << N << "..."; { bool fail = false; qDebug() << "\t testing running min..."; lastNSamples.clear(); MovingPercentile movingMin(N, 0.0f); for (int s = 0; s < 3*N; s++) { float sample = random(); lastNSamples.push_back(sample); if (lastNSamples.size() > N) { lastNSamples.pop_front(); } movingMin.updatePercentile(sample); float experimentMin = movingMin.getValueAtPercentile(); float actualMin = lastNSamples[0]; for (int j = 0; j < lastNSamples.size(); j++) { if (lastNSamples.at(j) < actualMin) { actualMin = lastNSamples.at(j); } } if (experimentMin != actualMin) { qDebug() << "\t\t FAIL at sample" << s; fail = true; break; } } if (!fail) { qDebug() << "\t\t PASS"; } } { bool fail = false; qDebug() << "\t testing running max..."; lastNSamples.clear(); MovingPercentile movingMax(N, 1.0f); for (int s = 0; s < 10000; s++) { float sample = random(); lastNSamples.push_back(sample); if (lastNSamples.size() > N) { lastNSamples.pop_front(); } movingMax.updatePercentile(sample); float experimentMax = movingMax.getValueAtPercentile(); float actualMax = lastNSamples[0]; for (int j = 0; j < lastNSamples.size(); j++) { if (lastNSamples.at(j) > actualMax) { actualMax = lastNSamples.at(j); } } if (experimentMax != actualMax) { qDebug() << "\t\t FAIL at sample" << s; fail = true; break; } } if (!fail) { qDebug() << "\t\t PASS"; } } { bool fail = false; qDebug() << "\t testing running median..."; lastNSamples.clear(); MovingPercentile movingMedian(N, 0.5f); for (int s = 0; s < 10000; s++) { float sample = random(); lastNSamples.push_back(sample); if (lastNSamples.size() > N) { lastNSamples.pop_front(); } movingMedian.updatePercentile(sample); float experimentMedian = movingMedian.getValueAtPercentile(); int samplesLessThan = 0; int samplesMoreThan = 0; for (int j=0; j<lastNSamples.size(); j++) { if (lastNSamples.at(j) < experimentMedian) { samplesLessThan++; } else if (lastNSamples.at(j) > experimentMedian) { samplesMoreThan++; } } if (!(samplesLessThan <= N/2 && samplesMoreThan <= N-1/2)) { qDebug() << "\t\t FAIL at sample" << s; fail = true; break; } } if (!fail) { qDebug() << "\t\t PASS"; } } } }
26.405882
88
0.450212
ey6es
26945ad97669474146a61832833e9516173e6d14
268
cpp
C++
robot_driver/src/robot_driver_node.cpp
robomechanics/quad-software
89154df18e98162249f38301b669df27ee595220
[ "MIT" ]
20
2021-12-05T03:40:28.000Z
2022-03-30T02:53:56.000Z
robot_driver/src/robot_driver_node.cpp
robomechanics/rml-spirit-firmware
89154df18e98162249f38301b669df27ee595220
[ "MIT" ]
45
2021-12-06T12:45:05.000Z
2022-03-31T22:15:47.000Z
robot_driver/src/robot_driver_node.cpp
robomechanics/rml-spirit-firmware
89154df18e98162249f38301b669df27ee595220
[ "MIT" ]
2
2021-12-06T03:20:15.000Z
2022-02-20T04:19:41.000Z
#include <ros/ros.h> #include <iostream> #include "robot_driver/robot_driver.h" int main(int argc, char** argv) { ros::init(argc, argv, "robot_driver_node"); ros::NodeHandle nh; RobotDriver robot_driver(nh, argc, argv); robot_driver.spin(); return 0; }
16.75
45
0.69403
robomechanics
2696661cdfcc1cdd32850db86f3aa38a27bdf078
52,915
cpp
C++
libraries/ble/nRF51822/nordic/ble/ble_bondmngr.cpp
hakehuang/mbed
04b488dcc418f0317cdee1781b27a59295909c77
[ "Apache-2.0" ]
null
null
null
libraries/ble/nRF51822/nordic/ble/ble_bondmngr.cpp
hakehuang/mbed
04b488dcc418f0317cdee1781b27a59295909c77
[ "Apache-2.0" ]
null
null
null
libraries/ble/nRF51822/nordic/ble/ble_bondmngr.cpp
hakehuang/mbed
04b488dcc418f0317cdee1781b27a59295909c77
[ "Apache-2.0" ]
null
null
null
/* Copyright (c) 2012 Nordic Semiconductor. All Rights Reserved. * * The information contained herein is property of Nordic Semiconductor ASA. * Terms and conditions of usage are described in detail in NORDIC * SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT. * * Licensees are granted free, non-transferable use of the information. NO * WARRANTY of ANY KIND is provided. This heading must NOT be removed from * the file. * */ #include "ble_bondmngr.h" #include <stdlib.h> #include <stdint.h> #include <string.h> #include "nordic_common.h" #include "nrf_error.h" #include "ble_gap.h" #include "ble_srv_common.h" #include "app_util.h" #include "nrf_assert.h" //#include "nrf.h" #include "nrf51_bitfields.h" #include "crc16.h" #include "pstorage.h" #include "ble_bondmngr_cfg.h" #define CCCD_SIZE 6 /**< Number of bytes needed for storing the state of one CCCD. */ #define CRC_SIZE 2 /**< Size of CRC in sys_attribute data. */ #define SYS_ATTR_BUFFER_MAX_LEN (((BLE_BONDMNGR_CCCD_COUNT + 1) * CCCD_SIZE) + CRC_SIZE) /**< Size of sys_attribute data. */ #define MAX_NUM_CENTRAL_WHITE_LIST MIN(BLE_BONDMNGR_MAX_BONDED_CENTRALS, 8) /**< Maximum number of whitelisted centrals supported.*/ #define MAX_BONDS_IN_FLASH 10 /**< Maximum number of bonds that can be stored in flash. */ #define BOND_MANAGER_DATA_SIGNATURE 0x53240000 /**@defgroup ble_bond_mngr_sec_access Bond Manager Security Status Access Macros * @brief The following group of macros abstract access to Security Status with a peer. * @{ */ #define SEC_STATUS_INIT_VAL 0x00 /**< Initialization value for security status flags. */ #define ENC_STATUS_SET_VAL 0x01 /**< Bitmask for encryption status. */ #define BOND_IN_PROGRESS_SET_VAL 0x02 /**< Bitmask for 'bonding in progress'. */ /**@brief Macro for setting the Encryption Status for current link. * * @details Macro for setting the Encryption Status for current link. */ #define ENCRYPTION_STATUS_SET() \ do \ { \ m_sec_con_status |= ENC_STATUS_SET_VAL; \ } while (0) /**@brief Macro for getting the Encryption Status for current link. * * @details Macro for getting the Encryption Status for current link. */ #define ENCRYPTION_STATUS_GET() \ (((m_sec_con_status & ENC_STATUS_SET_VAL) == 0) ? false : true) /**@brief Macro for resetting the Encryption Status for current link. * * @details Macro for resetting the Encryption Status for current link. */ #define ENCRYPTION_STATUS_RESET() \ do \ { \ m_sec_con_status &= (~ENC_STATUS_SET_VAL); \ } while (0) /**@brief Macro for resetting the Bonding In Progress status for current link. * * @details Macro for resetting the Bonding In Progress status for current link. */ #define BONDING_IN_PROGRESS_STATUS_SET() \ do \ { \ m_sec_con_status |= BOND_IN_PROGRESS_SET_VAL; \ } while (0) /**@brief Macro for setting the Bonding In Progress status for current link. * * @details Macro for setting the Bonding In Progress status for current link. */ #define BONDING_IN_PROGRESS_STATUS_GET() \ (((m_sec_con_status & BOND_IN_PROGRESS_SET_VAL) == 0) ? false: true) /**@brief Macro for resetting the Bonding In Progress status for current link. * * @details Macro for resetting the Bonding In Progress status for current link. */ #define BONDING_IN_PROGRESS_STATUS_RESET() \ do \ { \ m_sec_con_status &= (~BOND_IN_PROGRESS_SET_VAL); \ } while (0) /**@brief Macro for resetting all security status flags for current link. * * @details Macro for resetting all security status flags for current link. */ #define SECURITY_STATUS_RESET() \ do \ { \ m_sec_con_status = SEC_STATUS_INIT_VAL; \ } while (0) /** @} */ /**@brief Verify module's initialization status. * * @details Verify module's initialization status. Returns NRF_INVALID_STATE in case a module API * is called without initializing the module. */ #define VERIFY_MODULE_INITIALIZED() \ do \ { \ if (!m_is_bondmngr_initialized) \ { \ return NRF_ERROR_INVALID_STATE; \ } \ } while(0) /**@brief This structure contains the Bonding Information for one central. */ typedef struct { int32_t central_handle; /**< Central's handle (NOTE: Size is 32 bits just to make struct size dividable by 4). */ ble_gap_evt_auth_status_t auth_status; /**< Central authentication data. */ ble_gap_evt_sec_info_request_t central_id_info; /**< Central identification info. */ ble_gap_addr_t central_addr; /**< Central's address. */ } central_bond_t; STATIC_ASSERT(sizeof(central_bond_t) % 4 == 0); /**@brief This structure contains the System Attributes information related to one central. */ typedef struct { int32_t central_handle; /**< Central's handle (NOTE: Size is 32 bits just to make struct size dividable by 4). */ uint8_t sys_attr[SYS_ATTR_BUFFER_MAX_LEN]; /**< Central sys_attribute data. */ uint32_t sys_attr_size; /**< Central sys_attribute data's size (NOTE: Size is 32 bits just to make struct size dividable by 4). */ } central_sys_attr_t; STATIC_ASSERT(sizeof(central_sys_attr_t) % 4 == 0); /**@brief This structure contains the Bonding Information and System Attributes related to one * central. */ typedef struct { central_bond_t bond; /**< Bonding information. */ central_sys_attr_t sys_attr; /**< System attribute information. */ } central_t; /**@brief This structure contains the whitelisted addresses. */ typedef struct { int8_t central_handle; /**< Central's handle. */ ble_gap_addr_t * p_addr; /**< Pointer to the central's address if BLE_GAP_ADDR_TYPE_PUBLIC. */ } whitelist_addr_t; /**@brief This structure contains the whitelisted IRKs. */ typedef struct { int8_t central_handle; /**< Central's handle. */ ble_gap_irk_t * p_irk; /**< Pointer to the central's irk if available. */ } whitelist_irk_t; static bool m_is_bondmngr_initialized = false; /**< Flag for checking if module has been initialized. */ static ble_bondmngr_init_t m_bondmngr_config; /**< Configuration as specified by the application. */ static uint16_t m_conn_handle; /**< Current connection handle. */ static central_t m_central; /**< Current central data. */ static central_t m_centrals_db[BLE_BONDMNGR_MAX_BONDED_CENTRALS]; /**< Pointer to start of bonded centrals database. */ static uint8_t m_centrals_in_db_count; /**< Number of bonded centrals. */ static whitelist_addr_t m_whitelist_addr[MAX_NUM_CENTRAL_WHITE_LIST]; /**< List of central's addresses for the whitelist. */ static whitelist_irk_t m_whitelist_irk[MAX_NUM_CENTRAL_WHITE_LIST]; /**< List of central's IRKs for the whitelist. */ static uint8_t m_addr_count; /**< Number of addresses in the whitelist. */ static uint8_t m_irk_count; /**< Number of IRKs in the whitelist. */ static uint16_t m_crc_bond_info; /**< Combined CRC for all Bonding Information currently stored in flash. */ static uint16_t m_crc_sys_attr; /**< Combined CRC for all System Attributes currently stored in flash. */ static pstorage_handle_t mp_flash_bond_info; /**< Pointer to flash location to write next Bonding Information. */ static pstorage_handle_t mp_flash_sys_attr; /**< Pointer to flash location to write next System Attribute information. */ static uint8_t m_bond_info_in_flash_count; /**< Number of Bonding Information currently stored in flash. */ static uint8_t m_sys_attr_in_flash_count; /**< Number of System Attributes currently stored in flash. */ static uint8_t m_sec_con_status; /**< Variable to denote security status.*/ static bool m_bond_loaded; /**< Variable to indicate if the bonding information of the currently connected central is available in the RAM.*/ static bool m_sys_attr_loaded; /**< Variable to indicate if the system attribute information of the currently connected central is loaded from the database and set in the S110 SoftDevice.*/ static uint32_t m_bond_crc_array[BLE_BONDMNGR_MAX_BONDED_CENTRALS]; static uint32_t m_sys_crc_array[BLE_BONDMNGR_MAX_BONDED_CENTRALS]; /**@brief Function for extracting the CRC from an encoded 32 bit number that typical resides in * the flash memory * * @param[in] header Header containing CRC and magic number. * @param[out] p_crc Extracted CRC. * * @retval NRF_SUCCESS CRC successfully extracted. * @retval NRF_ERROR_NOT_FOUND Flash seems to be empty. * @retval NRF_ERROR_INVALID_DATA Header does not contain the magic number. */ static uint32_t crc_extract(uint32_t header, uint16_t * p_crc) { if ((header & 0xFFFF0000U) == BOND_MANAGER_DATA_SIGNATURE) { *p_crc = (uint16_t)(header & 0x0000FFFFU); return NRF_SUCCESS; } else if (header == 0xFFFFFFFFU) { return NRF_ERROR_NOT_FOUND; } else { return NRF_ERROR_INVALID_DATA; } } /**@brief Function for storing the Bonding Information of the specified central to the flash. * * @param[in] p_bond Bonding information to be stored. * * @return NRF_SUCCESS on success, an error_code otherwise. */ static uint32_t bond_info_store(central_bond_t * p_bond) { uint32_t err_code; pstorage_handle_t dest_block; // Check if flash is full if (m_bond_info_in_flash_count >= MAX_BONDS_IN_FLASH) { return NRF_ERROR_NO_MEM; } // Check if this is the first bond to be stored if (m_bond_info_in_flash_count == 0) { // Initialize CRC m_crc_bond_info = crc16_compute(NULL, 0, NULL); } // Get block pointer from base err_code = pstorage_block_identifier_get(&mp_flash_bond_info,m_bond_info_in_flash_count,&dest_block); if (err_code != NRF_SUCCESS) { return err_code; } // Write Bonding Information err_code = pstorage_store(&dest_block, (uint8_t *)p_bond, sizeof(central_bond_t), sizeof(uint32_t)); if (err_code != NRF_SUCCESS) { return err_code; } m_crc_bond_info = crc16_compute((uint8_t *)p_bond, sizeof(central_bond_t), &m_crc_bond_info); // Write header m_bond_crc_array[m_bond_info_in_flash_count] = (BOND_MANAGER_DATA_SIGNATURE | m_crc_bond_info); err_code = pstorage_store (&dest_block, (uint8_t *)&m_bond_crc_array[m_bond_info_in_flash_count],sizeof(uint32_t),0); if (err_code != NRF_SUCCESS) { return err_code; } m_bond_info_in_flash_count++; return NRF_SUCCESS; } /**@brief Function for storing the System Attributes related to a specified central in flash. * * @param[in] p_sys_attr System Attributes to be stored. * * @return NRF_SUCCESS on success, an error_code otherwise. */ static uint32_t sys_attr_store(central_sys_attr_t * p_sys_attr) { uint32_t err_code; pstorage_handle_t dest_block; // Check if flash is full. if (m_sys_attr_in_flash_count >= MAX_BONDS_IN_FLASH) { return NRF_ERROR_NO_MEM; } // Check if this is the first time any System Attributes is stored. if (m_sys_attr_in_flash_count == 0) { // Initialize CRC m_crc_sys_attr = crc16_compute(NULL, 0, NULL); } // Get block pointer from base err_code = pstorage_block_identifier_get(&mp_flash_sys_attr,m_sys_attr_in_flash_count,&dest_block); if (err_code != NRF_SUCCESS) { return err_code; } // Write System Attributes in flash. err_code = pstorage_store(&dest_block, (uint8_t *)p_sys_attr, sizeof(central_sys_attr_t), sizeof(uint32_t)); if (err_code != NRF_SUCCESS) { return err_code; } m_crc_sys_attr = crc16_compute((uint8_t *)p_sys_attr, sizeof(central_sys_attr_t), &m_crc_sys_attr); // Write header. m_sys_crc_array[m_sys_attr_in_flash_count] = (BOND_MANAGER_DATA_SIGNATURE | m_crc_sys_attr); err_code = pstorage_store (&dest_block, (uint8_t *)&m_sys_crc_array[m_sys_attr_in_flash_count], sizeof(uint32_t), 0); if (err_code != NRF_SUCCESS) { return err_code; } m_sys_attr_in_flash_count++; return NRF_SUCCESS; } /**@brief Function for loading the Bonding Information of one central from flash. * * @param[out] p_bond Loaded Bonding Information. * * @return NRF_SUCCESS on success, otherwise an error code. */ static uint32_t bonding_info_load_from_flash(central_bond_t * p_bond) { pstorage_handle_t source_block; uint32_t err_code; uint32_t crc; uint16_t crc_header; // Check if this is the first bond to be loaded, in which case the // m_bond_info_in_flash_count variable would have the intial value 0. if (m_bond_info_in_flash_count == 0) { // Initialize CRC. m_crc_bond_info = crc16_compute(NULL, 0, NULL); } // Get block pointer from base err_code = pstorage_block_identifier_get(&mp_flash_bond_info, m_bond_info_in_flash_count, &source_block); if (err_code != NRF_SUCCESS) { return err_code; } err_code = pstorage_load((uint8_t *)&crc, &source_block, sizeof(uint32_t), 0); if (err_code != NRF_SUCCESS) { return err_code; } // Extract CRC from header. err_code = crc_extract(crc, &crc_header); if (err_code != NRF_SUCCESS) { return err_code; } // Load central. err_code = pstorage_load((uint8_t *)p_bond, &source_block, sizeof(central_bond_t), sizeof(uint32_t)); if (err_code != NRF_SUCCESS) { return err_code; } // Check CRC. m_crc_bond_info = crc16_compute((uint8_t *)p_bond, sizeof(central_bond_t), &m_crc_bond_info); if (m_crc_bond_info == crc_header) { m_bond_info_in_flash_count++; return NRF_SUCCESS; } else { return NRF_ERROR_INVALID_DATA; } } /**@brief Function for loading the System Attributes related to one central from flash. * * @param[out] p_sys_attr Loaded System Attributes. * * @return NRF_SUCCESS on success, otherwise an error code. */ static uint32_t sys_attr_load_from_flash(central_sys_attr_t * p_sys_attr) { pstorage_handle_t source_block; uint32_t err_code; uint32_t crc; uint16_t crc_header; // Check if this is the first time System Attributes is loaded from flash, in which case the // m_sys_attr_in_flash_count variable would have the initial value 0. if (m_sys_attr_in_flash_count == 0) { // Initialize CRC. m_crc_sys_attr = crc16_compute(NULL, 0, NULL); } // Get block pointer from base err_code = pstorage_block_identifier_get(&mp_flash_sys_attr, m_sys_attr_in_flash_count, &source_block); if (err_code != NRF_SUCCESS) { return err_code; } err_code = pstorage_load((uint8_t *)&crc, &source_block, sizeof(uint32_t), 0); if (err_code != NRF_SUCCESS) { return err_code; } // Extract CRC from header. err_code = crc_extract(crc, &crc_header); if (err_code != NRF_SUCCESS) { return err_code; } err_code = pstorage_load((uint8_t *)p_sys_attr, &source_block, sizeof(central_sys_attr_t), sizeof(uint32_t)); if (err_code != NRF_SUCCESS) { return err_code; } // Check CRC. m_crc_sys_attr = crc16_compute((uint8_t *)p_sys_attr, sizeof(central_sys_attr_t), &m_crc_sys_attr); if (m_crc_sys_attr == crc_header) { m_sys_attr_in_flash_count++; return NRF_SUCCESS; } else { return NRF_ERROR_INVALID_DATA; } } /**@brief Function for erasing the flash pages that contain Bonding Information and System * Attributes. * * @return NRF_SUCCESS on success, otherwise an error code. */ static uint32_t flash_pages_erase(void) { uint32_t err_code; err_code = pstorage_clear(&mp_flash_bond_info, MAX_BONDS_IN_FLASH); if (err_code == NRF_SUCCESS) { err_code = pstorage_clear(&mp_flash_sys_attr, MAX_BONDS_IN_FLASH); } return err_code; } /**@brief Function for checking if Bonding Information in RAM is different from that in * flash. * * @return TRUE if Bonding Information in flash and RAM are different, FALSE otherwise. */ static bool bond_info_changed(void) { int i; uint16_t crc = crc16_compute(NULL, 0, NULL); // Compute CRC for all bonds in database. for (i = 0; i < m_centrals_in_db_count; i++) { crc = crc16_compute((uint8_t *)&m_centrals_db[i].bond, sizeof(central_bond_t), &crc); } // Compare the computed CRS to CRC stored in flash. return (crc != m_crc_bond_info); } /**@brief Function for checking if System Attributes in RAM is different from that in flash. * * @return TRUE if System Attributes in flash and RAM are different, FALSE otherwise. */ static bool sys_attr_changed(void) { int i; uint16_t crc = crc16_compute(NULL, 0, NULL); // Compute CRC for all System Attributes in database. for (i = 0; i < m_centrals_in_db_count; i++) { crc = crc16_compute((uint8_t *)&m_centrals_db[i].sys_attr, sizeof(central_sys_attr_t), &crc); } // Compare the CRC of System Attributes in flash with that of the System Attributes in memory. return (crc != m_crc_sys_attr); } /**@brief Function for setting the System Attributes for specified central to the SoftDevice, or * clearing the System Attributes if central is a previously unknown. * * @param[in] p_central Central for which the System Attributes is to be set. * * @return NRF_SUCCESS on success, otherwise an error code. */ static uint32_t central_sys_attr_set(central_t * p_central) { uint8_t * p_sys_attr; if (m_central.sys_attr.sys_attr_size != 0) { if (m_central.sys_attr.sys_attr_size > SYS_ATTR_BUFFER_MAX_LEN) { return NRF_ERROR_INTERNAL; } p_sys_attr = m_central.sys_attr.sys_attr; } else { p_sys_attr = NULL; } return sd_ble_gatts_sys_attr_set(m_conn_handle, p_sys_attr, m_central.sys_attr.sys_attr_size); } /**@brief Function for updating the whitelist data structures. */ static void update_whitelist(void) { int i; for (i = 0, m_addr_count = 0, m_irk_count = 0; i < m_centrals_in_db_count; i++) { central_bond_t * p_bond = &m_centrals_db[i].bond; if (p_bond->auth_status.central_kex.irk) { m_whitelist_irk[m_irk_count].central_handle = p_bond->central_handle; m_whitelist_irk[m_irk_count].p_irk = &(p_bond->auth_status.central_keys.irk); m_irk_count++; } if (p_bond->central_addr.addr_type != BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE) { m_whitelist_addr[m_addr_count].central_handle = p_bond->central_handle; m_whitelist_addr[m_addr_count].p_addr = &(p_bond->central_addr); m_addr_count++; } } } /**@brief Function for handling the authentication status event related to a new central. * * @details This function adds the new central to the database and stores the central's Bonding * Information to flash. It also notifies the application when the new bond is created, * and sets the System Attributes to prepare the stack for connection with the new * central. * * @param[in] p_auth_status New authentication status. * * @return NRF_SUCCESS on success, otherwise an error code. */ static uint32_t on_auth_status_from_new_central(ble_gap_evt_auth_status_t * p_auth_status) { uint32_t err_code; if (m_centrals_in_db_count >= BLE_BONDMNGR_MAX_BONDED_CENTRALS) { return NRF_ERROR_NO_MEM; } // Update central. m_central.bond.auth_status = *p_auth_status; m_central.bond.central_id_info.div = p_auth_status->periph_keys.enc_info.div; m_central.sys_attr.sys_attr_size = 0; // Add new central to database. m_central.bond.central_handle = m_centrals_in_db_count; m_centrals_db[m_centrals_in_db_count++] = m_central; update_whitelist(); m_bond_loaded = true; // Clear System Attributes. err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0); if (err_code != NRF_SUCCESS) { return err_code; } // Write new central's Bonding Information to flash. err_code = bond_info_store(&m_central.bond); if ((err_code == NRF_ERROR_NO_MEM) && (m_bondmngr_config.evt_handler != NULL)) { ble_bondmngr_evt_t evt; evt.evt_type = BLE_BONDMNGR_EVT_BOND_FLASH_FULL; evt.central_handle = m_central.bond.central_handle; evt.central_id = m_central.bond.central_id_info.div; m_bondmngr_config.evt_handler(&evt); } else if (err_code != NRF_SUCCESS) { return err_code; } // Pass the event to application. if (m_bondmngr_config.evt_handler != NULL) { ble_bondmngr_evt_t evt; evt.evt_type = BLE_BONDMNGR_EVT_NEW_BOND; evt.central_handle = m_central.bond.central_handle; evt.central_id = m_central.bond.central_id_info.div; m_bondmngr_config.evt_handler(&evt); } return NRF_SUCCESS; } /**@brief Function for updating the current central's entry in the database. */ static uint32_t central_update(void) { uint32_t err_code; int32_t central_handle = m_central.bond.central_handle; if ((central_handle >= 0) && (central_handle < m_centrals_in_db_count)) { // Update the database based on whether the bond and system attributes have // been loaded or not to avoid overwriting information that was not used in the // connection session. if (m_bond_loaded) { m_centrals_db[central_handle].bond = m_central.bond; } if (m_sys_attr_loaded) { m_centrals_db[central_handle].sys_attr = m_central.sys_attr; } update_whitelist(); err_code = NRF_SUCCESS; } else { err_code = NRF_ERROR_INTERNAL; } return err_code; } /**@brief Function for searching for the central in the database of known centrals. * * @details If the central is found, the variable m_central will be populated with all the * information (Bonding Information and System Attributes) related to that central. * * @param[in] central_id Central Identifier. * @return NRF_SUCCESS on success, otherwise an error code. */ static uint32_t central_find_in_db(uint16_t central_id) { int i; for (i = 0; i < m_centrals_in_db_count; i++) { if (central_id == m_centrals_db[i].bond.central_id_info.div) { m_central = m_centrals_db[i]; return NRF_SUCCESS; } } return NRF_ERROR_NOT_FOUND; } /**@brief Function for loading all Bonding Information and System Attributes from flash. * * @return NRF_SUCCESS on success, otherwise an error code. */ static uint32_t load_all_from_flash(void) { uint32_t err_code; int i; m_centrals_in_db_count = 0; while (m_centrals_in_db_count < BLE_BONDMNGR_MAX_BONDED_CENTRALS) { central_bond_t central_bond_info; int central_handle; // Load Bonding Information. err_code = bonding_info_load_from_flash(&central_bond_info); if (err_code == NRF_ERROR_NOT_FOUND) { // No more bonds in flash. break; } else if (err_code != NRF_SUCCESS) { return err_code; } central_handle = central_bond_info.central_handle; if (central_handle > m_centrals_in_db_count) { // Central handle value(s) missing in flash. This should never happen. return NRF_ERROR_INVALID_DATA; } else { // Add/update Bonding Information in central array. m_centrals_db[central_handle].bond = central_bond_info; if (central_handle == m_centrals_in_db_count) { // New central handle, clear System Attributes. m_centrals_db[central_handle].sys_attr.sys_attr_size = 0; m_centrals_db[central_handle].sys_attr.central_handle = INVALID_CENTRAL_HANDLE; m_centrals_in_db_count++; } else { // Entry was updated, do nothing. } } } // Load System Attributes for all previously known centrals. for (i = 0; i < m_centrals_in_db_count; i++) { central_sys_attr_t central_sys_attr; // Load System Attributes. err_code = sys_attr_load_from_flash(&central_sys_attr); if (err_code == NRF_ERROR_NOT_FOUND) { // No more System Attributes in flash. break; } else if (err_code != NRF_SUCCESS) { return err_code; } if (central_sys_attr.central_handle > m_centrals_in_db_count) { // Central handle value(s) missing in flash. This should never happen. return NRF_ERROR_INVALID_DATA; } else { // Add/update Bonding Information in central array. m_centrals_db[central_sys_attr.central_handle].sys_attr = central_sys_attr; } } // Initialize the remaining empty bond entries in the memory. for (i = m_centrals_in_db_count; i < BLE_BONDMNGR_MAX_BONDED_CENTRALS; i++) { m_centrals_db[i].bond.central_handle = INVALID_CENTRAL_HANDLE; m_centrals_db[i].sys_attr.sys_attr_size = 0; m_centrals_db[i].sys_attr.central_handle = INVALID_CENTRAL_HANDLE; } // Update whitelist data structures. update_whitelist(); return NRF_SUCCESS; } /**@brief Function for handling the connected event received from the BLE stack. * * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_connect(ble_evt_t * p_ble_evt) { m_conn_handle = p_ble_evt->evt.gap_evt.conn_handle; m_central.bond.central_handle = INVALID_CENTRAL_HANDLE; m_central.bond.central_addr = p_ble_evt->evt.gap_evt.params.connected.peer_addr; m_central.sys_attr.sys_attr_size = 0; if (p_ble_evt->evt.gap_evt.params.connected.irk_match) { uint8_t irk_idx = p_ble_evt->evt.gap_evt.params.connected.irk_match_idx; if ((irk_idx >= MAX_NUM_CENTRAL_WHITE_LIST) || (m_whitelist_irk[irk_idx].central_handle >= BLE_BONDMNGR_MAX_BONDED_CENTRALS)) { m_bondmngr_config.error_handler(NRF_ERROR_INTERNAL); } else { m_central = m_centrals_db[m_whitelist_irk[irk_idx].central_handle]; } } else { int i; for (i = 0; i < m_addr_count; i++) { ble_gap_addr_t * p_cur_addr = m_whitelist_addr[i].p_addr; if (memcmp(p_cur_addr->addr, m_central.bond.central_addr.addr, BLE_GAP_ADDR_LEN) == 0) { m_central = m_centrals_db[m_whitelist_addr[i].central_handle]; break; } } } if (m_central.bond.central_handle != INVALID_CENTRAL_HANDLE) { // Reset bond and system attributes loaded variables. m_bond_loaded = false; m_sys_attr_loaded = false; // Do not set the system attributes of the central on connection. if (m_bondmngr_config.evt_handler != NULL) { ble_bondmngr_evt_t evt; evt.evt_type = BLE_BONDMNGR_EVT_CONN_TO_BONDED_CENTRAL; evt.central_handle = m_central.bond.central_handle; evt.central_id = m_central.bond.central_id_info.div; m_bondmngr_config.evt_handler(&evt); } } } /**@brief Function for handling the 'System Attributes Missing' event received from the * SoftDevice. * * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_sys_attr_missing(ble_evt_t * p_ble_evt) { uint32_t err_code; if ( (m_central.bond.central_handle == INVALID_CENTRAL_HANDLE) || !ENCRYPTION_STATUS_GET() || BONDING_IN_PROGRESS_STATUS_GET() ) { err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0); } else { // Current central is valid, use its data. Set the corresponding sys_attr. err_code = central_sys_attr_set(&m_central); if (err_code == NRF_SUCCESS) { // Set System Attributes loaded status variable. m_sys_attr_loaded = true; } } if (err_code != NRF_SUCCESS) { m_bondmngr_config.error_handler(err_code); } } /**@brief Function for handling the new authentication status event, received from the * SoftDevice, related to an already bonded central. * * @details This function also writes the updated Bonding Information to flash and notifies the * application. * * @param[in] p_auth_status Updated authentication status. */ static void auth_status_update(ble_gap_evt_auth_status_t * p_auth_status) { uint32_t err_code; // Authentication status changed, update Bonding Information. m_central.bond.auth_status = *p_auth_status; m_central.bond.central_id_info.div = p_auth_status->periph_keys.enc_info.div; memset(&(m_centrals_db[m_central.bond.central_handle]), 0, sizeof(central_t)); m_centrals_db[m_central.bond.central_handle] = m_central; // Write updated Bonding Information to flash. err_code = bond_info_store(&m_central.bond); if ((err_code == NRF_ERROR_NO_MEM) && (m_bondmngr_config.evt_handler != NULL)) { ble_bondmngr_evt_t evt; evt.evt_type = BLE_BONDMNGR_EVT_BOND_FLASH_FULL; evt.central_handle = m_central.bond.central_handle; evt.central_id = m_central.bond.central_id_info.div; m_bondmngr_config.evt_handler(&evt); } else if (err_code != NRF_SUCCESS) { m_bondmngr_config.error_handler(err_code); } // Pass the event to the application. if (m_bondmngr_config.evt_handler != NULL) { ble_bondmngr_evt_t evt; evt.evt_type = BLE_BONDMNGR_EVT_AUTH_STATUS_UPDATED; evt.central_handle = m_central.bond.central_handle; evt.central_id = m_central.bond.central_id_info.div; m_bondmngr_config.evt_handler(&evt); } } /**@brief Function for handling the Authentication Status event received from the BLE stack. * * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_auth_status(ble_gap_evt_auth_status_t * p_auth_status) { if (p_auth_status->auth_status != BLE_GAP_SEC_STATUS_SUCCESS) { return; } // Verify if its pairing and not bonding if (!ENCRYPTION_STATUS_GET()) { return; } if (m_central.bond.central_handle == INVALID_CENTRAL_HANDLE) { uint32_t err_code = central_find_in_db(p_auth_status->periph_keys.enc_info.div); if (err_code == NRF_SUCCESS) { // Possible DIV Collision indicate error to application, // not storing the new LTK err_code = NRF_ERROR_FORBIDDEN; } else { // Add the new device to data base err_code = on_auth_status_from_new_central(p_auth_status); } if (err_code != NRF_SUCCESS) { m_bondmngr_config.error_handler(err_code); } } else { m_bond_loaded = true; // Receiving a auth status again when already in have existing information! auth_status_update(p_auth_status); } } /**@brief Function for handling the Security Info Request event received from the BLE stack. * * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_sec_info_request(ble_evt_t * p_ble_evt) { uint32_t err_code; err_code = central_find_in_db(p_ble_evt->evt.gap_evt.params.sec_info_request.div); if (err_code == NRF_SUCCESS) { // Bond information has been found and loaded for security procedures. Reflect this in the // status variable m_bond_loaded = true; // Central found in the list of bonded central. Use the encryption info for this central. err_code = sd_ble_gap_sec_info_reply(m_conn_handle, &m_central.bond.auth_status.periph_keys.enc_info, NULL); if (err_code != NRF_SUCCESS) { m_bondmngr_config.error_handler(err_code); } // Do not set the sys_attr yet, should be set only when sec_update is successful. } else if (err_code == NRF_ERROR_NOT_FOUND) { m_central.bond.central_id_info = p_ble_evt->evt.gap_evt.params.sec_info_request; // New central. err_code = sd_ble_gap_sec_info_reply(m_conn_handle, NULL, NULL); if (err_code != NRF_SUCCESS) { m_bondmngr_config.error_handler(err_code); } // Initialize the sys_attr. err_code = sd_ble_gatts_sys_attr_set(m_conn_handle, NULL, 0); } if (err_code != NRF_SUCCESS) { m_bondmngr_config.error_handler(err_code); } } /**@brief Function for handling the Connection Security Update event received from the BLE * stack. * * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_sec_update(ble_gap_evt_conn_sec_update_t * p_sec_update) { uint8_t security_mode = p_sec_update->conn_sec.sec_mode.sm; uint8_t security_level = p_sec_update->conn_sec.sec_mode.lv; if (((security_mode == 1) && (security_level > 1)) || ((security_mode == 2) && (security_level != 0))) { ENCRYPTION_STATUS_SET(); uint32_t err_code = central_sys_attr_set(&m_central); if (err_code != NRF_SUCCESS) { m_bondmngr_config.error_handler(err_code); } else { m_sys_attr_loaded = true; } if (m_bondmngr_config.evt_handler != NULL) { ble_bondmngr_evt_t evt; evt.evt_type = BLE_BONDMNGR_EVT_ENCRYPTED; evt.central_handle = m_central.bond.central_handle; evt.central_id = m_central.bond.central_id_info.div; m_bondmngr_config.evt_handler(&evt); } } } /**@brief Function for handling the Connection Security Parameters Request event received from * the BLE stack. * * @param[in] p_ble_evt Event received from the BLE stack. */ static void on_sec_param_request(ble_gap_evt_sec_params_request_t * p_sec_update) { if (p_sec_update->peer_params.bond) { BONDING_IN_PROGRESS_STATUS_SET(); if (m_central.bond.central_handle != INVALID_CENTRAL_HANDLE) { // Bonding request received from a bonded central, make all system attributes null m_central.sys_attr.sys_attr_size = 0; memset(m_central.sys_attr.sys_attr, 0, SYS_ATTR_BUFFER_MAX_LEN); } } } void ble_bondmngr_on_ble_evt(ble_evt_t * p_ble_evt) { if (!m_is_bondmngr_initialized) { m_bondmngr_config.error_handler(NRF_ERROR_INVALID_STATE); } switch (p_ble_evt->header.evt_id) { case BLE_GAP_EVT_CONNECTED: on_connect(p_ble_evt); break; // NOTE: All actions to be taken on the Disconnected event are performed in // ble_bondmngr_bonded_centrals_store(). This function must be called from the // Disconnected handler of the application before advertising is restarted (to make // sure the flash blocks are cleared while the radio is inactive). case BLE_GAP_EVT_DISCONNECTED: SECURITY_STATUS_RESET(); break; case BLE_GATTS_EVT_SYS_ATTR_MISSING: on_sys_attr_missing(p_ble_evt); break; case BLE_GAP_EVT_AUTH_STATUS: on_auth_status(&p_ble_evt->evt.gap_evt.params.auth_status); break; case BLE_GAP_EVT_SEC_INFO_REQUEST: on_sec_info_request(p_ble_evt); break; case BLE_GAP_EVT_SEC_PARAMS_REQUEST: on_sec_param_request(&p_ble_evt->evt.gap_evt.params.sec_params_request); break; case BLE_GAP_EVT_CONN_SEC_UPDATE: on_sec_update(&p_ble_evt->evt.gap_evt.params.conn_sec_update); break; default: // No implementation needed. break; } } uint32_t ble_bondmngr_bonded_centrals_store(void) { uint32_t err_code; int i; VERIFY_MODULE_INITIALIZED(); if (m_central.bond.central_handle != INVALID_CENTRAL_HANDLE) { // Fetch System Attributes from stack. uint16_t sys_attr_size = SYS_ATTR_BUFFER_MAX_LEN; err_code = sd_ble_gatts_sys_attr_get(m_conn_handle, m_central.sys_attr.sys_attr, &sys_attr_size); if (err_code != NRF_SUCCESS) { return err_code; } m_central.sys_attr.central_handle = m_central.bond.central_handle; m_central.sys_attr.sys_attr_size = (uint16_t)sys_attr_size; // Update the current central. err_code = central_update(); if (err_code != NRF_SUCCESS) { return err_code; } } // Save Bonding Information if changed. if (bond_info_changed()) { // Erase flash page. err_code = pstorage_clear(&mp_flash_bond_info,MAX_BONDS_IN_FLASH); if (err_code != NRF_SUCCESS) { return err_code; } // Store bond information for all centrals. m_bond_info_in_flash_count = 0; for (i = 0; i < m_centrals_in_db_count; i++) { err_code = bond_info_store(&m_centrals_db[i].bond); if (err_code != NRF_SUCCESS) { return err_code; } } } // Save System Attributes, if changed. if (sys_attr_changed()) { // Erase flash page. err_code = pstorage_clear(&mp_flash_sys_attr, MAX_BONDS_IN_FLASH); if (err_code != NRF_SUCCESS) { return err_code; } // Store System Attributes for all centrals. m_sys_attr_in_flash_count = 0; for (i = 0; i < m_centrals_in_db_count; i++) { err_code = sys_attr_store(&m_centrals_db[i].sys_attr); if (err_code != NRF_SUCCESS) { return err_code; } } } m_conn_handle = BLE_CONN_HANDLE_INVALID; m_central.bond.central_handle = INVALID_CENTRAL_HANDLE; m_central.sys_attr.central_handle = INVALID_CENTRAL_HANDLE; m_central.sys_attr.sys_attr_size = 0; m_bond_loaded = false; m_sys_attr_loaded = false; return NRF_SUCCESS; } uint32_t ble_bondmngr_sys_attr_store(void) { uint32_t err_code; if (m_central.sys_attr.sys_attr_size == 0) { // Connected to new central. So the flash block for System Attributes for this // central is empty. Hence no erase is needed. uint16_t sys_attr_size = SYS_ATTR_BUFFER_MAX_LEN; // Fetch System Attributes from stack. err_code = sd_ble_gatts_sys_attr_get(m_conn_handle, m_central.sys_attr.sys_attr, &sys_attr_size); if (err_code != NRF_SUCCESS) { return err_code; } m_central.sys_attr.central_handle = m_central.bond.central_handle; m_central.sys_attr.sys_attr_size = (uint16_t)sys_attr_size; // Copy the System Attributes to database. m_centrals_db[m_central.bond.central_handle].sys_attr = m_central.sys_attr; // Write new central's System Attributes to flash. return (sys_attr_store(&m_central.sys_attr)); } else { // Will not write to flash because System Attributes of an old central would already be // in flash and so this operation needs a flash erase operation. return NRF_ERROR_INVALID_STATE; } } uint32_t ble_bondmngr_bonded_centrals_delete(void) { VERIFY_MODULE_INITIALIZED(); m_centrals_in_db_count = 0; m_bond_info_in_flash_count = 0; m_sys_attr_in_flash_count = 0; return flash_pages_erase(); } uint32_t ble_bondmngr_central_addr_get(int8_t central_handle, ble_gap_addr_t * p_central_addr) { if ( (central_handle == INVALID_CENTRAL_HANDLE) || (central_handle >= m_centrals_in_db_count) || (p_central_addr == NULL) || ( m_centrals_db[central_handle].bond.central_addr.addr_type == BLE_GAP_ADDR_TYPE_RANDOM_PRIVATE_RESOLVABLE ) ) { return NRF_ERROR_INVALID_PARAM; } *p_central_addr = m_centrals_db[central_handle].bond.central_addr; return NRF_SUCCESS; } uint32_t ble_bondmngr_whitelist_get(ble_gap_whitelist_t * p_whitelist) { static ble_gap_addr_t * s_addr[MAX_NUM_CENTRAL_WHITE_LIST]; static ble_gap_irk_t * s_irk[MAX_NUM_CENTRAL_WHITE_LIST]; int i; for (i = 0; i < m_irk_count; i++) { s_irk[i] = m_whitelist_irk[i].p_irk; } for (i = 0; i < m_addr_count; i++) { s_addr[i] = m_whitelist_addr[i].p_addr; } p_whitelist->addr_count = m_addr_count; p_whitelist->pp_addrs = (m_addr_count != 0) ? s_addr : NULL; p_whitelist->irk_count = m_irk_count; p_whitelist->pp_irks = (m_irk_count != 0) ? s_irk : NULL; return NRF_SUCCESS; } static void bm_pstorage_cb_handler(pstorage_handle_t * handle, uint8_t op_code, uint32_t result, uint8_t * p_data, uint32_t data_len) { if (result != NRF_SUCCESS) { m_bondmngr_config.error_handler(result); } } uint32_t ble_bondmngr_init(ble_bondmngr_init_t * p_init) { pstorage_module_param_t param; uint32_t err_code; if (p_init->error_handler == NULL) { return NRF_ERROR_INVALID_PARAM; } if (BLE_BONDMNGR_MAX_BONDED_CENTRALS > MAX_BONDS_IN_FLASH) { return NRF_ERROR_DATA_SIZE; } param.block_size = sizeof (central_bond_t) + sizeof (uint32_t); param.block_count = MAX_BONDS_IN_FLASH; param.cb = bm_pstorage_cb_handler; // Blocks are requested twice, once for bond information and once for system attributes. // The number of blocks requested has to be the maximum number of bonded devices that // need to be supported. However, the size of blocks can be different if the sizes of // system attributes and bonds are not too close. err_code = pstorage_register(&param, &mp_flash_bond_info); if (err_code != NRF_SUCCESS) { return err_code; } param.block_size = sizeof(central_sys_attr_t) + sizeof(uint32_t); err_code = pstorage_register(&param, &mp_flash_sys_attr); if (err_code != NRF_SUCCESS) { return err_code; } m_bondmngr_config = *p_init; memset(&m_central, 0, sizeof(central_t)); m_central.bond.central_handle = INVALID_CENTRAL_HANDLE; m_conn_handle = BLE_CONN_HANDLE_INVALID; m_centrals_in_db_count = 0; m_bond_info_in_flash_count = 0; m_sys_attr_in_flash_count = 0; SECURITY_STATUS_RESET(); // Erase all stored centrals if specified. if (m_bondmngr_config.bonds_delete) { err_code = flash_pages_erase(); if (err_code != NRF_SUCCESS) { return err_code; } m_centrals_in_db_count = 0; int i; for (i = m_centrals_in_db_count; i < BLE_BONDMNGR_MAX_BONDED_CENTRALS; i++) { m_centrals_db[i].bond.central_handle = INVALID_CENTRAL_HANDLE; m_centrals_db[i].sys_attr.sys_attr_size = 0; m_centrals_db[i].sys_attr.central_handle = INVALID_CENTRAL_HANDLE; } } else { // Load bond manager data from flash. err_code = load_all_from_flash(); if (err_code != NRF_SUCCESS) { return err_code; } } m_is_bondmngr_initialized = true; return NRF_SUCCESS; } uint32_t ble_bondmngr_central_ids_get(uint16_t * p_central_ids, uint16_t * p_length) { VERIFY_MODULE_INITIALIZED(); int i; if (p_length == NULL) { return NRF_ERROR_NULL; } if (*p_length < m_centrals_in_db_count) { // Length of the input array is not enough to fit all known central identifiers. return NRF_ERROR_DATA_SIZE; } *p_length = m_centrals_in_db_count; if (p_central_ids == NULL) { // Only the length field was required to be filled. return NRF_SUCCESS; } for (i = 0; i < m_centrals_in_db_count; i++) { p_central_ids[i] = m_centrals_db[i].bond.central_id_info.div; } return NRF_SUCCESS; } uint32_t ble_bondmngr_bonded_central_delete(uint16_t central_id) { VERIFY_MODULE_INITIALIZED(); int8_t central_handle_to_be_deleted = INVALID_CENTRAL_HANDLE; uint8_t i; // Search for the handle of the central. for (i = 0; i < m_centrals_in_db_count; i++) { if (m_centrals_db[i].bond.central_id_info.div == central_id) { central_handle_to_be_deleted = i; break; } } if (central_handle_to_be_deleted == INVALID_CENTRAL_HANDLE) { // Central ID not found. return NRF_ERROR_NOT_FOUND; } // Delete the central in RAM. for (i = central_handle_to_be_deleted; i < (m_centrals_in_db_count - 1); i++) { // Overwrite the current central entry with the next one. m_centrals_db[i] = m_centrals_db[i + 1]; // Decrement the value of handle. m_centrals_db[i].bond.central_handle--; if (INVALID_CENTRAL_HANDLE != m_centrals_db[i].sys_attr.central_handle) { m_centrals_db[i].sys_attr.central_handle--; } } // Clear the last database entry. memset(&(m_centrals_db[m_centrals_in_db_count - 1]), 0, sizeof(central_t)); m_centrals_in_db_count--; uint32_t err_code; // Reinitialize the pointers to the memory where bonding info and System Attributes are stored // in flash. // Refresh the data in the flash memory (both Bonding Information and System Attributes). // Erase and rewrite bonding info and System Attributes. err_code = flash_pages_erase(); if (err_code != NRF_SUCCESS) { return err_code; } m_bond_info_in_flash_count = 0; m_sys_attr_in_flash_count = 0; for (i = 0; i < m_centrals_in_db_count; i++) { err_code = bond_info_store(&(m_centrals_db[i].bond)); if (err_code != NRF_SUCCESS) { return err_code; } } for (i = 0; i < m_centrals_in_db_count; i++) { err_code = sys_attr_store(&(m_centrals_db[i].sys_attr)); if (err_code != NRF_SUCCESS) { return err_code; } } update_whitelist(); return NRF_SUCCESS; } uint32_t ble_bondmngr_is_link_encrypted (bool * status) { VERIFY_MODULE_INITIALIZED(); (*status) = ENCRYPTION_STATUS_GET(); return NRF_SUCCESS; }
33.175549
234
0.594349
hakehuang
2697c546ea3da0d71d51f7cd8512991e28feccbc
646
cpp
C++
src/215.kth_largest_element_in_an_array/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2016-07-02T17:44:10.000Z
2016-07-02T17:44:10.000Z
src/215.kth_largest_element_in_an_array/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
null
null
null
src/215.kth_largest_element_in_an_array/code.cpp
cloudzfy/leetcode
9d32090429ef297e1f62877382bff582d247266a
[ "MIT" ]
1
2019-12-21T04:57:15.000Z
2019-12-21T04:57:15.000Z
class Solution { public: int findKthLargest(vector<int>& nums, int k) { int left = 0, right = nums.size() - 1; while (left < right) { int pivot = nums[left]; int i = left, j = right; while (i < j) { while (i < j && nums[j] < pivot) j--; nums[i] = nums[j]; while (i < j && nums[i] >= pivot) i++; nums[j] = nums[i]; } nums[i] = pivot; if (i == k - 1) return nums[i]; else if (i < k - 1) left = i + 1; else right = i - 1; } return nums[k - 1]; } };
29.363636
54
0.380805
cloudzfy
269d05c443de786d7da37be9593012adcfb37aa9
828
cpp
C++
Regression_test/examples/threshold/src/threshold.cpp
minseongg/dynamatic
268d97690f128569da46e4f39a99346e93ee9d4e
[ "MIT" ]
46
2019-11-16T13:44:07.000Z
2022-03-12T14:28:44.000Z
Regression_test/examples/threshold/src/threshold.cpp
minseongg/dynamatic
268d97690f128569da46e4f39a99346e93ee9d4e
[ "MIT" ]
11
2020-05-12T17:20:51.000Z
2022-02-04T10:04:59.000Z
Regression_test/examples/threshold/src/threshold.cpp
minseongg/dynamatic
268d97690f128569da46e4f39a99346e93ee9d4e
[ "MIT" ]
22
2020-02-21T21:33:40.000Z
2022-02-24T06:50:41.000Z
#include <stdlib.h> #include "threshold.h" void threshold(inout_int_t red[1000], inout_int_t green[1000], inout_int_t blue[1000], in_int_t th) { for (int i = 0; i < 1000; i++) { int sum = red[i] + green [i] + blue [i]; if (sum <= th) { red[i] = 0; green [i] = 0; blue [i] = 0; } } } #define AMOUNT_OF_TEST 1 int main(void){ inout_int_t red[AMOUNT_OF_TEST][1000]; inout_int_t green[AMOUNT_OF_TEST][1000]; inout_int_t blue[AMOUNT_OF_TEST][1000]; inout_int_t th[AMOUNT_OF_TEST]; for(int i = 0; i < AMOUNT_OF_TEST; ++i){ th[i] = (rand() % 100); for(int j = 0; j < 1000; ++j){ red[i][j] = (rand() % 100); green[i][j] = (rand() % 100); blue[i][j] = (rand() % 100); } } //for(int i = 0; i < AMOUNT_OF_TEST; ++i){ int i = 0; threshold(red[i], green[i], blue[i], th[i]); //} }
18.818182
101
0.570048
minseongg
269d8a6d9b8f916c3dda647e0ed287f1f9313bef
2,491
cpp
C++
src/io/OutputFile.cpp
feliwir/libcharta
4581ad4dc0751264ed6104a49260e7e070dfc141
[ "Apache-2.0" ]
null
null
null
src/io/OutputFile.cpp
feliwir/libcharta
4581ad4dc0751264ed6104a49260e7e070dfc141
[ "Apache-2.0" ]
8
2021-05-20T11:15:34.000Z
2021-05-21T12:29:48.000Z
src/io/OutputFile.cpp
feliwir/libcharta
4581ad4dc0751264ed6104a49260e7e070dfc141
[ "Apache-2.0" ]
2
2021-05-24T14:43:46.000Z
2021-05-25T08:31:41.000Z
/* Source File : OutputFile.cpp Copyright 2011 Gal Kahana PDFWriter Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "io/OutputFile.h" #include "Trace.h" #include "io/OutputBufferedStream.h" #include "io/OutputFileStream.h" charta::OutputFile::OutputFile() { mOutputStream = nullptr; } charta::OutputFile::~OutputFile() { CloseFile(); } charta::EStatusCode charta::OutputFile::OpenFile(const std::string &inFilePath, bool inAppend) { EStatusCode status; do { status = CloseFile(); if (status != charta::eSuccess) { TRACE_LOG1("charta::OutputFile::OpenFile, Unexpected Failure. Couldn't close previously open file - %s", mFilePath.c_str()); break; } auto outputFileStream = std::make_unique<OutputFileStream>(); status = outputFileStream->Open(inFilePath, inAppend); // explicitly open, so status may be retrieved if (status != charta::eSuccess) { TRACE_LOG1("charta::OutputFile::OpenFile, Unexpected Failure. Cannot open file for writing - %s", inFilePath.c_str()); break; } mOutputStream = new OutputBufferedStream(std::move(outputFileStream)); mFilePath = inFilePath; } while (false); return status; } charta::EStatusCode charta::OutputFile::CloseFile() { if (nullptr == mOutputStream) { return charta::eSuccess; } mOutputStream->Flush(); auto *outputStream = (OutputFileStream *)mOutputStream->GetTargetStream(); EStatusCode status = outputStream->Close(); // explicitly close, so status may be retrieved delete mOutputStream; // will delete the referenced file stream as well mOutputStream = nullptr; return status; } charta::IByteWriterWithPosition *charta::OutputFile::GetOutputStream() { return mOutputStream; } const std::string &charta::OutputFile::GetFilePath() { return mFilePath; }
27.988764
116
0.674428
feliwir
26a0be9f2af8de90d7f9795281eff836adf25290
7,004
hh
C++
src/memo/cli/KeyValueStore.hh
infinit/memo
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
[ "Apache-2.0" ]
124
2017-06-22T19:20:54.000Z
2021-12-23T21:36:37.000Z
src/memo/cli/KeyValueStore.hh
infinit/memo
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
[ "Apache-2.0" ]
4
2017-08-21T15:57:29.000Z
2019-01-10T02:52:35.000Z
src/memo/cli/KeyValueStore.hh
infinit/memo
3a8394d0f647efe03ccb8bfe885a7279cb8be8a6
[ "Apache-2.0" ]
12
2017-06-29T09:15:35.000Z
2020-12-31T12:39:52.000Z
#pragma once #include <elle/das/cli.hh> #include <memo/cli/Object.hh> #include <memo/cli/Mode.hh> #include <memo/cli/fwd.hh> #include <memo/cli/symbols.hh> #include <memo/symbols.hh> namespace memo { namespace cli { class KeyValueStore : public Object<KeyValueStore> { public: using Self = KeyValueStore; KeyValueStore(Memo& cli); using Modes = decltype(elle::meta::list(cli::create, cli::delete_, cli::export_, cli::fetch, cli::import, cli::list, cli::pull, cli::push, cli::run)); using Strings = std::vector<std::string>; /*---------------. | Mode: create. | `---------------*/ Mode<Self, void (decltype(cli::name)::Formal<std::string const&>, decltype(cli::network)::Formal<std::string const&>, decltype(cli::description = boost::optional<std::string>()), decltype(cli::push_key_value_store = false), decltype(cli::output = boost::optional<std::string>()), decltype(cli::push = false)), decltype(modes::mode_create)> create; void mode_create(std::string const& name, std::string const& network, boost::optional<std::string> description = {}, bool push_key_value_store = false, boost::optional<std::string> output = {}, bool push = false); /*---------------. | Mode: delete. | `---------------*/ Mode<Self, void (decltype(cli::name)::Formal<std::string const&>, decltype(cli::pull = false), decltype(cli::purge = false)), decltype(modes::mode_delete)> delete_; void mode_delete(std::string const& name, bool pull, bool purge); /*---------------. | Mode: export. | `---------------*/ Mode<Self, void (decltype(cli::name)::Formal<std::string const&>, decltype(cli::output = boost::optional<std::string>())), decltype(modes::mode_export)> export_; void mode_export(std::string const& volume_name, boost::optional<std::string> const& output_name = {}); /*--------------. | Mode: fetch. | `--------------*/ Mode<Self, void (decltype(cli::name = boost::optional<std::string>()), decltype(cli::network = boost::optional<std::string>())), decltype(modes::mode_fetch)> fetch; void mode_fetch(boost::optional<std::string> volume_name = {}, boost::optional<std::string> network_name = {}); /*---------------. | Mode: import. | `---------------*/ Mode<Self, void (decltype(cli::input = boost::optional<std::string>())), decltype(modes::mode_import)> import; void mode_import(boost::optional<std::string> input_name = {}); /*-------------. | Mode: list. | `-------------*/ Mode<Self, void (), decltype(modes::mode_list)> list; void mode_list(); /*-------------. | Mode: pull. | `-------------*/ Mode<Self, void (decltype(cli::name)::Formal<std::string const&>, decltype(cli::purge = false)), decltype(modes::mode_pull)> pull; void mode_pull(std::string const& name, bool purge = false); /*-------------. | Mode: push. | `-------------*/ Mode<Self, void (decltype(cli::name)::Formal<std::string const&>), decltype(modes::mode_push)> push; void mode_push(std::string const& name); /*------------. | Mode: run. | `------------*/ Mode<Self, void (decltype(cli::name)::Formal<std::string const&>, decltype(cli::grpc)::Formal<std::string const&>, decltype(cli::allow_root_creation = false), decltype(cli::peer = Strings{}), decltype(cli::async = false), decltype(cli::cache = false), decltype(cli::cache_ram_size = boost::optional<int>()), decltype(cli::cache_ram_ttl = boost::optional<int>()), decltype(cli::cache_ram_invalidation = boost::optional<int>()), decltype(cli::cache_disk_size = boost::optional<uint64_t>()), decltype(cli::fetch_endpoints = false), decltype(cli::fetch = false), decltype(cli::push_endpoints = false), decltype(cli::push = false), decltype(cli::publish = false), decltype(cli::endpoints_file = boost::optional<std::string>()), decltype(cli::peers_file = boost::optional<std::string>()), decltype(cli::port = boost::optional<int>()), decltype(cli::listen = boost::optional<std::string>()), decltype(cli::fetch_endpoints_interval = boost::optional<int>()), decltype(cli::no_local_endpoints = false), decltype(cli::no_public_endpoints = false), decltype(cli::advertise_host = Strings{}), decltype(cli::grpc_port_file = boost::optional<std::string>())), decltype(modes::mode_run)> run; void mode_run(std::string const& name, std::string const& grpc, bool allow_root_creation = false, Strings peer = {}, bool async = false, bool cache = false, boost::optional<int> cache_ram_size = {}, boost::optional<int> cache_ram_ttl = {}, boost::optional<int> cache_ram_invalidation = {}, boost::optional<uint64_t> cache_disk_size = {}, bool fetch_endpoints = false, bool fetch = false, bool push_endpoints = false, bool push = false, bool publish = false, boost::optional<std::string> const& endpoint_file = {}, boost::optional<std::string> const& peers_file = {}, boost::optional<int> port = {}, boost::optional<std::string> listen = {}, boost::optional<int> fetch_endpoints_interval = {}, bool no_local_endpoints = false, bool no_public_endpoints = false, Strings advertise_host = {}, boost::optional<std::string> grpc_port_file = {}); }; } }
34.673267
81
0.476442
infinit
26a5fa3870e7d9939e9a10f6124b408b1d15a119
583
cc
C++
src/figureknight.cc
zerozez/qt-chess
4a066195f656cb57e83f49beeaa9e244796b18d3
[ "Apache-2.0" ]
5
2018-05-09T05:09:50.000Z
2021-07-30T06:48:21.000Z
src/figureknight.cc
zerozez/qt-chess
4a066195f656cb57e83f49beeaa9e244796b18d3
[ "Apache-2.0" ]
null
null
null
src/figureknight.cc
zerozez/qt-chess
4a066195f656cb57e83f49beeaa9e244796b18d3
[ "Apache-2.0" ]
5
2017-11-29T23:49:25.000Z
2021-06-10T15:13:07.000Z
#include <movepoints.hpp> #include "figureknight.hpp" FigureKnight::FigureKnight(const uint x, const uint y, FigureIntf::Color side, QObject *parent) : FigureIntf(x, y, side, new MovePoints(), parent) { MovePoints *points = defMoveList(); points->addPoint(2, 1); points->addPoint(2, -1); points->addPoint(-2, 1); points->addPoint(-2, -1); points->addPoint(1, 2); points->addPoint(1, -2); points->addPoint(-1, 2); points->addPoint(-1, -2); points->setCurrent(x, y); } QString FigureKnight::imagePath() const { return s_path; }
24.291667
78
0.636364
zerozez
26a889910b55f98ee3c9093b47d7d9cc2bf7dd96
1,251
cpp
C++
src/Engine/Material/BSDF_CookTorrance.cpp
trygas/CGHomework
2dfff76f407b8a7ba87c5ba9d12a4428708ffbbe
[ "MIT" ]
289
2020-01-28T09:07:10.000Z
2022-03-25T09:00:25.000Z
src/Engine/Material/BSDF_CookTorrance.cpp
Ricahrd-Li/ASAP_ARAP_Parameterization
c12d83605ce9ea9cac29efbd991d21e2b363e375
[ "MIT" ]
12
2020-02-19T07:11:14.000Z
2021-08-07T06:41:27.000Z
src/Engine/Material/BSDF_CookTorrance.cpp
Ricahrd-Li/ASAP_ARAP_Parameterization
c12d83605ce9ea9cac29efbd991d21e2b363e375
[ "MIT" ]
249
2020-02-01T08:14:36.000Z
2022-03-30T14:52:58.000Z
#include <Engine/Material/BSDF_CookTorrance.h> #include <Basic/Math.h> using namespace Ubpa; using namespace std; float BSDF_CookTorrance::NDF(const normalf & h) { cout << "WARNING::BSDF_CookTorrance:" << endl << "\t" << "not implemented" << endl; return 0.f; } float BSDF_CookTorrance::Fr(const normalf & wi, const normalf & h) { cout << "WARNING::BSDF_CookTorrance:" << endl << "\t" << "not implemented" << endl; return 0.f; } float BSDF_CookTorrance::G(const normalf & wo, const normalf & wi, const normalf & h){ cout << "WARNING::BSDF_CookTorrance:" << endl << "\t" << "not implemented" << endl; return 0.f; } const rgbf BSDF_CookTorrance::F(const normalf & wo, const normalf & wi, const pointf2 & texcoord) { cout << "WARNING::BSDF_CookTorrance:" << endl << "\t" << "not implemented" << endl; return 0.f; } float BSDF_CookTorrance::PDF(const normalf & wo, const normalf & wi, const pointf2 & texcoord) { cout << "WARNING::BSDF_CookTorrance:" << endl << "\t" << "not implemented" << endl; return 0.f; } const rgbf BSDF_CookTorrance::Sample_f(const normalf & wo, const pointf2 & texcoord, normalf & wi, float & pd) { cout << "WARNING::BSDF_CookTorrance:" << endl << "\t" << "not implemented" << endl; return 0.f; }
28.431818
112
0.663469
trygas
26aaca0b24611b659b37f098826c03e808543bb7
1,148
cpp
C++
libs/liblynel/test/src/lynel/matrix.cpp
tybl/tybl
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
[ "Unlicense" ]
1
2022-02-11T21:25:53.000Z
2022-02-11T21:25:53.000Z
libs/liblynel/test/src/lynel/matrix.cpp
tybl/tybl
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
[ "Unlicense" ]
15
2021-08-21T13:41:29.000Z
2022-03-08T14:13:43.000Z
libs/liblynel/test/src/lynel/matrix.cpp
tybl/tybl
cc74416d3d982177d46b89c0ca44f3a8e1cf00d6
[ "Unlicense" ]
null
null
null
// License: The Unlicense (https://unlicense.org) #include "lynel/matrix.hpp" #include <doctest/doctest.h> using namespace tybl::lynel; TEST_CASE("matrix::operator==()") { matrix<double,3,3> a = { 0,1,2,3,4,5,6,7,8 }; matrix<double,3,3> b = { 0,1,2,3,4,5,6,7,8 }; matrix<double,3,3> c = { 1,1,2,3,4,5,6,7,8 }; matrix<double,3,3> d = { 0,1,2,3,4,5,6,7,9 }; CHECK(a == a); CHECK(a == b); CHECK(!(a == c)); CHECK(!(b == d)); } TEST_CASE("aggregate initialization and correct positional assignment of values") { // NOLINT matrix<double,3,3> m = { 0,1,2,3,4,5,6,7,8 }; CHECK(m(0,0) == 0.0); CHECK(m(0,1) == 1.0); CHECK(m(0,2) == 2.0); CHECK(m(1,0) == 3.0); CHECK(m(1,1) == 4.0); CHECK(m(1,2) == 5.0); CHECK(m(2,0) == 6.0); CHECK(m(2,1) == 7.0); CHECK(m(2,2) == 8.0); } TEST_CASE("scalar multiplication") { matrix<double,3,3> m = { 0,1,2, 3,4,5, 6,7,8 }; matrix<double,3,3> a = { 0,2,4,6,8,10,12,14,16 }; m *= 2.0; CHECK(a == m); } TEST_CASE("transpose 3x3") { matrix<double,3,3> m = { 0,1,2,3,4,5,6,7,8 }; matrix<double,3,3> mt = { 0,3,6,1,4,7,2,5,8 }; auto n = transpose(m); CHECK(n == mt); }
24.956522
93
0.542683
tybl
26ac80c078b14510e88e45ebc37e3e0029bcbe72
213
cpp
C++
leetcode.com/0912 Sort an Array/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2020-08-20T11:02:49.000Z
2020-08-20T11:02:49.000Z
leetcode.com/0912 Sort an Array/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
null
null
null
leetcode.com/0912 Sort an Array/main.cpp
sky-bro/AC
29bfa3f13994612887e18065fa6e854b9a29633d
[ "MIT" ]
1
2022-01-01T23:23:13.000Z
2022-01-01T23:23:13.000Z
#include <algorithm> #include <iostream> #include <vector> using namespace std; class Solution { public: vector<int> sortArray(vector<int>& nums) { sort(nums.begin(), nums.end()); return nums; } };
15.214286
44
0.661972
sky-bro
26adb3d9943b8ee8a33b935fe87e6ad5d0233046
4,140
hpp
C++
image/globals.hpp
mywoodstock/woo
7a6e39b2914ec8ff5bf52c3aa5217214532390e4
[ "BSL-1.0" ]
1
2017-05-09T14:25:18.000Z
2017-05-09T14:25:18.000Z
image/globals.hpp
mywoodstock/woo
7a6e39b2914ec8ff5bf52c3aa5217214532390e4
[ "BSL-1.0" ]
null
null
null
image/globals.hpp
mywoodstock/woo
7a6e39b2914ec8ff5bf52c3aa5217214532390e4
[ "BSL-1.0" ]
null
null
null
/** * Project: The Stock Libraries * * File: globals.hpp * Created: Jun 05, 2012 * * Author: Abhinav Sarje <[email protected]> * * Copyright (c) 2012-2017 Abhinav Sarje * Distributed under the Boost Software License. * See accompanying LICENSE file. */ #ifndef __GLOBALS_HPP__ #define __GLOBALS_HPP__ #include <boost/array.hpp> #include <vector> #include <cmath> #include "typedefs.hpp" namespace stock { typedef struct vector2_t { boost::array <real_t, 2> vec_; /* constructors */ vector2_t() { vec_[0] = 0; vec_[1] = 0; } // vector2_t() vector2_t(real_t a, real_t b) { vec_[0] = a; vec_[1] = b; } // vector2_t() vector2_t(vector2_t& a) { vec_[0] = a[0]; vec_[1] = a[1]; } // vector2_t() vector2_t(const vector2_t& a) { vec_ = a.vec_; } // vector2_t() /* operators */ vector2_t& operator=(const vector2_t& a) { vec_ = a.vec_; return *this; } // operator= vector2_t& operator=(vector2_t& a) { vec_ = a.vec_; return *this; } // operator= real_t& operator[](int i) { return vec_[i]; } // operator[] } vector2_t; typedef struct vector3_t { boost::array <real_t, 3> vec_; /* constructors */ vector3_t() { vec_[0] = 0; vec_[1] = 0; vec_[2] = 0; } // vector3_t() vector3_t(real_t a, real_t b, real_t c) { vec_[0] = a; vec_[1] = b; vec_[2] = c; } // vector3_t() vector3_t(vector3_t& a) { vec_[0] = a[0]; vec_[1] = a[1]; vec_[2] = a[2]; } // vector3_t() vector3_t(const vector3_t& a) { vec_ = a.vec_; } // vector3_t() /* operators */ vector3_t& operator=(const vector3_t& a) { vec_ = a.vec_; return *this; } // operator= vector3_t& operator=(vector3_t& a) { vec_ = a.vec_; return *this; } // operator= real_t& operator[](int i) { return vec_[i]; } // operator[] vector3_t operator+(int toadd) { return vector3_t(vec_[0] + toadd, vec_[1] + toadd, vec_[2] + toadd); } // operator+() vector3_t operator+(vector3_t toadd) { return vector3_t(vec_[0] + toadd[0], vec_[1] + toadd[1], vec_[2] + toadd[2]); } // operator+() vector3_t operator-(int tosub) { return vector3_t(vec_[0] - tosub, vec_[1] - tosub, vec_[2] - tosub); } // operator-() vector3_t operator-(vector3_t tosub) { return vector3_t(vec_[0] - tosub[0], vec_[1] - tosub[1], vec_[2] - tosub[2]); } // operator-() vector3_t operator/(vector3_t todiv) { return vector3_t(vec_[0] / todiv[0], vec_[1] / todiv[1], vec_[2] / todiv[2]); } // operator/() } vector3_t; typedef struct matrix3x3_t { typedef boost::array<real_t, 3> mat3_t; mat3_t mat_[3]; /* constructors */ matrix3x3_t() { for(int i = 0; i < 3; ++ i) for(int j = 0; j < 3; ++ j) mat_[i][j] = 0.0; } // matrix3x3_t() matrix3x3_t(const matrix3x3_t& a) { mat_[0] = a.mat_[0]; mat_[1] = a.mat_[1]; mat_[2] = a.mat_[2]; } // matrix3x3_t /* operators */ mat3_t& operator[](unsigned int index) { return mat_[index]; } // operator[]() mat3_t& operator[](int index) { return mat_[index]; } // operator[]() matrix3x3_t& operator=(matrix3x3_t& a) { for(int i = 0; i < 3; ++ i) for(int j = 0; j < 3; ++ j) mat_[i][j] = a[i][j]; return *this; } // operstor=() matrix3x3_t operator+(int toadd) { matrix3x3_t sum; for(int i = 0; i < 3; ++ i) for(int j = 0; j < 3; ++ j) sum.mat_[i][j] = mat_[i][j] + toadd; return sum; } // operator+() matrix3x3_t operator+(matrix3x3_t& toadd) { matrix3x3_t sum; for(int i = 0; i < 3; ++ i) for(int j = 0; j < 3; ++ j) sum.mat_[i][j] = mat_[i][j] + toadd[i][j]; return sum; } // operator+() matrix3x3_t operator*(int tomul) { matrix3x3_t prod; for(int i = 0; i < 3; ++ i) for(int j = 0; j < 3; ++ j) prod.mat_[i][j] = mat_[i][j] * tomul; return prod; } // operator*() matrix3x3_t operator*(matrix3x3_t& tomul) { matrix3x3_t prod; for(int i = 0; i < 3; ++ i) for(int j = 0; j < 3; ++ j) prod.mat_[i][j] = mat_[i][j] * tomul[i][j]; return prod; } // operator*() } matrix3x3_t; } // namespace stock #endif /* __GLOBALS_HPP__ */
21.122449
80
0.572464
mywoodstock
26aed0a38df84b58cd7c72fdc67a16f3eda0840d
1,424
cpp
C++
aws-cpp-sdk-proton/source/model/ListRepositorySyncDefinitionsResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-proton/source/model/ListRepositorySyncDefinitionsResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-proton/source/model/ListRepositorySyncDefinitionsResult.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/proton/model/ListRepositorySyncDefinitionsResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::Proton::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListRepositorySyncDefinitionsResult::ListRepositorySyncDefinitionsResult() { } ListRepositorySyncDefinitionsResult::ListRepositorySyncDefinitionsResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListRepositorySyncDefinitionsResult& ListRepositorySyncDefinitionsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("nextToken")) { m_nextToken = jsonValue.GetString("nextToken"); } if(jsonValue.ValueExists("syncDefinitions")) { Array<JsonView> syncDefinitionsJsonList = jsonValue.GetArray("syncDefinitions"); for(unsigned syncDefinitionsIndex = 0; syncDefinitionsIndex < syncDefinitionsJsonList.GetLength(); ++syncDefinitionsIndex) { m_syncDefinitions.push_back(syncDefinitionsJsonList[syncDefinitionsIndex].AsObject()); } } return *this; }
28.48
138
0.778792
perfectrecall
565489757ce1fd9e8bd5ab39a63f70b20df0e50f
4,838
cc
C++
xapian/xapian-core-1.2.13/backends/flint/flint_termlisttable.cc
pgs7179/xapian_modified
0229c9efb9eca19be4c9f463cd4b793672f24198
[ "MIT" ]
2
2021-01-13T21:17:42.000Z
2021-01-13T21:17:42.000Z
xapian/xapian-core-1.2.13/backends/flint/flint_termlisttable.cc
Loslove55/tailbench
fbbf3f31e3f0af1bb7db7f07c2e7193b84abb1eb
[ "MIT" ]
null
null
null
xapian/xapian-core-1.2.13/backends/flint/flint_termlisttable.cc
Loslove55/tailbench
fbbf3f31e3f0af1bb7db7f07c2e7193b84abb1eb
[ "MIT" ]
null
null
null
/** @file flint_termlisttable.cc * @brief Subclass of FlintTable which holds termlists. */ /* Copyright (C) 2007,2008 Olly Betts * * 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 2 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., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #include <config.h> #include <xapian/document.h> #include <xapian/error.h> #include <xapian/termiterator.h> #include "flint_termlisttable.h" #include "flint_utils.h" #include "debuglog.h" #include "omassert.h" #include "str.h" #include "stringutils.h" #include <string> using namespace std; void FlintTermListTable::set_termlist(Xapian::docid did, const Xapian::Document & doc, flint_doclen_t doclen) { LOGCALL_VOID(DB, "FlintTermListTable::set_termlist", did | doc | doclen); Xapian::doccount termlist_size = doc.termlist_count(); if (termlist_size == 0) { // doclen is sum(wdf) so should be zero if there are no terms. Assert(doclen == 0); Assert(doc.termlist_begin() == doc.termlist_end()); add(flint_docid_to_key(did), string()); return; } string tag = F_pack_uint(doclen); Xapian::TermIterator t = doc.termlist_begin(); if (t != doc.termlist_end()) { tag += F_pack_uint(termlist_size); string prev_term = *t; // Previous database versions encoded a boolean here, which was // always false (and F_pack_bool() encodes false as a '0'). We can // just omit this and successfully read old and new termlists // except in the case where the next byte is a '0' - in this case // we need keep the '0' so that the decoder can just skip any '0' // it sees in this position (this shouldn't be a common case - 48 // character terms aren't very common, and the first term // alphabetically is likely to be shorter than average). if (prev_term.size() == '0') tag += '0'; tag += char(prev_term.size()); tag += prev_term; tag += F_pack_uint(t.get_wdf()); --termlist_size; while (++t != doc.termlist_end()) { const string & term = *t; // If there's a shared prefix with the previous term, we don't // store it explicitly, but just store the length of the shared // prefix. In general, this is a big win. size_t reuse = common_prefix_length(prev_term, term); // reuse must be <= prev_term.size(), and we know that value while // decoding. So if the wdf is small enough that we can multiply it // by (prev_term.size() + 1), add reuse and fit the result in a // byte, then we can pack reuse and the wdf into a single byte and // save ourselves a byte. We actually need to add one to the wdf // before multiplying so that a wdf of 0 can be detected by the // decoder. size_t packed = 0; Xapian::termcount wdf = t.get_wdf(); // If wdf >= 128, then we aren't going to be able to pack it in so // don't even try to avoid the calculation overflowing and making // us think we can. if (wdf < 127) packed = (wdf + 1) * (prev_term.size() + 1) + reuse; if (packed && packed < 256) { // We can pack the wdf into the same byte. tag += char(packed); tag += char(term.size() - reuse); tag.append(term.data() + reuse, term.size() - reuse); } else { tag += char(reuse); tag += char(term.size() - reuse); tag.append(term.data() + reuse, term.size() - reuse); // FIXME: pack wdf after reuse next time we rejig the format // incompatibly. tag += F_pack_uint(wdf); } prev_term = *t; --termlist_size; } } Assert(termlist_size == 0); add(flint_docid_to_key(did), tag); } flint_doclen_t FlintTermListTable::get_doclength(Xapian::docid did) const { LOGCALL(DB, flint_doclen_t, "FlintTermListTable::get_doclength", did); string tag; if (!get_exact_entry(flint_docid_to_key(did), tag)) throw Xapian::DocNotFoundError("No termlist found for document " + str(did)); if (tag.empty()) RETURN(0); const char * pos = tag.data(); const char * end = pos + tag.size(); flint_doclen_t doclen; if (!F_unpack_uint(&pos, end, &doclen)) { const char *msg; if (pos == 0) { msg = "Too little data for doclen in termlist"; } else { msg = "Overflowed value for doclen in termlist"; } throw Xapian::DatabaseCorruptError(msg); } RETURN(doclen); }
32.689189
77
0.673419
pgs7179
56552f854b8b9d39c69acb10804e90e7397e6248
3,101
cpp
C++
CODEJAM/2014/ROUND1C/b.cpp
henviso/contests
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
[ "Apache-2.0" ]
null
null
null
CODEJAM/2014/ROUND1C/b.cpp
henviso/contests
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
[ "Apache-2.0" ]
null
null
null
CODEJAM/2014/ROUND1C/b.cpp
henviso/contests
aa8a5ce9ed4524e6c3130ee73af7640e5a86954c
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cstdio> #include <string> #include <cstring> #include <cstdlib> #include <stack> #include <algorithm> #include <cctype> #include <vector> #include <queue> #include <tr1/unordered_map> #include <cmath> #include <map> #include <bitset> #include <set> using namespace std; typedef long long ll; typedef unsigned long long ull; typedef vector<int> vi; typedef pair<int,int> ii; typedef vector< ii > vii; ///////////////////////////////UTIL///////////////////////////////// #define ALL(x) (x).begin(),x.end() #define CLEAR0(v) memset(v, 0, sizeof(v)) #define CLEAR(v, x) memset(v, x, sizeof(v)) #define IN0(x, n) ((x) > -1 && (x) < n) #define IN(x, a, b) ((x) >= a && (x) <= b) #define COPY(a, b) memcpy(a, b, sizeof(a)) #define CMP(a, b) memcmp(a, b, sizeof(a)) #define REP(i,n) for(int i = 0; i<n; i++) #define REPP(i,a,n) for(int i = a; i<n; i++) #define REPD(i,n) for(int i = n-1; i>-1; i--) #define REPDP(i,a,n) for(int i = n-1; i>=a; i--) #define pb push_back #define pf push_front #define sz size() #define mp make_pair /////////////////////////////NUMERICAL////////////////////////////// #define INCMOD(a,b,c) (((a)+b)%c) #define DECMOD(a,b,c) (((a)+c-b)%c) #define ROUNDINT(a) (int)((double)(a) + 0.5) #define INF 0x3f3f3f3f #define EPS 1e-9 /////////////////////////////BITWISE//////////////////////////////// #define CHECK(S, j) (S & (1 << j)) #define CHECKFIRST(S) (S & (-S)) //PRECISA DE UMA TABELA PARA TRANSFORMAR EM INDICE #define SET(S, j) S |= (1 << j) #define SETALL(S, j) S = (1 << j)-1 //J PRIMEIROS #define UNSET(S, j) S &= ~(1 << j) #define TOOGLE(S, j) S ^= (1 << j) ///////////////////////////////64 BITS////////////////////////////// #define LCHECK(S, j) (S & (1ULL << j)) #define LSET(S, j) S |= (1ULL << j) #define LSETALL(S, j) S = (1ULL << j)-1ULL //J PRIMEIROS #define LUNSET(S, j) S &= ~(1ULL << j) #define LTOOGLE(S, j) S ^= (1ULL << j) #define MOD 1000000007LL //__builtin_popcount(m) //scanf(" %d ", &t); typedef unsigned long long hash; string simplify(string &a){ //cout << " STRING A " << a << endl; string res = "$"; int i = 0; while(i < a.length()){ if(a[i] != res[res.length()-1]) res += a[i]; i++; } //cout << " SIMPLIFICADA " << res.substr(1) << endl; return res.substr(1); } bool hasRepeated(string &a){ if(a.length() > 26) return true; bool vis[30]; CLEAR0(vis); REP(i, a.length()){ if(vis[(a[i]-'a')]) return true; vis[(a[i]-'a')] = true; } return false; } bool valid(string &a){ return !hasRepeated(a); } pair<int, string> s[1000]; int N, t; int main(){ cin >> t; REPP(ca, 1, t+1){ cin >> N; ll ans = 1LL; REP(i, N){ cin >> s[i].second; s[i].second = simplify(s[i].second); if(!valid(s[i].second)) ans = 0LL; s[i].first = i; } if(ans == 0LL) cout << "Case #" << ca << ": " << ans << endl; else{ ll ans = 0LL; sort(s, s+N); do{ //cout << " N " << N << endl; string c = ""; REP(i, N) c += s[i].second; c = simplify(c); ans = ((ans+valid(c))%MOD); }while(next_permutation(s, s+N)); cout << "Case #" << ca << ": " << ans << endl; } } }
25.841667
84
0.529507
henviso
56579e54ba5cf939dd05730da3ab5320b8cfbc5b
1,077
cpp
C++
proj-e/tests/internal_test.cpp
romz-pl/b-plus-tree
5af2db1c4188d507d0ff28eac91dc255d4e49a35
[ "Apache-2.0" ]
1
2019-02-01T09:10:11.000Z
2019-02-01T09:10:11.000Z
proj-e/tests/internal_test.cpp
romz-pl/b-plus-tree
5af2db1c4188d507d0ff28eac91dc255d4e49a35
[ "Apache-2.0" ]
3
2017-10-30T07:38:49.000Z
2017-10-30T08:55:50.000Z
proj-e/tests/internal_test.cpp
romz-pl/b-plus-tree
5af2db1c4188d507d0ff28eac91dc255d4e49a35
[ "Apache-2.0" ]
null
null
null
#include <gtest/gtest.h> #include <internal.h> // // // TEST(Internal, init) { using Key = int; using Data = int; btree::Internal< Key, Data > internal( nullptr ); const Key key = 2; const Data data = 3; const btree::Leaf< Key, Data >::value_type x( key, data ); internal.insert_value( 0, x ); EXPECT_EQ( internal.value( 0 ), x ); EXPECT_EQ( internal.count( ), 1U ); btree::Internal< Key, Data > c0( nullptr ); btree::Internal< Key, Data > c1( nullptr ); internal.set_child( 0, &c0 ); internal.set_child( 1, &c1 ); const btree::Leaf< Key, Data >::value_type y( key + 1, data + 1 ); internal.insert_value( 0, y ); EXPECT_EQ( internal.value( 0 ), y ); EXPECT_EQ( internal.value( 1 ), x ); EXPECT_EQ( internal.count( ), 2U ); btree::Internal< Key, Data > c2( nullptr ); internal.set_child( 1, &c2 ); internal.remove_value( 0 ); EXPECT_EQ( internal.value( 0 ), x ); EXPECT_EQ( internal.count( ), 1U ); internal.remove_value( 0 ); EXPECT_EQ( internal.count( ), 0U ); }
22.914894
70
0.593315
romz-pl
5659f243a4ca9717204ad2bbb3d2d565772ee6ff
1,246
cpp
C++
GameGuy/src/Panels/AudioPanel.cpp
salvorizza/GameGuy
b539d5be002387907fe5d6e6e9da5deae234c182
[ "MIT" ]
null
null
null
GameGuy/src/Panels/AudioPanel.cpp
salvorizza/GameGuy
b539d5be002387907fe5d6e6e9da5deae234c182
[ "MIT" ]
null
null
null
GameGuy/src/Panels/AudioPanel.cpp
salvorizza/GameGuy
b539d5be002387907fe5d6e6e9da5deae234c182
[ "MIT" ]
null
null
null
#include "Panels/AudioPanel.h" #include <imgui.h> namespace GameGuy { AudioPanel::AudioPanel() : Panel("Audio Panel ", false, true) { } AudioPanel::~AudioPanel() { } void AudioPanel::addSample(size_t time, double left, double right) { std::lock_guard<std::mutex> lc(mMutex); if (mSamples.size() > MAX_SAMPLES) mSamples.pop_front(); mSamples.push_back(std::make_tuple(time, left, right)); } void AudioPanel::onImGuiRender() { std::lock_guard<std::mutex> lc(mMutex); ImVec2 pos = ImGui::GetWindowPos(); ImVec2 region = ImGui::GetContentRegionAvail(); ImDrawList* drawList = ImGui::GetWindowDrawList(); float xInc = region.x / MAX_SAMPLES; float amp = region.y / 4; ImVec2 previousPos = { pos.x,pos.y + region.y / 2.0f }; for (auto& sample : mSamples) { ImVec2 currentPos; currentPos.y = pos.y + (region.y / 2) + (std::get<1>(sample) * amp); currentPos.x = previousPos.x + xInc; drawList->AddLine(previousPos, currentPos, ImColor(255,0,0)); previousPos = currentPos; } drawList->AddLine({ pos.x,pos.y + region.y / 2.0f }, { pos.x + region.x,pos.y + region.y / 2.0f }, ImColor(255,255,255, 75)); //drawList->AddRectFilled({ 10,10 }, { 40,40 }, ImColor(255, 255, 255)); } }
22.654545
127
0.654896
salvorizza
565bd4355598dc7147bc724f18a0ae8d4768cb67
5,842
cpp
C++
client/Client.cpp
MohamedAshrafTolba/http-client-server
3776f1a5ff1921564d6c288be0ba870dbdacce22
[ "MIT" ]
null
null
null
client/Client.cpp
MohamedAshrafTolba/http-client-server
3776f1a5ff1921564d6c288be0ba870dbdacce22
[ "MIT" ]
null
null
null
client/Client.cpp
MohamedAshrafTolba/http-client-server
3776f1a5ff1921564d6c288be0ba870dbdacce22
[ "MIT" ]
null
null
null
#include "Client.h" #include <sstream> #include <fstream> #include <iostream> #include <thread> #include <mutex> #include <sys/stat.h> #include <condition_variable> #include "../strutil.h" Client::Client(std::string &host_name, std::string &port_number, std::string &requests_file, bool dry_run) { socket = new Socket(host_name, port_number); this->requests_file = requests_file; this->dry_run = dry_run; } Client::~Client() { if (socket != nullptr) { delete socket; } } void Client::run() { std::mutex pipelined_requests_mutex; std::mutex running_mutex; std::mutex socket_mutex; bool running = true; auto f = [&] { running_mutex.lock(); while (running) { running_mutex.unlock(); pipelined_requests_mutex.lock(); if (pipelined_requests.empty()) { pipelined_requests_mutex.unlock(); std::this_thread::sleep_for(std::chrono::seconds(2)); } else { std::string file_name = pipelined_requests.front(); pipelined_requests.pop(); pipelined_requests_mutex.unlock(); socket_mutex.lock(); get_response(GET, file_name); socket_mutex.unlock(); } } pipelined_requests_mutex.lock(); while (!pipelined_requests.empty()) { std::string file_name = pipelined_requests.front(); pipelined_requests.pop(); socket_mutex.lock(); get_response(GET, file_name); socket_mutex.unlock(); } pipelined_requests_mutex.unlock(); }; std::thread *pipelining_thread = nullptr; std::ifstream requests_file_stream(requests_file); std::string request; while (std::getline(requests_file_stream, request)) { if (request.empty()) { continue; } std::stringstream split_stream(request); std::string method, file_name; split_stream >> method; if (!split_stream.eof() && split_stream.tellg() != -1) { split_stream >> file_name; } else { perror("Skipping request: File name is missing"); continue; } RequestMethod req_method = NOP; if (strutil::iequals(method, "GET")) { req_method = GET; } else if (strutil::iequals(method, "POST")) { req_method = POST; } if (req_method == POST) { if (pipelining_thread) { running_mutex.lock(); running = false; running_mutex.unlock(); pipelining_thread->join(); delete pipelining_thread; pipelining_thread = nullptr; } socket_mutex.lock(); make_request(req_method, file_name); get_response(POST, file_name); socket_mutex.unlock(); } else { if (!pipelining_thread) { running = true; pipelining_thread = new std::thread(f); } socket_mutex.lock(); make_request(req_method, file_name); socket_mutex.unlock(); pipelined_requests_mutex.lock(); pipelined_requests.push(file_name); pipelined_requests_mutex.unlock(); } } running_mutex.lock(); running = false; running_mutex.unlock(); pipelining_thread->join(); } int Client::get_client_socket_fd() const { return socket->get_socket_fd(); } std::string Client::get_requests_file() const { return requests_file; } bool Client::is_dry_run() const { return dry_run; } std::string Client::read_file(std::string &file_name) { std::string file_path = "." + file_name; std::ifstream input_stream(file_path); std::string contents(std::istreambuf_iterator<char>(input_stream), {}); input_stream.close(); return contents; } long Client::get_file_size(std::string filename) { struct stat stat_buf; int rc = stat(filename.c_str(), &stat_buf); return rc == 0 ? stat_buf.st_size : -1; } void Client::write_file(std::string &file_name, std::string &contents) { std::string file_path = "." + file_name; std::ofstream output_stream(file_path); output_stream << contents; output_stream.close(); } void Client::make_request(RequestMethod method, std::string &file_name) { std::stringstream request_stream; const static std::string req_method[] = {"GET", "POST", "INVALID"}; request_stream << req_method[method] << ' ' << file_name << ' ' << HTTP_VERSION << "\r\n"; if (method == POST) { request_stream << "Content-Length: " << get_file_size("." + file_name) << "\r\n\r\n"; } else { request_stream << "\r\n"; } std::string request = request_stream.str(); socket->send_http_msg(request); } std::string Client::get_response(RequestMethod method, std::string &file_name) { std::string headers = socket->receive_http_msg_headers(); std::cout << file_name << "\n-----------------------\n" << headers <<"\n----------------------------\n"; std::string file_path = "." + file_name; if (method == POST) { if (headers.find("200 OK") != std::string::npos) { std::string file_contents = read_file(file_name); socket->send_http_msg(file_contents); } return headers; } HttpRequest request(headers); // Hacky implementation to parse the options std::string content_length_str = request.get_options()["Content-Length"]; int content_length = atoi(content_length_str.c_str()); std::string body = socket->receive_http_msg_body(content_length); if (!dry_run) { write_file(file_name, body); } return headers + "\r\n\r\n" + body; }
32.455556
108
0.590894
MohamedAshrafTolba
565e30463b4f98a0b1e179f888c0f6748885652a
1,029
cpp
C++
app/src/main/cpp/IPlayBuilder.cpp
yishuinanfeng/UnitedPlayer
3e3e43ac7ecaa6636965870420eda600205be34d
[ "Apache-2.0" ]
100
2020-02-01T05:39:16.000Z
2022-03-15T06:54:27.000Z
app/src/main/cpp/IPlayBuilder.cpp
yishuinanfeng/UnitedPlayer
3e3e43ac7ecaa6636965870420eda600205be34d
[ "Apache-2.0" ]
null
null
null
app/src/main/cpp/IPlayBuilder.cpp
yishuinanfeng/UnitedPlayer
3e3e43ac7ecaa6636965870420eda600205be34d
[ "Apache-2.0" ]
16
2020-02-04T05:52:42.000Z
2021-08-09T07:15:27.000Z
// // Created by yanxi on 2019/10/28. // #include "IPlayBuilder.h" #include "IPlayer.h" #include "IDemux.h" #include "XLog.h" #include "IDecode.h" #include "IResample.h" #include "IAudioPlay.h" #include "IVideoView.h" IPlayer *IPlayBuilder::BuildPlayer(unsigned int index) { IPlayer *play = CreatePalyer(index); IDemux *iDemux = CreateDemux(); IDecode *audioDecode = CreateDecode(); IDecode *videoDecode = CreateDecode(); //解复用一帧之后,通知解码器 iDemux->AddOberver(audioDecode); iDemux->AddOberver(videoDecode); IVideoView *iVideoView = CreateVideoView(); //解码一帧之后,通知显示模块 videoDecode->AddOberver(iVideoView); IResample *resample = CreateResample(); audioDecode->AddOberver(resample); IAudioPlay *audioPlay = CreateAudioPlay(); resample->AddOberver(audioPlay); play->iDemux = iDemux; play->audioPlay = audioPlay; play->audioDecode = audioDecode; play->videoDecode = videoDecode; play->resample = resample; play->videoView = iVideoView; return play; }
27.078947
56
0.697765
yishuinanfeng
565ea2dbe5b5bc0ade95a826f48e162f5851317d
133,992
cpp
C++
module/mpc-be/SRC/src/filters/transform/MPCVideoDec/MPCVideoDec.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/filters/transform/MPCVideoDec/MPCVideoDec.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
module/mpc-be/SRC/src/filters/transform/MPCVideoDec/MPCVideoDec.cpp
1aq/PBox
67ced599ee36ceaff097c6584f8100cf96006dfe
[ "MIT" ]
null
null
null
/* * (C) 2006-2020 see Authors.txt * * This file is part of MPC-BE. * * MPC-BE 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. * * MPC-BE 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, see <http://www.gnu.org/licenses/>. * */ #include "stdafx.h" #include <atlbase.h> #include <MMReg.h> #include "MPCVideoDec.h" #include "DXVADecoder/DXVAAllocator.h" #include "FfmpegContext.h" #include "../../../DSUtil/CPUInfo.h" #include "../../../DSUtil/D3D9Helper.h" #include "../../../DSUtil/DSUtil.h" #include "../../../DSUtil/ffmpeg_log.h" #include "../../../DSUtil/GolombBuffer.h" #include "../../../DSUtil/SysVersion.h" #include "../../../DSUtil/DXVAState.h" #include "../../parser/AviSplitter/AviSplitter.h" #include "../../parser/OggSplitter/OggSplitter.h" #include "../../parser/MpegSplitter/MpegSplitter.h" #include "../../Lock.h" #include <moreuuids.h> #include <FilterInterfaces.h> #include "Version.h" #pragma warning(push) #pragma warning(disable: 4005) #pragma warning(disable: 5033) extern "C" { #include <ffmpeg/libavcodec/avcodec.h> #include <ffmpeg/libavcodec/dxva2.h> #include <ffmpeg/libavutil/intreadwrite.h> #include <ffmpeg/libavutil/imgutils.h> #include <ffmpeg/libavutil/mastering_display_metadata.h> #include <ffmpeg/libavutil/opt.h> #include <ffmpeg/libavutil/pixdesc.h> } #pragma warning(pop) #ifdef _DEBUG #pragma comment(lib, "libmfx_d.lib") #else #pragma comment(lib, "libmfx.lib") #endif // option names #define OPT_REGKEY_VideoDec L"Software\\MPC-BE Filters\\MPC Video Decoder" #define OPT_SECTION_VideoDec L"Filters\\MPC Video Decoder" #define OPT_ThreadNumber L"ThreadNumber" #define OPT_DiscardMode L"DiscardMode" #define OPT_ScanType L"ScanType" #define OPT_ARMode L"ARMode" #define OPT_DXVACheck L"DXVACheckCompatibility" #define OPT_DisableDXVA_SD L"DisableDXVA_SD" #define OPT_SW_prefix L"Sw_" #define OPT_SwRGBLevels L"SwRGBLevels" #define MAX_AUTO_THREADS 32 #pragma region any_constants #ifdef REGISTER_FILTER #define OPT_REGKEY_VCodecs L"Software\\MPC-BE Filters\\MPC Video Decoder\\Codecs" static const struct vcodec_t { const LPCWSTR opt_name; const unsigned __int64 flag; } vcodecs[] = { {L"h264", CODEC_H264 }, {L"h264_mvc", CODEC_H264_MVC }, {L"mpeg1", CODEC_MPEG1 }, {L"mpeg3", CODEC_MPEG2 }, {L"vc1", CODEC_VC1 }, {L"msmpeg4", CODEC_MSMPEG4 }, {L"xvid", CODEC_XVID }, {L"divx", CODEC_DIVX }, {L"wmv", CODEC_WMV }, {L"hevc", CODEC_HEVC }, {L"vp356", CODEC_VP356 }, {L"vp89", CODEC_VP89 }, {L"theora", CODEC_THEORA }, {L"mjpeg", CODEC_MJPEG }, {L"dv", CODEC_DV }, {L"lossless", CODEC_LOSSLESS }, {L"prores", CODEC_PRORES }, {L"canopus", CODEC_CANOPUS }, {L"screc", CODEC_SCREC }, {L"indeo", CODEC_INDEO }, {L"h263", CODEC_H263 }, {L"svq3", CODEC_SVQ3 }, {L"realv", CODEC_REALV }, {L"dirac", CODEC_DIRAC }, {L"binkv", CODEC_BINKV }, {L"amvv", CODEC_AMVV }, {L"flash", CODEC_FLASH }, {L"utvd", CODEC_UTVD }, {L"png", CODEC_PNG }, {L"uncompressed", CODEC_UNCOMPRESSED}, {L"dnxhd", CODEC_DNXHD }, {L"cinepak", CODEC_CINEPAK }, {L"quicktime", CODEC_QT }, {L"cineform", CODEC_CINEFORM }, {L"hap", CODEC_HAP }, {L"av1", CODEC_AV1 }, // dxva codecs {L"h264_dxva", CODEC_H264_DXVA }, {L"hevc_dxva", CODEC_HEVC_DXVA }, {L"mpeg2_dxva", CODEC_MPEG2_DXVA}, {L"vc1_dxva", CODEC_VC1_DXVA }, {L"wmv3_dxva", CODEC_WMV3_DXVA }, {L"vp9_dxva", CODEC_VP9_DXVA } }; #endif struct FFMPEG_CODECS { const CLSID* clsMinorType; const enum AVCodecID nFFCodec; const int FFMPEGCode; const int DXVACode; }; struct { const enum AVCodecID nCodecId; const GUID decoderGUID; const bool bHighBitdepth; } DXVAModes [] = { // H.264 { AV_CODEC_ID_H264, DXVA2_ModeH264_E, false }, { AV_CODEC_ID_H264, DXVA2_ModeH264_F, false }, { AV_CODEC_ID_H264, DXVA2_Intel_H264_ClearVideo, false }, // HEVC { AV_CODEC_ID_HEVC, DXVA2_ModeHEVC_VLD_Main10, true }, { AV_CODEC_ID_HEVC, DXVA2_ModeHEVC_VLD_Main, false }, // MPEG2 { AV_CODEC_ID_MPEG2VIDEO, DXVA2_ModeMPEG2_VLD, false }, // VC1 { AV_CODEC_ID_VC1, DXVA2_ModeVC1_D2010, false }, { AV_CODEC_ID_VC1, DXVA2_ModeVC1_D, false }, // WMV3 { AV_CODEC_ID_WMV3, DXVA2_ModeVC1_D2010, false }, { AV_CODEC_ID_WMV3, DXVA2_ModeVC1_D, false }, // VP9 { AV_CODEC_ID_VP9, DXVA2_ModeVP9_VLD_10bit_Profile2, true }, { AV_CODEC_ID_VP9, DXVA2_ModeVP9_VLD_Profile0, false } }; FFMPEG_CODECS ffCodecs[] = { // Flash video { &MEDIASUBTYPE_FLV1, AV_CODEC_ID_FLV1, VDEC_FLV, -1 }, { &MEDIASUBTYPE_flv1, AV_CODEC_ID_FLV1, VDEC_FLV, -1 }, { &MEDIASUBTYPE_FLV4, AV_CODEC_ID_VP6F, VDEC_FLV, -1 }, { &MEDIASUBTYPE_flv4, AV_CODEC_ID_VP6F, VDEC_FLV, -1 }, { &MEDIASUBTYPE_VP6F, AV_CODEC_ID_VP6F, VDEC_FLV, -1 }, { &MEDIASUBTYPE_vp6f, AV_CODEC_ID_VP6F, VDEC_FLV, -1 }, // VP3 { &MEDIASUBTYPE_VP30, AV_CODEC_ID_VP3, VDEC_VP356, -1 }, { &MEDIASUBTYPE_VP31, AV_CODEC_ID_VP3, VDEC_VP356, -1 }, // VP5 { &MEDIASUBTYPE_VP50, AV_CODEC_ID_VP5, VDEC_VP356, -1 }, { &MEDIASUBTYPE_vp50, AV_CODEC_ID_VP5, VDEC_VP356, -1 }, // VP6 { &MEDIASUBTYPE_VP60, AV_CODEC_ID_VP6, VDEC_VP356, -1 }, { &MEDIASUBTYPE_vp60, AV_CODEC_ID_VP6, VDEC_VP356, -1 }, { &MEDIASUBTYPE_VP61, AV_CODEC_ID_VP6, VDEC_VP356, -1 }, { &MEDIASUBTYPE_vp61, AV_CODEC_ID_VP6, VDEC_VP356, -1 }, { &MEDIASUBTYPE_VP62, AV_CODEC_ID_VP6, VDEC_VP356, -1 }, { &MEDIASUBTYPE_vp62, AV_CODEC_ID_VP6, VDEC_VP356, -1 }, { &MEDIASUBTYPE_VP6A, AV_CODEC_ID_VP6A, VDEC_VP356, -1 }, { &MEDIASUBTYPE_vp6a, AV_CODEC_ID_VP6A, VDEC_VP356, -1 }, // VP7 { &MEDIASUBTYPE_VP70, AV_CODEC_ID_VP7, VDEC_VP789, -1 }, // VP8 { &MEDIASUBTYPE_VP80, AV_CODEC_ID_VP8, VDEC_VP789, -1 }, // VP9 { &MEDIASUBTYPE_VP90, AV_CODEC_ID_VP9, VDEC_VP789, VDEC_DXVA_VP9 }, // Xvid { &MEDIASUBTYPE_XVID, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_xvid, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_XVIX, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_xvix, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, // DivX { &MEDIASUBTYPE_DX50, AV_CODEC_ID_MPEG4, VDEC_DIVX, -1 }, { &MEDIASUBTYPE_dx50, AV_CODEC_ID_MPEG4, VDEC_DIVX, -1 }, { &MEDIASUBTYPE_DIVX, AV_CODEC_ID_MPEG4, VDEC_DIVX, -1 }, { &MEDIASUBTYPE_divx, AV_CODEC_ID_MPEG4, VDEC_DIVX, -1 }, { &MEDIASUBTYPE_Divx, AV_CODEC_ID_MPEG4, VDEC_DIVX, -1 }, // WMV1/2/3 { &MEDIASUBTYPE_WMV1, AV_CODEC_ID_WMV1, VDEC_WMV, -1 }, { &MEDIASUBTYPE_wmv1, AV_CODEC_ID_WMV1, VDEC_WMV, -1 }, { &MEDIASUBTYPE_WMV2, AV_CODEC_ID_WMV2, VDEC_WMV, -1 }, { &MEDIASUBTYPE_wmv2, AV_CODEC_ID_WMV2, VDEC_WMV, -1 }, { &MEDIASUBTYPE_WMV3, AV_CODEC_ID_WMV3, VDEC_WMV, VDEC_DXVA_WMV3 }, { &MEDIASUBTYPE_wmv3, AV_CODEC_ID_WMV3, VDEC_WMV, VDEC_DXVA_WMV3 }, // WMVP { &MEDIASUBTYPE_WMVP, AV_CODEC_ID_WMV3IMAGE, VDEC_WMV, -1 }, // MPEG-2 { &MEDIASUBTYPE_MPEG2_VIDEO, AV_CODEC_ID_MPEG2VIDEO, VDEC_MPEG2, VDEC_DXVA_MPEG2 }, { &MEDIASUBTYPE_MPG2, AV_CODEC_ID_MPEG2VIDEO, VDEC_MPEG2, VDEC_DXVA_MPEG2 }, // MPEG-1 { &MEDIASUBTYPE_MPEG1Packet, AV_CODEC_ID_MPEG1VIDEO, VDEC_MPEG1, -1 }, { &MEDIASUBTYPE_MPEG1Payload, AV_CODEC_ID_MPEG1VIDEO, VDEC_MPEG1, -1 }, // MSMPEG-4 { &MEDIASUBTYPE_DIV3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_div3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_DVX3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_dvx3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_MP43, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_mp43, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_COL1, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_col1, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_DIV4, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_div4, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_DIV5, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_div5, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_DIV6, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_div6, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_AP41, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_ap41, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_MPG3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_mpg3, AV_CODEC_ID_MSMPEG4V3, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_DIV2, AV_CODEC_ID_MSMPEG4V2, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_div2, AV_CODEC_ID_MSMPEG4V2, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_MP42, AV_CODEC_ID_MSMPEG4V2, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_mp42, AV_CODEC_ID_MSMPEG4V2, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_MPG4, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_mpg4, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_DIV1, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_div1, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_MP41, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 }, { &MEDIASUBTYPE_mp41, AV_CODEC_ID_MSMPEG4V1, VDEC_MSMPEG4, -1 }, // AMV Video { &MEDIASUBTYPE_AMVV, AV_CODEC_ID_AMV, VDEC_AMV, -1 }, // MJPEG { &MEDIASUBTYPE_MJPG, AV_CODEC_ID_MJPEG, VDEC_MJPEG, -1 }, { &MEDIASUBTYPE_QTJpeg, AV_CODEC_ID_MJPEG, VDEC_MJPEG, -1 }, { &MEDIASUBTYPE_MJPA, AV_CODEC_ID_MJPEG, VDEC_MJPEG, -1 }, { &MEDIASUBTYPE_MJPB, AV_CODEC_ID_MJPEGB, VDEC_MJPEG, -1 }, { &MEDIASUBTYPE_MJP2, AV_CODEC_ID_JPEG2000, VDEC_MJPEG, -1 }, { &MEDIASUBTYPE_MJ2C, AV_CODEC_ID_JPEG2000, VDEC_MJPEG, -1 }, // Cinepak { &MEDIASUBTYPE_CVID, AV_CODEC_ID_CINEPAK, VDEC_CINEPAK, -1 }, // DV VIDEO { &MEDIASUBTYPE_dvsl, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_dvsd, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_dvhd, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_dv25, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_dv50, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_dvh1, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_CDVH, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_CDVC, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, // Quicktime DV sybtypes (used in LAV Splitter) { &MEDIASUBTYPE_DVCP, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVPP, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DV5P, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVC, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVH2, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVH3, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVH4, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVH5, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVH6, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVHQ, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_DVHP, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_AVdv, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, { &MEDIASUBTYPE_AVd1, AV_CODEC_ID_DVVIDEO, VDEC_DV, -1 }, // Quicktime { &MEDIASUBTYPE_8BPS, AV_CODEC_ID_8BPS, VDEC_QT, -1 }, { &MEDIASUBTYPE_QTRle, AV_CODEC_ID_QTRLE, VDEC_QT, -1 }, { &MEDIASUBTYPE_QTRpza, AV_CODEC_ID_RPZA, VDEC_QT, -1 }, // Screen recorder { &MEDIASUBTYPE_CSCD, AV_CODEC_ID_CSCD, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_TSCC, AV_CODEC_ID_TSCC, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_TSCC2, AV_CODEC_ID_TSCC2, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_VMnc, AV_CODEC_ID_VMNC, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_FLASHSV1, AV_CODEC_ID_FLASHSV, VDEC_SCREEN, -1 }, // { &MEDIASUBTYPE_FLASHSV2, AV_CODEC_ID_FLASHSV2, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_FPS1, AV_CODEC_ID_FRAPS, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_MSS1, AV_CODEC_ID_MSS1, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_MSS2, AV_CODEC_ID_MSS2, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_MSA1, AV_CODEC_ID_MSA1, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_MTS2, AV_CODEC_ID_MTS2, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_G2M2, AV_CODEC_ID_G2M, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_G2M3, AV_CODEC_ID_G2M, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_G2M4, AV_CODEC_ID_G2M, VDEC_SCREEN, -1 }, { &MEDIASUBTYPE_CRAM, AV_CODEC_ID_MSVIDEO1, VDEC_SCREEN, -1 }, // CRAM - Microsoft Video 1 { &MEDIASUBTYPE_FICV, AV_CODEC_ID_FIC, VDEC_SCREEN, -1 }, // UtVideo { &MEDIASUBTYPE_Ut_ULRA, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_ULRG, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_ULY0, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_ULY2, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_ULY4, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_ULH0, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_ULH2, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_ULH4, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, // UtVideo T2 { &MEDIASUBTYPE_Ut_UMRA, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UMRG, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UMY2, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UMY4, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UMH2, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UMH4, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, // UtVideo Pro { &MEDIASUBTYPE_Ut_UQRA, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UQRG, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UQY0, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, { &MEDIASUBTYPE_Ut_UQY2, AV_CODEC_ID_UTVIDEO, VDEC_UT, -1 }, // DIRAC { &MEDIASUBTYPE_DRAC, AV_CODEC_ID_DIRAC, VDEC_DIRAC, -1 }, // Lossless Video { &MEDIASUBTYPE_HuffYUV, AV_CODEC_ID_HUFFYUV, VDEC_LOSSLESS, -1 }, { &MEDIASUBTYPE_HYMT, AV_CODEC_ID_HYMT, VDEC_LOSSLESS, -1 }, { &MEDIASUBTYPE_FFVHuff, AV_CODEC_ID_FFVHUFF, VDEC_LOSSLESS, -1 }, { &MEDIASUBTYPE_FFV1, AV_CODEC_ID_FFV1, VDEC_LOSSLESS, -1 }, { &MEDIASUBTYPE_Lagarith, AV_CODEC_ID_LAGARITH, VDEC_LOSSLESS, -1 }, { &MEDIASUBTYPE_MAGICYUV, AV_CODEC_ID_MAGICYUV, VDEC_LOSSLESS, -1 }, // Indeo 3/4/5 { &MEDIASUBTYPE_IV31, AV_CODEC_ID_INDEO3, VDEC_INDEO, -1 }, { &MEDIASUBTYPE_IV32, AV_CODEC_ID_INDEO3, VDEC_INDEO, -1 }, { &MEDIASUBTYPE_IV41, AV_CODEC_ID_INDEO4, VDEC_INDEO, -1 }, { &MEDIASUBTYPE_IV50, AV_CODEC_ID_INDEO5, VDEC_INDEO, -1 }, // H264/AVC { &MEDIASUBTYPE_H264, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_h264, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_X264, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_x264, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_VSSH, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_vssh, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_DAVC, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_davc, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_PAVC, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_pavc, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_AVC1, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_avc1, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, { &MEDIASUBTYPE_H264_bis, AV_CODEC_ID_H264, VDEC_H264, VDEC_DXVA_H264 }, // H264 MVC { &MEDIASUBTYPE_AMVC, AV_CODEC_ID_H264, VDEC_H264_MVC, -1 }, { &MEDIASUBTYPE_MVC1, AV_CODEC_ID_H264, VDEC_H264_MVC, -1 }, // SVQ3 { &MEDIASUBTYPE_SVQ3, AV_CODEC_ID_SVQ3, VDEC_SVQ, -1 }, // SVQ1 { &MEDIASUBTYPE_SVQ1, AV_CODEC_ID_SVQ1, VDEC_SVQ, -1 }, // H263 { &MEDIASUBTYPE_H263, AV_CODEC_ID_H263, VDEC_H263, -1 }, { &MEDIASUBTYPE_h263, AV_CODEC_ID_H263, VDEC_H263, -1 }, { &MEDIASUBTYPE_S263, AV_CODEC_ID_H263, VDEC_H263, -1 }, { &MEDIASUBTYPE_s263, AV_CODEC_ID_H263, VDEC_H263, -1 }, // Real Video { &MEDIASUBTYPE_RV10, AV_CODEC_ID_RV10, VDEC_REAL, -1 }, { &MEDIASUBTYPE_RV20, AV_CODEC_ID_RV20, VDEC_REAL, -1 }, { &MEDIASUBTYPE_RV30, AV_CODEC_ID_RV30, VDEC_REAL, -1 }, { &MEDIASUBTYPE_RV40, AV_CODEC_ID_RV40, VDEC_REAL, -1 }, // Theora { &MEDIASUBTYPE_THEORA, AV_CODEC_ID_THEORA, VDEC_THEORA, -1 }, { &MEDIASUBTYPE_theora, AV_CODEC_ID_THEORA, VDEC_THEORA, -1 }, // WVC1 { &MEDIASUBTYPE_WVC1, AV_CODEC_ID_VC1, VDEC_VC1, VDEC_DXVA_VC1 }, { &MEDIASUBTYPE_wvc1, AV_CODEC_ID_VC1, VDEC_VC1, VDEC_DXVA_VC1 }, // WMVA { &MEDIASUBTYPE_WMVA, AV_CODEC_ID_VC1, VDEC_VC1, VDEC_DXVA_VC1 }, // WVP2 { &MEDIASUBTYPE_WVP2, AV_CODEC_ID_VC1IMAGE, VDEC_VC1, -1 }, // Apple ProRes { &MEDIASUBTYPE_apch, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 }, { &MEDIASUBTYPE_apcn, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 }, { &MEDIASUBTYPE_apcs, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 }, { &MEDIASUBTYPE_apco, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 }, { &MEDIASUBTYPE_ap4h, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 }, { &MEDIASUBTYPE_ap4x, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 }, { &MEDIASUBTYPE_icpf, AV_CODEC_ID_PRORES, VDEC_PRORES, -1 }, { &MEDIASUBTYPE_icod, AV_CODEC_ID_AIC, VDEC_PRORES, -1 }, // Bink Video { &MEDIASUBTYPE_BINKVI, AV_CODEC_ID_BINKVIDEO, VDEC_BINK, -1 }, { &MEDIASUBTYPE_BINKVB, AV_CODEC_ID_BINKVIDEO, VDEC_BINK, -1 }, // PNG { &MEDIASUBTYPE_PNG, AV_CODEC_ID_PNG, VDEC_PNG, -1 }, // Canopus { &MEDIASUBTYPE_CLLC, AV_CODEC_ID_CLLC, VDEC_CANOPUS, -1 }, { &MEDIASUBTYPE_CUVC, AV_CODEC_ID_HQ_HQA, VDEC_CANOPUS, -1 }, { &MEDIASUBTYPE_CHQX, AV_CODEC_ID_HQX, VDEC_CANOPUS, -1 }, // CineForm { &MEDIASUBTYPE_CFHD, AV_CODEC_ID_CFHD, VDEC_CINEFORM, -1 }, // HEVC { &MEDIASUBTYPE_HEVC, AV_CODEC_ID_HEVC, VDEC_HEVC, VDEC_DXVA_HEVC }, { &MEDIASUBTYPE_HVC1, AV_CODEC_ID_HEVC, VDEC_HEVC, VDEC_DXVA_HEVC }, { &MEDIASUBTYPE_HM10, AV_CODEC_ID_HEVC, VDEC_HEVC, VDEC_DXVA_HEVC }, // Avid DNxHD { &MEDIASUBTYPE_AVdn, AV_CODEC_ID_DNXHD, VDEC_DNXHD, -1 }, // Avid DNxHR { &MEDIASUBTYPE_AVdh, AV_CODEC_ID_DNXHD, VDEC_DNXHD, -1 }, // Other MPEG-4 { &MEDIASUBTYPE_MP4V, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_mp4v, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_M4S2, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_m4s2, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_MP4S, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_mp4s, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_3IV1, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_3iv1, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_3IV2, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_3iv2, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_3IVX, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_3ivx, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_BLZ0, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_blz0, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_DM4V, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_dm4v, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_FFDS, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_ffds, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_FVFW, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_fvfw, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_DXGM, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_dxgm, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_FMP4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_fmp4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_HDX4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_hdx4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_LMP4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_lmp4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_NDIG, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_ndig, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_RMP4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_rmp4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_SMP4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_smp4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_SEDG, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_sedg, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_UMP4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_ump4, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_WV1F, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, { &MEDIASUBTYPE_wv1f, AV_CODEC_ID_MPEG4, VDEC_XVID, -1 }, // Vidvox Hap { &MEDIASUBTYPE_Hap1, AV_CODEC_ID_HAP, VDEC_HAP, -1 }, { &MEDIASUBTYPE_Hap5, AV_CODEC_ID_HAP, VDEC_HAP, -1 }, { &MEDIASUBTYPE_HapA, AV_CODEC_ID_HAP, VDEC_HAP, -1 }, { &MEDIASUBTYPE_HapM, AV_CODEC_ID_HAP, VDEC_HAP, -1 }, { &MEDIASUBTYPE_HapY, AV_CODEC_ID_HAP, VDEC_HAP, -1 }, // AV1 { &MEDIASUBTYPE_AV01, AV_CODEC_ID_AV1, VDEC_AV1, -1 }, // uncompressed video { &MEDIASUBTYPE_v210, AV_CODEC_ID_V210, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_V410, AV_CODEC_ID_V410, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_r210, AV_CODEC_ID_R210, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_R10g, AV_CODEC_ID_R10K, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_R10k, AV_CODEC_ID_R10K, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_AVrp, AV_CODEC_ID_AVRP, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_Y8, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_Y800, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_Y16, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_I420, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_Y41B, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_Y42B, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_444P, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_cyuv, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_YVU9, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_IYUV, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_UYVY, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_YUY2, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_NV12, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_YV12, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_YV16, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_YV24, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_BGR48, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_BGRA64, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_b48r, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_b64a, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 }, { &MEDIASUBTYPE_LAV_RAWVIDEO, AV_CODEC_ID_RAWVIDEO, VDEC_UNCOMPRESSED, -1 } }; /* Important: the order should be exactly the same as in ffCodecs[] */ const AMOVIESETUP_MEDIATYPE sudPinTypesIn[] = { // Flash video { &MEDIATYPE_Video, &MEDIASUBTYPE_FLV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_flv1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FLV4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_flv4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP6F }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp6f }, // VP3 { &MEDIATYPE_Video, &MEDIASUBTYPE_VP30 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP31 }, // VP5 { &MEDIATYPE_Video, &MEDIASUBTYPE_VP50 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp50 }, // VP6 { &MEDIATYPE_Video, &MEDIASUBTYPE_VP60 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp60 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP61 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp61 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP62 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp62 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VP6A }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vp6a }, // VP7 { &MEDIATYPE_Video, &MEDIASUBTYPE_VP70 }, // VP8 { &MEDIATYPE_Video, &MEDIASUBTYPE_VP80 }, // VP9 { &MEDIATYPE_Video, &MEDIASUBTYPE_VP90 }, // Xvid { &MEDIATYPE_Video, &MEDIASUBTYPE_XVID }, { &MEDIATYPE_Video, &MEDIASUBTYPE_xvid }, { &MEDIATYPE_Video, &MEDIASUBTYPE_XVIX }, { &MEDIATYPE_Video, &MEDIASUBTYPE_xvix }, // DivX { &MEDIATYPE_Video, &MEDIASUBTYPE_DX50 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dx50 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIVX }, { &MEDIATYPE_Video, &MEDIASUBTYPE_divx }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Divx }, // WMV1/2/3 { &MEDIATYPE_Video, &MEDIASUBTYPE_WMV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wmv1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WMV2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wmv2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WMV3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wmv3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WMVP }, // MPEG-2 { &MEDIATYPE_Video, &MEDIASUBTYPE_MPEG2_VIDEO }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MPG2 }, // MPEG-1 { &MEDIATYPE_Video, &MEDIASUBTYPE_MPEG1Packet }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MPEG1Payload }, // MSMPEG-4 { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVX3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dvx3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MP43 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mp43 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_COL1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_col1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV5 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div5 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV6 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div6 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AP41 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ap41 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MPG3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mpg3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MP42 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mp42 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MPG4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mpg4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DIV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_div1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MP41 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mp41 }, // AMV Video { &MEDIATYPE_Video, &MEDIASUBTYPE_AMVV }, // MJPEG { &MEDIATYPE_Video, &MEDIASUBTYPE_MJPG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_QTJpeg }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MJPA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MJPB }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MJP2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MJ2C }, // CINEPAK { &MEDIATYPE_Video, &MEDIASUBTYPE_CVID }, // DV VIDEO { &MEDIATYPE_Video, &MEDIASUBTYPE_dvsl }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dvsd }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dvhd }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dv25 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dv50 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dvh1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CDVH }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CDVC }, // Quicktime DV sybtypes (used in LAV Splitter) { &MEDIATYPE_Video, &MEDIASUBTYPE_DVCP }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVPP }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DV5P }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH5 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVH6 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVHQ }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DVHP }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AVdv }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AVd1 }, // QuickTime video { &MEDIATYPE_Video, &MEDIASUBTYPE_8BPS }, { &MEDIATYPE_Video, &MEDIASUBTYPE_QTRle }, { &MEDIATYPE_Video, &MEDIASUBTYPE_QTRpza }, // Screen recorder { &MEDIATYPE_Video, &MEDIASUBTYPE_CSCD }, { &MEDIATYPE_Video, &MEDIASUBTYPE_TSCC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_TSCC2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VMnc }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FLASHSV1 }, // { &MEDIATYPE_Video, &MEDIASUBTYPE_FLASHSV2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FPS1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MSS1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MSS2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MSA1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MTS2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_G2M2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_G2M3 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_G2M4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CRAM }, // CRAM - Microsoft Video 1 { &MEDIATYPE_Video, &MEDIASUBTYPE_FICV }, // UtVideo { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULRA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULRG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULY0 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULY2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULY4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULH0 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULH2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_ULH4 }, // UtVideo T2 { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMRA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMRG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMY2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMY4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMH2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UMH4 }, // UtVideo Pro { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UQRA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UQRG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UQY0 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Ut_UQY2 }, // DIRAC { &MEDIATYPE_Video, &MEDIASUBTYPE_DRAC }, // Lossless Video { &MEDIATYPE_Video, &MEDIASUBTYPE_HuffYUV }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HYMT }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FFVHuff }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FFV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Lagarith }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MAGICYUV }, // Indeo 3/4/5 { &MEDIATYPE_Video, &MEDIASUBTYPE_IV31 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_IV32 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_IV41 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_IV50 }, // H264/AVC { &MEDIATYPE_Video, &MEDIASUBTYPE_H264 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_h264 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_X264 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_x264 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_VSSH }, { &MEDIATYPE_Video, &MEDIASUBTYPE_vssh }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DAVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_davc }, { &MEDIATYPE_Video, &MEDIASUBTYPE_PAVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_pavc }, { &MEDIATYPE_Video, &MEDIASUBTYPE_AVC1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_avc1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_H264_bis }, // H264 MVC { &MEDIATYPE_Video, &MEDIASUBTYPE_AMVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MVC1 }, // SVQ3 { &MEDIATYPE_Video, &MEDIASUBTYPE_SVQ3 }, // SVQ1 { &MEDIATYPE_Video, &MEDIASUBTYPE_SVQ1 }, // H263 { &MEDIATYPE_Video, &MEDIASUBTYPE_H263 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_h263 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_S263 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_s263 }, // Real video { &MEDIATYPE_Video, &MEDIASUBTYPE_RV10 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_RV20 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_RV30 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_RV40 }, // Theora { &MEDIATYPE_Video, &MEDIASUBTYPE_THEORA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_theora }, // VC1 { &MEDIATYPE_Video, &MEDIASUBTYPE_WVC1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wvc1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WMVA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WVP2 }, // Apple ProRes { &MEDIATYPE_Video, &MEDIASUBTYPE_apch }, { &MEDIATYPE_Video, &MEDIASUBTYPE_apcn }, { &MEDIATYPE_Video, &MEDIASUBTYPE_apcs }, { &MEDIATYPE_Video, &MEDIASUBTYPE_apco }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ap4h }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ap4x }, { &MEDIATYPE_Video, &MEDIASUBTYPE_icpf }, { &MEDIATYPE_Video, &MEDIASUBTYPE_icod }, // Bink Video { &MEDIATYPE_Video, &MEDIASUBTYPE_BINKVI }, { &MEDIATYPE_Video, &MEDIASUBTYPE_BINKVB }, // PNG { &MEDIATYPE_Video, &MEDIASUBTYPE_PNG }, // Canopus { &MEDIATYPE_Video, &MEDIASUBTYPE_CLLC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CUVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_CHQX }, // CineForm { &MEDIATYPE_Video, &MEDIASUBTYPE_CFHD }, // HEVC { &MEDIATYPE_Video, &MEDIASUBTYPE_HEVC }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HVC1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HM10 }, // Avid DNxHD { &MEDIATYPE_Video, &MEDIASUBTYPE_AVdn }, // Avid DNxHR { &MEDIATYPE_Video, &MEDIASUBTYPE_AVdh }, // Other MPEG-4 { &MEDIATYPE_Video, &MEDIASUBTYPE_MP4V }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mp4v }, { &MEDIATYPE_Video, &MEDIASUBTYPE_M4S2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_m4s2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_MP4S }, { &MEDIATYPE_Video, &MEDIASUBTYPE_mp4s }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3IV1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3iv1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3IV2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3iv2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3IVX }, { &MEDIATYPE_Video, &MEDIASUBTYPE_3ivx }, { &MEDIATYPE_Video, &MEDIASUBTYPE_BLZ0 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_blz0 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DM4V }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dm4v }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FFDS }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ffds }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FVFW }, { &MEDIATYPE_Video, &MEDIASUBTYPE_fvfw }, { &MEDIATYPE_Video, &MEDIASUBTYPE_DXGM }, { &MEDIATYPE_Video, &MEDIASUBTYPE_dxgm }, { &MEDIATYPE_Video, &MEDIASUBTYPE_FMP4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_fmp4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HDX4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_hdx4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_LMP4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_lmp4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_NDIG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ndig }, { &MEDIATYPE_Video, &MEDIASUBTYPE_RMP4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_rmp4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_SMP4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_smp4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_SEDG }, { &MEDIATYPE_Video, &MEDIASUBTYPE_sedg }, { &MEDIATYPE_Video, &MEDIASUBTYPE_UMP4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_ump4 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_WV1F }, { &MEDIATYPE_Video, &MEDIASUBTYPE_wv1f }, // Vidvox Hap { &MEDIATYPE_Video, &MEDIASUBTYPE_Hap1 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_Hap5 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HapA }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HapM }, { &MEDIATYPE_Video, &MEDIASUBTYPE_HapY }, // AV1 { &MEDIATYPE_Video, &MEDIASUBTYPE_AV01 }, }; const AMOVIESETUP_MEDIATYPE sudPinTypesInUncompressed[] = { // uncompressed video { &MEDIATYPE_Video, &MEDIASUBTYPE_v210 }, // YUV 4:2:2 10-bit { &MEDIATYPE_Video, &MEDIASUBTYPE_V410 }, // YUV 4:4:4 10-bit { &MEDIATYPE_Video, &MEDIASUBTYPE_r210 }, // RGB30 { &MEDIATYPE_Video, &MEDIASUBTYPE_R10g }, // RGB30 { &MEDIATYPE_Video, &MEDIASUBTYPE_R10k }, // RGB30 { &MEDIATYPE_Video, &MEDIASUBTYPE_AVrp }, // RGB30 { &MEDIATYPE_Video, &MEDIASUBTYPE_Y8 }, // Y 8-bit (monochrome) { &MEDIATYPE_Video, &MEDIASUBTYPE_Y800 }, // Y 8-bit (monochrome) { &MEDIATYPE_Video, &MEDIASUBTYPE_Y16 }, // Y 16-bit (monochrome) { &MEDIATYPE_Video, &MEDIASUBTYPE_I420 }, // YUV 4:2:0 Planar { &MEDIATYPE_Video, &MEDIASUBTYPE_Y41B }, // YUV 4:1:1 Planar { &MEDIATYPE_Video, &MEDIASUBTYPE_Y42B }, // YUV 4:2:2 Planar { &MEDIATYPE_Video, &MEDIASUBTYPE_444P }, // YUV 4:4:4 Planar { &MEDIATYPE_Video, &MEDIASUBTYPE_cyuv }, // UYVY flipped vertically { &MEDIATYPE_Video, &MEDIASUBTYPE_YVU9 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_IYUV }, { &MEDIATYPE_Video, &MEDIASUBTYPE_UYVY }, { &MEDIATYPE_Video, &MEDIASUBTYPE_YUY2 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_NV12 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_YV12 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_YV16 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_YV24 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_BGR48 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_BGRA64 }, { &MEDIATYPE_Video, &MEDIASUBTYPE_b48r }, { &MEDIATYPE_Video, &MEDIASUBTYPE_b64a }, { &MEDIATYPE_Video, &MEDIASUBTYPE_LAV_RAWVIDEO }, }; #pragma endregion any_constants const AMOVIESETUP_MEDIATYPE sudPinTypesOut[] = { {&MEDIATYPE_Video, &MEDIASUBTYPE_NV12}, {&MEDIATYPE_Video, &MEDIASUBTYPE_YV12}, {&MEDIATYPE_Video, &MEDIASUBTYPE_YUY2}, {&MEDIATYPE_Video, &MEDIASUBTYPE_YV16}, {&MEDIATYPE_Video, &MEDIASUBTYPE_AYUV}, {&MEDIATYPE_Video, &MEDIASUBTYPE_YV24}, {&MEDIATYPE_Video, &MEDIASUBTYPE_P010}, {&MEDIATYPE_Video, &MEDIASUBTYPE_P210}, {&MEDIATYPE_Video, &MEDIASUBTYPE_Y410}, {&MEDIATYPE_Video, &MEDIASUBTYPE_P016}, {&MEDIATYPE_Video, &MEDIASUBTYPE_P216}, {&MEDIATYPE_Video, &MEDIASUBTYPE_Y416}, {&MEDIATYPE_Video, &MEDIASUBTYPE_RGB32}, }; #ifdef REGISTER_FILTER const AMOVIESETUP_PIN sudpPins[] = { {L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesIn), sudPinTypesIn}, {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesOut), sudPinTypesOut} }; const AMOVIESETUP_PIN sudpPinsUncompressed[] = { {L"Input", FALSE, FALSE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesInUncompressed), sudPinTypesInUncompressed}, {L"Output", FALSE, TRUE, FALSE, FALSE, &CLSID_NULL, nullptr, _countof(sudPinTypesOut), sudPinTypesOut} }; CLSID Converter_clsID = GUIDFromCString(L"{0B7FA55E-FA38-4671-A2F2-B8F300C955C4}"); const AMOVIESETUP_FILTER sudFilters[] = { {&__uuidof(CMPCVideoDecFilter), MPCVideoDecName, MERIT_NORMAL + 1, _countof(sudpPins), sudpPins, CLSID_LegacyAmFilterCategory}, {&Converter_clsID, MPCVideoConvName, MERIT_NORMAL + 1, _countof(sudpPinsUncompressed), sudpPinsUncompressed, CLSID_LegacyAmFilterCategory} // merit of video converter must be lower than merit of video renderers }; CFactoryTemplate g_Templates[] = { {sudFilters[0].strName, sudFilters[0].clsID, CreateInstance<CMPCVideoDecFilter>, nullptr, &sudFilters[0]}, {sudFilters[1].strName, sudFilters[1].clsID, CreateInstance<CMPCVideoDecFilter>, nullptr, &sudFilters[1]}, {L"CMPCVideoDecPropertyPage", &__uuidof(CMPCVideoDecSettingsWnd), CreateInstance<CInternalPropertyPageTempl<CMPCVideoDecSettingsWnd> >}, {L"CMPCVideoDecPropertyPage2", &__uuidof(CMPCVideoDecCodecWnd), CreateInstance<CInternalPropertyPageTempl<CMPCVideoDecCodecWnd> >}, }; int g_cTemplates = _countof(g_Templates); STDAPI DllRegisterServer() { return AMovieDllRegisterServer2(TRUE); } STDAPI DllUnregisterServer() { return AMovieDllRegisterServer2(FALSE); } #include "../../filters/Filters.h" CFilterApp theApp; #else #include "../../../DSUtil/Profile.h" #endif BOOL CALLBACK EnumFindProcessWnd (HWND hwnd, LPARAM lParam) { DWORD procid = 0; WCHAR WindowClass[40]; GetWindowThreadProcessId(hwnd, &procid); GetClassName(hwnd, WindowClass, _countof(WindowClass)); if (procid == GetCurrentProcessId() && wcscmp(WindowClass, MPC_WND_CLASS_NAMEW) == 0) { HWND* pWnd = (HWND*) lParam; *pWnd = hwnd; return FALSE; } return TRUE; } #define CleanDXVAVariable() { m_DXVADecoderGUID = GUID_NULL; ZeroMemory(&m_DXVA2Config, sizeof(m_DXVA2Config)); } // CMPCVideoDecFilter CMPCVideoDecFilter::CMPCVideoDecFilter(LPUNKNOWN lpunk, HRESULT* phr) : CBaseVideoFilter(L"MPC - Video decoder", lpunk, phr, __uuidof(this)) , m_nThreadNumber(0) , m_nDiscardMode(AVDISCARD_DEFAULT) , m_nScanType(SCAN_AUTO) , m_nARMode(2) , m_nDXVACheckCompatibility(1) , m_nDXVA_SD(0) , m_nSwRGBLevels(0) , m_pAVCodec(nullptr) , m_pAVCtx(nullptr) , m_pFrame(nullptr) , m_pParser(nullptr) , m_nCodecNb(-1) , m_nCodecId(AV_CODEC_ID_NONE) , m_bCalculateStopTime(false) , m_bReorderBFrame(false) , m_nBFramePos(0) , m_bWaitKeyFrame(false) , m_DXVADecoderGUID(GUID_NULL) , m_nActiveCodecs(CODECS_ALL & ~CODEC_H264_MVC) , m_rtAvrTimePerFrame(0) , m_rtLastStop(0) , m_rtStartCache(INVALID_TIME) , m_bDXVACompatible(true) , m_nARX(0) , m_nARY(0) , m_bUseDXVA(true) , m_bUseFFmpeg(true) , m_pDXVADecoder(nullptr) , m_pVideoOutputFormat(nullptr) , m_nVideoOutputCount(0) , m_hDevice(INVALID_HANDLE_VALUE) , m_bWaitingForKeyFrame(TRUE) , m_bRVDropBFrameTimings(FALSE) , m_bInterlaced(FALSE) , m_dwSYNC(0) , m_bDecodingStart(FALSE) , m_bHighBitdepth(FALSE) , m_dRate(1.0) , m_pMSDKDecoder(nullptr) , m_iMvcOutputMode(MVC_OUTPUT_Auto) , m_bMvcSwapLR(false) , m_MVC_Base_View_R_flag(FALSE) , m_dxva_pix_fmt(AV_PIX_FMT_NONE) { if (phr) { *phr = S_OK; } if (m_pOutput) { delete m_pOutput; } m_pOutput = DNew CVideoDecOutputPin(L"CVideoDecOutputPin", this, phr, L"Output"); if (!m_pOutput) { *phr = E_OUTOFMEMORY; return; } for (int i = 0; i < PixFmt_count; i++) { if (i == PixFmt_AYUV || i == PixFmt_RGB48) { m_fPixFmts[i] = false; } else { m_fPixFmts[i] = true; } } memset(&m_DDPixelFormat, 0, sizeof(m_DDPixelFormat)); memset(&m_DXVAFilters, false, sizeof(m_DXVAFilters)); memset(&m_VideoFilters, false, sizeof(m_VideoFilters)); m_VideoFilters[VDEC_UNCOMPRESSED] = true; #ifdef REGISTER_FILTER CRegKey key; ULONG len = 255; if (ERROR_SUCCESS == key.Open(HKEY_CURRENT_USER, OPT_REGKEY_VideoDec, KEY_READ)) { DWORD dw; if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_ThreadNumber, dw)) { m_nThreadNumber = dw; } if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_DiscardMode, dw)) { m_nDiscardMode = dw; } if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_ScanType, dw)) { m_nScanType = (MPC_SCAN_TYPE)dw; } if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_ARMode, dw)) { m_nARMode = dw; } if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_DXVACheck, dw)) { m_nDXVACheckCompatibility = dw; } if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_DisableDXVA_SD, dw)) { m_nDXVA_SD = dw; } for (int i = 0; i < PixFmt_count; i++) { CString optname = OPT_SW_prefix; optname += GetSWOF(i)->name; if (ERROR_SUCCESS == key.QueryDWORDValue(optname, dw)) { m_fPixFmts[i] = !!dw; } } if (ERROR_SUCCESS == key.QueryDWORDValue(OPT_SwRGBLevels, dw)) { m_nSwRGBLevels = dw; } } if (ERROR_SUCCESS == key.Open(HKEY_CURRENT_USER, OPT_REGKEY_VCodecs, KEY_READ)) { m_nActiveCodecs = 0; for (size_t i = 0; i < _countof(vcodecs); i++) { DWORD dw = 1; key.QueryDWORDValue(vcodecs[i].opt_name, dw); if (dw) { m_nActiveCodecs |= vcodecs[i].flag; } } } #else CProfile& profile = AfxGetProfile(); profile.ReadInt(OPT_SECTION_VideoDec, OPT_ThreadNumber, m_nThreadNumber, 0, 16); profile.ReadInt(OPT_SECTION_VideoDec, OPT_ScanType, *(int*)&m_nScanType); profile.ReadInt(OPT_SECTION_VideoDec, OPT_ARMode, m_nARMode); profile.ReadInt(OPT_SECTION_VideoDec, OPT_DiscardMode, m_nDiscardMode); profile.ReadInt(OPT_SECTION_VideoDec, OPT_DXVACheck, m_nDXVACheckCompatibility); profile.ReadInt(OPT_SECTION_VideoDec, OPT_DisableDXVA_SD, m_nDXVA_SD); profile.ReadInt(OPT_SECTION_VideoDec, OPT_SwRGBLevels, m_nSwRGBLevels); for (int i = 0; i < PixFmt_count; i++) { CString optname = OPT_SW_prefix; optname += GetSWOF(i)->name; profile.ReadBool(OPT_SECTION_VideoDec, optname, m_fPixFmts[i]); } #endif if (m_nDiscardMode != AVDISCARD_BIDIR) { m_nDiscardMode = AVDISCARD_DEFAULT; } m_nDXVACheckCompatibility = std::clamp(m_nDXVACheckCompatibility, 0, 3); if (m_nScanType > SCAN_PROGRESSIVE) { m_nScanType = SCAN_AUTO; } if (m_nSwRGBLevels != 1) { m_nSwRGBLevels = 0; } #ifdef DEBUG_OR_LOG av_log_set_callback(ff_log); #else av_log_set_callback(nullptr); #endif m_FormatConverter.SetOptions(m_nSwRGBLevels); HWND hWnd = nullptr; EnumWindows(EnumFindProcessWnd, (LPARAM)&hWnd); DetectVideoCard(hWnd); #ifdef _DEBUG // Check codec definition table size_t nCodecs = _countof(ffCodecs); size_t nPinTypes = _countof(sudPinTypesIn); size_t nPinTypesUncompressed = _countof(sudPinTypesInUncompressed); ASSERT(nCodecs == nPinTypes + nPinTypesUncompressed ); for (size_t i = 0; i < nPinTypes; i++) { ASSERT(ffCodecs[i].clsMinorType == sudPinTypesIn[i].clsMinorType); } for (size_t i = 0; i < nPinTypesUncompressed ; i++) { ASSERT(ffCodecs[nPinTypes + i].clsMinorType == sudPinTypesInUncompressed[i].clsMinorType); } #endif } CMPCVideoDecFilter::~CMPCVideoDecFilter() { Cleanup(); } void CMPCVideoDecFilter::DetectVideoCard(HWND hWnd) { m_nPCIVendor = 0; m_nPCIDevice = 0; m_VideoDriverVersion = 0; auto pD3D9 = D3D9Helper::Direct3DCreate9(); if (pD3D9) { D3DADAPTER_IDENTIFIER9 AdapID9 = {}; if (pD3D9->GetAdapterIdentifier(D3D9Helper::GetAdapter(pD3D9, hWnd), 0, &AdapID9) == S_OK) { m_nPCIVendor = AdapID9.VendorId; m_nPCIDevice = AdapID9.DeviceId; m_VideoDriverVersion = AdapID9.DriverVersion.QuadPart; if (SysVersion::IsWin81orLater() && (m_VideoDriverVersion & 0xffff00000000) == 0 && (m_VideoDriverVersion & 0xffff) == 0) { // fix bug in GetAdapterIdentifier() m_VideoDriverVersion = (m_VideoDriverVersion & 0xffff000000000000) | ((m_VideoDriverVersion & 0xffff0000) << 16) | 0xffffffff; } m_strDeviceDescription.Format(L"%S (%04X:%04X)", AdapID9.Description, m_nPCIVendor, m_nPCIDevice); } pD3D9->Release(); } } REFERENCE_TIME CMPCVideoDecFilter::GetFrameDuration() { if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO || m_nCodecId == AV_CODEC_ID_MPEG1VIDEO) { if (m_pAVCtx->time_base.num && m_pAVCtx->time_base.den) { REFERENCE_TIME frame_duration = (UNITS * m_pAVCtx->time_base.num / m_pAVCtx->time_base.den) * m_pAVCtx->ticks_per_frame; return frame_duration; } } return m_rtAvrTimePerFrame; } void CMPCVideoDecFilter::UpdateFrameTime(REFERENCE_TIME& rtStart, REFERENCE_TIME& rtStop) { if (rtStart == INVALID_TIME) { rtStart = m_rtLastStop; rtStop = INVALID_TIME; } if (rtStop == INVALID_TIME || m_bCalculateStopTime) { REFERENCE_TIME frame_duration = GetFrameDuration(); if (m_pFrame && m_pFrame->repeat_pict) { frame_duration = frame_duration * 3 / 2; } rtStop = rtStart + (frame_duration / m_dRate); } m_rtLastStop = rtStop; } void CMPCVideoDecFilter::GetFrameTimeStamp(AVFrame* pFrame, REFERENCE_TIME& rtStart, REFERENCE_TIME& rtStop) { // Reorder B-Frames if needed if (m_bReorderBFrame && m_pAVCtx->has_b_frames) { rtStart = m_tBFrameDelay[m_nBFramePos].rtStart; rtStop = m_tBFrameDelay[m_nBFramePos].rtStop; } else { rtStart = pFrame->best_effort_timestamp; if (pFrame->pkt_duration) { rtStop = rtStart + pFrame->pkt_duration; } else { rtStop = INVALID_TIME; } } } bool CMPCVideoDecFilter::AddFrameSideData(IMediaSample* pSample, AVFrame* pFrame) { CheckPointer(pSample, false); CheckPointer(pFrame, false); CComPtr<IMediaSideData> pMediaSideData; if (SUCCEEDED(pSample->QueryInterface(&pMediaSideData))) { HRESULT hr = E_FAIL; if (AVFrameSideData* sd = av_frame_get_side_data(pFrame, AV_FRAME_DATA_MASTERING_DISPLAY_METADATA)) { if (sd->size == sizeof(AVMasteringDisplayMetadata)) { AVMasteringDisplayMetadata* metadata = (AVMasteringDisplayMetadata*)sd->data; MediaSideDataHDR hdr = { 0 }; if (metadata->has_primaries) { // export the display primaries in GBR order hdr.display_primaries_x[0] = av_q2d(metadata->display_primaries[1][0]); hdr.display_primaries_y[0] = av_q2d(metadata->display_primaries[1][1]); hdr.display_primaries_x[1] = av_q2d(metadata->display_primaries[2][0]); hdr.display_primaries_y[1] = av_q2d(metadata->display_primaries[2][1]); hdr.display_primaries_x[2] = av_q2d(metadata->display_primaries[0][0]); hdr.display_primaries_y[2] = av_q2d(metadata->display_primaries[0][1]); hdr.white_point_x = av_q2d(metadata->white_point[0]); hdr.white_point_y = av_q2d(metadata->white_point[1]); } if (metadata->has_luminance) { hdr.max_display_mastering_luminance = av_q2d(metadata->max_luminance); hdr.min_display_mastering_luminance = av_q2d(metadata->min_luminance); } hr = pMediaSideData->SetSideData(IID_MediaSideDataHDR, (const BYTE*)&hdr, sizeof(hdr)); } else { DLog(L"CMPCVideoDecFilter::AddFrameSideData(): Found HDR data of an unexpected size (%d)", sd->size); } } else if (m_FilterInfo.masterDataHDR) { hr = pMediaSideData->SetSideData(IID_MediaSideDataHDR, (const BYTE*)m_FilterInfo.masterDataHDR, sizeof(MediaSideDataHDR)); SAFE_DELETE(m_FilterInfo.masterDataHDR); } if (AVFrameSideData* sd = av_frame_get_side_data(pFrame, AV_FRAME_DATA_CONTENT_LIGHT_LEVEL)) { if (sd->size == sizeof(AVContentLightMetadata)) { hr = pMediaSideData->SetSideData(IID_MediaSideDataHDRContentLightLevel, (const BYTE*)sd->data, sd->size); } else { DLog(L"CMPCVideoDecFilter::AddFrameSideData(): Found HDR Light Level data of an unexpected size (%d)", sd->size); } } else if (m_FilterInfo.HDRContentLightLevel) { hr = pMediaSideData->SetSideData(IID_MediaSideDataHDRContentLightLevel, (const BYTE*)m_FilterInfo.HDRContentLightLevel, sizeof(MediaSideDataHDRContentLightLevel)); SAFE_DELETE(m_FilterInfo.HDRContentLightLevel); } return (hr == S_OK); } return false; } // some codecs can reset the values width/height on initialization int CMPCVideoDecFilter::PictWidth() { return m_pAVCtx->width ? m_pAVCtx->width : m_pAVCtx->coded_width; } int CMPCVideoDecFilter::PictHeight() { return m_pAVCtx->height ? m_pAVCtx->height : m_pAVCtx->coded_height; } static bool IsFFMPEGEnabled(FFMPEG_CODECS ffcodec, const bool FFmpegFilters[VDEC_COUNT]) { if (ffcodec.FFMPEGCode < 0 || ffcodec.FFMPEGCode >= VDEC_COUNT) { return false; } return FFmpegFilters[ffcodec.FFMPEGCode]; } static bool IsDXVAEnabled(FFMPEG_CODECS ffcodec, const bool DXVAFilters[VDEC_DXVA_COUNT]) { if (ffcodec.DXVACode < 0 || ffcodec.DXVACode >= VDEC_DXVA_COUNT) { return false; } return DXVAFilters[ffcodec.DXVACode]; } int CMPCVideoDecFilter::FindCodec(const CMediaType* mtIn, BOOL bForced/* = FALSE*/) { m_bUseFFmpeg = false; m_bUseDXVA = false; for (size_t i = 0; i < _countof(ffCodecs); i++) if (mtIn->subtype == *ffCodecs[i].clsMinorType) { #ifndef REGISTER_FILTER m_bUseFFmpeg = bForced || IsFFMPEGEnabled(ffCodecs[i], m_VideoFilters); m_bUseDXVA = bForced || IsDXVAEnabled(ffCodecs[i], m_DXVAFilters); return ((m_bUseDXVA || m_bUseFFmpeg) ? i : -1); #else bool bCodecActivated = false; m_bUseFFmpeg = true; switch (ffCodecs[i].nFFCodec) { case AV_CODEC_ID_FLV1 : case AV_CODEC_ID_VP6F : bCodecActivated = (m_nActiveCodecs & CODEC_FLASH) != 0; break; case AV_CODEC_ID_MPEG4 : if ((*ffCodecs[i].clsMinorType == MEDIASUBTYPE_DX50) || // DivX (*ffCodecs[i].clsMinorType == MEDIASUBTYPE_dx50) || (*ffCodecs[i].clsMinorType == MEDIASUBTYPE_DIVX) || (*ffCodecs[i].clsMinorType == MEDIASUBTYPE_divx) || (*ffCodecs[i].clsMinorType == MEDIASUBTYPE_Divx) ) { bCodecActivated = (m_nActiveCodecs & CODEC_DIVX) != 0; } else { bCodecActivated = (m_nActiveCodecs & CODEC_XVID) != 0; // Xvid/MPEG-4 } break; case AV_CODEC_ID_WMV1 : case AV_CODEC_ID_WMV2 : case AV_CODEC_ID_WMV3IMAGE : bCodecActivated = (m_nActiveCodecs & CODEC_WMV) != 0; break; case AV_CODEC_ID_WMV3 : m_bUseDXVA = (m_nActiveCodecs & CODEC_WMV3_DXVA) != 0; m_bUseFFmpeg = (m_nActiveCodecs & CODEC_WMV) != 0; bCodecActivated = m_bUseDXVA || m_bUseFFmpeg; break; case AV_CODEC_ID_MSMPEG4V3 : case AV_CODEC_ID_MSMPEG4V2 : case AV_CODEC_ID_MSMPEG4V1 : bCodecActivated = (m_nActiveCodecs & CODEC_MSMPEG4) != 0; break; case AV_CODEC_ID_H264 : if ((*ffCodecs[i].clsMinorType == MEDIASUBTYPE_MVC1) || (*ffCodecs[i].clsMinorType == MEDIASUBTYPE_AMVC)) { bCodecActivated = (m_nActiveCodecs & CODEC_H264_MVC) != 0; } else { m_bUseDXVA = (m_nActiveCodecs & CODEC_H264_DXVA) != 0; m_bUseFFmpeg = (m_nActiveCodecs & CODEC_H264) != 0; bCodecActivated = m_bUseDXVA || m_bUseFFmpeg; } break; case AV_CODEC_ID_HEVC : m_bUseDXVA = (m_nActiveCodecs & CODEC_HEVC_DXVA) != 0; m_bUseFFmpeg = (m_nActiveCodecs & CODEC_HEVC) != 0; bCodecActivated = m_bUseDXVA || m_bUseFFmpeg; break; case AV_CODEC_ID_SVQ3 : case AV_CODEC_ID_SVQ1 : bCodecActivated = (m_nActiveCodecs & CODEC_SVQ3) != 0; break; case AV_CODEC_ID_H263 : bCodecActivated = (m_nActiveCodecs & CODEC_H263) != 0; break; case AV_CODEC_ID_DIRAC : bCodecActivated = (m_nActiveCodecs & CODEC_DIRAC) != 0; break; case AV_CODEC_ID_DVVIDEO : bCodecActivated = (m_nActiveCodecs & CODEC_DV) != 0; break; case AV_CODEC_ID_THEORA : bCodecActivated = (m_nActiveCodecs & CODEC_THEORA) != 0; break; case AV_CODEC_ID_VC1 : m_bUseDXVA = (m_nActiveCodecs & CODEC_VC1_DXVA) != 0; m_bUseFFmpeg = (m_nActiveCodecs & CODEC_VC1) != 0; bCodecActivated = m_bUseDXVA || m_bUseFFmpeg; break; case AV_CODEC_ID_VC1IMAGE : bCodecActivated = (m_nActiveCodecs & CODEC_VC1) != 0; break; case AV_CODEC_ID_AMV : bCodecActivated = (m_nActiveCodecs & CODEC_AMVV) != 0; break; case AV_CODEC_ID_LAGARITH : bCodecActivated = (m_nActiveCodecs & CODEC_LOSSLESS) != 0; break; case AV_CODEC_ID_VP3 : case AV_CODEC_ID_VP5 : case AV_CODEC_ID_VP6 : case AV_CODEC_ID_VP6A : bCodecActivated = (m_nActiveCodecs & CODEC_VP356) != 0; break; case AV_CODEC_ID_VP7 : case AV_CODEC_ID_VP8 : bCodecActivated = (m_nActiveCodecs & CODEC_VP89) != 0; break; case AV_CODEC_ID_VP9 : m_bUseDXVA = (m_nActiveCodecs & CODEC_VP9_DXVA) != 0; m_bUseFFmpeg = (m_nActiveCodecs & CODEC_VP89) != 0; bCodecActivated = m_bUseDXVA || m_bUseFFmpeg; break; case AV_CODEC_ID_MJPEG : case AV_CODEC_ID_MJPEGB : bCodecActivated = (m_nActiveCodecs & CODEC_MJPEG) != 0; break; case AV_CODEC_ID_INDEO3 : case AV_CODEC_ID_INDEO4 : case AV_CODEC_ID_INDEO5 : bCodecActivated = (m_nActiveCodecs & CODEC_INDEO) != 0; break; case AV_CODEC_ID_UTVIDEO : bCodecActivated = (m_nActiveCodecs & CODEC_UTVD) != 0; break; case AV_CODEC_ID_CSCD : case AV_CODEC_ID_TSCC : case AV_CODEC_ID_TSCC2 : case AV_CODEC_ID_VMNC : bCodecActivated = (m_nActiveCodecs & CODEC_SCREC) != 0; break; case AV_CODEC_ID_RV10 : case AV_CODEC_ID_RV20 : case AV_CODEC_ID_RV30 : case AV_CODEC_ID_RV40 : bCodecActivated = (m_nActiveCodecs & CODEC_REALV) != 0; break; case AV_CODEC_ID_MPEG2VIDEO : m_bUseDXVA = (m_nActiveCodecs & CODEC_MPEG2_DXVA) != 0; m_bUseFFmpeg = (m_nActiveCodecs & CODEC_MPEG2) != 0; bCodecActivated = m_bUseDXVA || m_bUseFFmpeg; break; case AV_CODEC_ID_MPEG1VIDEO : bCodecActivated = (m_nActiveCodecs & CODEC_MPEG1) != 0; break; case AV_CODEC_ID_PRORES : bCodecActivated = (m_nActiveCodecs & CODEC_PRORES) != 0; break; case AV_CODEC_ID_BINKVIDEO : bCodecActivated = (m_nActiveCodecs & CODEC_BINKV) != 0; break; case AV_CODEC_ID_PNG : bCodecActivated = (m_nActiveCodecs & CODEC_PNG) != 0; break; case AV_CODEC_ID_CLLC : case AV_CODEC_ID_HQ_HQA : case AV_CODEC_ID_HQX : bCodecActivated = (m_nActiveCodecs & CODEC_CANOPUS) != 0; break; case AV_CODEC_ID_CFHD : bCodecActivated = (m_nActiveCodecs & VDEC_CINEFORM) != 0; break; case AV_CODEC_ID_V210 : case AV_CODEC_ID_V410 : case AV_CODEC_ID_R210 : case AV_CODEC_ID_R10K : case AV_CODEC_ID_RAWVIDEO : bCodecActivated = (m_nActiveCodecs & CODEC_UNCOMPRESSED) != 0; break; case AV_CODEC_ID_DNXHD : bCodecActivated = (m_nActiveCodecs & CODEC_DNXHD) != 0; break; case AV_CODEC_ID_CINEPAK : bCodecActivated = (m_nActiveCodecs & CODEC_CINEPAK) != 0; break; case AV_CODEC_ID_8BPS : case AV_CODEC_ID_QTRLE : case AV_CODEC_ID_RPZA : bCodecActivated = (m_nActiveCodecs & CODEC_QT) != 0; break; case AV_CODEC_ID_HAP : bCodecActivated = (m_nActiveCodecs & CODEC_HAP) != 0; break; case AV_CODEC_ID_AV1 : bCodecActivated = (m_nActiveCodecs & CODEC_AV1) != 0; break; } if (!bCodecActivated && !bForced) { m_bUseFFmpeg = false; } return ((bForced || bCodecActivated) ? i : -1); #endif } return -1; } void CMPCVideoDecFilter::Cleanup() { CAutoLock cAutoLock(&m_csReceive); CleanupFFmpeg(); SAFE_DELETE(m_pMSDKDecoder); SAFE_DELETE(m_pDXVADecoder); SAFE_DELETE_ARRAY(m_pVideoOutputFormat); CleanupD3DResources(); m_FilterInfo.Clear(); } void CMPCVideoDecFilter::CleanupD3DResources() { if (m_hDevice != INVALID_HANDLE_VALUE) { m_pDeviceManager->CloseDeviceHandle(m_hDevice); m_hDevice = INVALID_HANDLE_VALUE; } m_pDeviceManager.Release(); m_pDecoderService.Release(); } void CMPCVideoDecFilter::CleanupFFmpeg() { m_pAVCodec = nullptr; av_parser_close(m_pParser); m_pParser = nullptr; if (m_pAVCtx) { av_freep(&m_pAVCtx->hwaccel_context); avcodec_free_context(&m_pAVCtx); } av_frame_free(&m_pFrame); m_FormatConverter.Cleanup(); m_nCodecNb = -1; m_nCodecId = AV_CODEC_ID_NONE; } STDMETHODIMP CMPCVideoDecFilter::NonDelegatingQueryInterface(REFIID riid, void** ppv) { return QI(IMPCVideoDecFilter) QI(ISpecifyPropertyPages) QI(ISpecifyPropertyPages2) __super::NonDelegatingQueryInterface(riid, ppv); } HRESULT CMPCVideoDecFilter::CheckInputType(const CMediaType* mtIn) { for (size_t i = 0; i < _countof(sudPinTypesIn); i++) { if ((mtIn->majortype == *sudPinTypesIn[i].clsMajorType) && (mtIn->subtype == *sudPinTypesIn[i].clsMinorType)) { return S_OK; } } for (size_t i = 0; i < _countof(sudPinTypesInUncompressed); i++) { if ((mtIn->majortype == *sudPinTypesInUncompressed[i].clsMajorType) && (mtIn->subtype == *sudPinTypesInUncompressed[i].clsMinorType)) { return S_OK; } } return VFW_E_TYPE_NOT_ACCEPTED; } HRESULT CMPCVideoDecFilter::CheckTransform(const CMediaType* mtIn, const CMediaType* mtOut) { return CheckInputType(mtIn); // TODO - add check output MediaType } HRESULT CMPCVideoDecFilter::SetMediaType(PIN_DIRECTION direction, const CMediaType *pmt) { if (direction == PINDIR_INPUT) { HRESULT hr = InitDecoder(pmt); if (FAILED(hr)) { return hr; } BuildOutputFormat(); if (UseDXVA2() && (m_pCurrentMediaType != *pmt)) { hr = ReinitDXVA2Decoder(); if (FAILED(hr)) { return hr; } } m_bDecodingStart = FALSE; m_pCurrentMediaType = *pmt; } else if (direction == PINDIR_OUTPUT) { BITMAPINFOHEADER bihOut; if (!ExtractBIH(&m_pOutput->CurrentMediaType(), &bihOut)) { return E_FAIL; } m_FormatConverter.UpdateOutput2(bihOut.biCompression, bihOut.biWidth, bihOut.biHeight); } return __super::SetMediaType(direction, pmt); } bool CMPCVideoDecFilter::IsDXVASupported() { if (m_nCodecId != AV_CODEC_ID_NONE) { // Enabled by user ? if (m_bUseDXVA) { // is the file compatible ? if (m_bDXVACompatible) { // Does the codec suppport DXVA ? for (int i = 0; i < _countof(DXVAModes); i++) { if (m_nCodecId == DXVAModes[i].nCodecId) { return true; } } } } } return false; } HRESULT CMPCVideoDecFilter::FindDecoderConfiguration() { DLog(L"CMPCVideoDecFilter::FindDecoderConfiguration(DXVA2)"); HRESULT hr = E_FAIL; CleanDXVAVariable(); if (m_pDecoderService) { UINT cDecoderGuids = 0; GUID* pDecoderGuids = nullptr; GUID decoderGuid = GUID_NULL; BOOL bFoundDXVA2Configuration = FALSE; DXVA2_ConfigPictureDecode config = { 0 }; if (SUCCEEDED(hr = m_pDecoderService->GetDecoderDeviceGuids(&cDecoderGuids, &pDecoderGuids)) && cDecoderGuids) { std::vector<GUID> supportedDecoderGuids; DLog(L" => Enumerating supported DXVA2 modes:"); for (UINT iGuid = 0; iGuid < cDecoderGuids; iGuid++) { const auto& guid = pDecoderGuids[iGuid]; #ifdef DEBUG_OR_LOG CString msg; msg.Format(L" %s", GetGUIDString(guid)); #endif if (IsSupportedDecoderMode(guid)) { #ifdef DEBUG_OR_LOG msg.Append(L" - supported"); #endif if (guid == DXVA2_ModeH264_E || guid == DXVA2_ModeH264_F) { supportedDecoderGuids.insert(supportedDecoderGuids.cbegin(), guid); } else { supportedDecoderGuids.emplace_back(guid); } } #ifdef DEBUG_OR_LOG DLog(msg); #endif } if (!supportedDecoderGuids.empty()) { for (const auto& guid : supportedDecoderGuids) { DLog(L" => Attempt : %s", GetGUIDString(guid)); if (DXVA2_Intel_H264_ClearVideo == guid) { const int width_mbs = m_nSurfaceWidth / 16; const int height_mbs = m_nSurfaceWidth / 16; const int max_ref_frames_dpb41 = std::min(11, 32768 / (width_mbs * height_mbs)); if (m_pAVCtx->refs > max_ref_frames_dpb41) { DLog(L" => Too many reference frames for Intel H.264 ClearVideo decoder, skip"); continue; } } // Find a configuration that we support. if (FAILED(hr = FindDXVA2DecoderConfiguration(m_pDecoderService, guid, &config, &bFoundDXVA2Configuration))) { break; } if (bFoundDXVA2Configuration) { // Found a good configuration. Save the GUID. decoderGuid = guid; DLog(L" => Use : %s", GetGUIDString(decoderGuid)); break; } } } } if (pDecoderGuids) { CoTaskMemFree(pDecoderGuids); } if (!bFoundDXVA2Configuration) { hr = E_FAIL; // Unable to find a configuration. } if (SUCCEEDED(hr)) { m_DXVA2Config = config; m_DXVADecoderGUID = decoderGuid; } } return hr; } #define H264_CHECK_PROFILE(profile) \ (((profile) & ~FF_PROFILE_H264_CONSTRAINED) <= FF_PROFILE_H264_HIGH) #define HEVC_CHECK_PROFILE(profile) \ ((profile) <= FF_PROFILE_HEVC_MAIN_10) #define VP9_CHECK_PROFILE(profile) \ ((profile) == FF_PROFILE_VP9_0 || (profile) == FF_PROFILE_VP9_2) static bool check_dxva_compatible(const AVCodecID& codec, const AVPixelFormat& pix_fmt, const int& profile) { switch (codec) { case AV_CODEC_ID_MPEG2VIDEO: if (pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUVJ420P) { return false; } break; case AV_CODEC_ID_H264: if (pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUVJ420P) { return false; } if (profile != FF_PROFILE_UNKNOWN && !H264_CHECK_PROFILE(profile)) { return false; } break; case AV_CODEC_ID_HEVC: if (pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUVJ420P && pix_fmt != AV_PIX_FMT_YUV420P10) { return false; } if (profile != FF_PROFILE_UNKNOWN && !HEVC_CHECK_PROFILE(profile)) { return false; } break; case AV_CODEC_ID_VP9: if (pix_fmt != AV_PIX_FMT_YUV420P && pix_fmt != AV_PIX_FMT_YUVJ420P && pix_fmt != AV_PIX_FMT_YUV420P10) { return false; } if (profile != FF_PROFILE_UNKNOWN && !VP9_CHECK_PROFILE(profile)) { return false; } break; case AV_CODEC_ID_WMV3: case AV_CODEC_ID_VC1: if (profile == FF_PROFILE_VC1_COMPLEX) { return false; } } return true; } HRESULT CMPCVideoDecFilter::InitDecoder(const CMediaType *pmt) { DLog(L"CMPCVideoDecFilter::InitDecoder()"); const BOOL bChangeType = (m_pCurrentMediaType != *pmt); const BOOL bReinit = (m_pAVCtx != nullptr); int64_t x264_build = -1; if (m_nCodecId == AV_CODEC_ID_H264 && bReinit && !bChangeType) { int64_t val = -1; if (av_opt_get_int(m_pAVCtx->priv_data, "x264_build", 0, &val) >= 0) { x264_build = val; } } redo: CleanupFFmpeg(); const int nNewCodec = FindCodec(pmt, bReinit); if (nNewCodec == -1) { return VFW_E_TYPE_NOT_ACCEPTED; } // Prevent connection to the video decoder - need to support decoding of uncompressed video (v210, V410, Y8, I420) CComPtr<IBaseFilter> pFilter = GetFilterFromPin(m_pInput->GetConnected()); if (pFilter && IsVideoDecoder(pFilter, true)) { return VFW_E_TYPE_NOT_ACCEPTED; } m_nCodecNb = nNewCodec; if (bChangeType) { ExtractAvgTimePerFrame(pmt, m_rtAvrTimePerFrame); int wout, hout; ExtractDim(pmt, wout, hout, m_nARX, m_nARY); UNREFERENCED_PARAMETER(wout); UNREFERENCED_PARAMETER(hout); } m_bMVC_Output_TopBottom = FALSE; if (pmt->subtype == MEDIASUBTYPE_AMVC || pmt->subtype == MEDIASUBTYPE_MVC1) { if (!m_pMSDKDecoder) { m_pMSDKDecoder = DNew CMSDKDecoder(this); } HRESULT hr = m_pMSDKDecoder->InitDecoder(pmt); if (hr != S_OK) { SAFE_DELETE(m_pMSDKDecoder); } if (m_pMSDKDecoder) { m_bMVC_Output_TopBottom = m_iMvcOutputMode == MVC_OUTPUT_TopBottom; return S_OK; } return VFW_E_TYPE_NOT_ACCEPTED; } m_nCodecId = ffCodecs[nNewCodec].nFFCodec; m_pAVCodec = avcodec_find_decoder(m_nCodecId); CheckPointer(m_pAVCodec, VFW_E_UNSUPPORTED_VIDEO); if (bChangeType) { const CLSID clsidInput = GetCLSID(m_pInput->GetConnected()); const BOOL bNotTrustSourceTimeStamp = (clsidInput == GUIDFromCString(L"{A2E7EDBB-DCDD-4C32-A2A9-0CFBBE6154B4}") // Daum PotPlayer's MKV Source || clsidInput == CLSID_WMAsfReader); // WM ASF Reader m_bCalculateStopTime = (m_nCodecId == AV_CODEC_ID_H264 || m_nCodecId == AV_CODEC_ID_DIRAC || (m_nCodecId == AV_CODEC_ID_MPEG4 && pmt->formattype == FORMAT_MPEG2Video) || bNotTrustSourceTimeStamp); m_bRVDropBFrameTimings = (m_nCodecId == AV_CODEC_ID_RV10 || m_nCodecId == AV_CODEC_ID_RV20 || m_nCodecId == AV_CODEC_ID_RV30 || m_nCodecId == AV_CODEC_ID_RV40); auto ReadSourceHeader = [&]() { if (m_dwSYNC != 0) { return; } m_dwSYNC = -1; CString fn; BeginEnumFilters(m_pGraph, pEF, pBF) { CComQIPtr<IFileSourceFilter> pFSF = pBF; if (pFSF) { LPOLESTR pFN = nullptr; AM_MEDIA_TYPE mt; if (SUCCEEDED(pFSF->GetCurFile(&pFN, &mt)) && pFN && *pFN) { fn = CString(pFN); CoTaskMemFree(pFN); } break; } } EndEnumFilters if (!fn.IsEmpty() && ::PathFileExistsW(fn)) { CFile f; CFileException fileException; if (!f.Open(fn, CFile::modeRead | CFile::typeBinary | CFile::shareDenyNone, &fileException)) { DLog(L"CMPCVideoDecFilter::ReadSource() : Can't open file '%s', error = %u", fn, fileException.m_cause); return; } f.Read(&m_dwSYNC, sizeof(m_dwSYNC)); f.Close(); } }; auto IsAVI = [&]() { ReadSourceHeader(); return (m_dwSYNC == MAKEFOURCC('R','I','F','F')); }; auto IsOGG = [&]() { ReadSourceHeader(); return (m_dwSYNC == MAKEFOURCC('O','g','g','S')); }; // Enable B-Frame reorder m_bReorderBFrame = !(clsidInput == __uuidof(CMpegSourceFilter) || clsidInput == __uuidof(CMpegSplitterFilter)) && !(m_pAVCodec->capabilities & AV_CODEC_CAP_FRAME_THREADS) && !(m_nCodecId == AV_CODEC_ID_MPEG1VIDEO || m_nCodecId == AV_CODEC_ID_MPEG2VIDEO) || (m_nCodecId == AV_CODEC_ID_MPEG4 && pmt->formattype != FORMAT_MPEG2Video) || clsidInput == __uuidof(CAviSourceFilter) || clsidInput == __uuidof(CAviSplitterFilter) || clsidInput == __uuidof(COggSourceFilter) || clsidInput == __uuidof(COggSplitterFilter) || IsAVI() || IsOGG(); } m_pAVCtx = avcodec_alloc_context3(m_pAVCodec); CheckPointer(m_pAVCtx, E_POINTER); if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO || m_nCodecId == AV_CODEC_ID_MPEG1VIDEO || pmt->subtype == MEDIASUBTYPE_H264 || pmt->subtype == MEDIASUBTYPE_h264 || pmt->subtype == MEDIASUBTYPE_X264 || pmt->subtype == MEDIASUBTYPE_x264 || pmt->subtype == MEDIASUBTYPE_H264_bis || pmt->subtype == MEDIASUBTYPE_HEVC) { m_pParser = av_parser_init(m_nCodecId); } if (bReinit && m_nDecoderMode == MODE_SOFTWARE) { m_bUseDXVA = false; } SetThreadCount(); m_pFrame = av_frame_alloc(); CheckPointer(m_pFrame, E_POINTER); BITMAPINFOHEADER *pBMI = nullptr; bool bInterlacedFieldPerSample = false; if (pmt->formattype == FORMAT_VideoInfo) { VIDEOINFOHEADER* vih = (VIDEOINFOHEADER*)pmt->pbFormat; pBMI = &vih->bmiHeader; } else if (pmt->formattype == FORMAT_VideoInfo2) { VIDEOINFOHEADER2* vih2 = (VIDEOINFOHEADER2*)pmt->pbFormat; pBMI = &vih2->bmiHeader; bInterlacedFieldPerSample = vih2->dwInterlaceFlags & AMINTERLACE_IsInterlaced && vih2->dwInterlaceFlags & AMINTERLACE_1FieldPerSample; } else if (pmt->formattype == FORMAT_MPEGVideo) { MPEG1VIDEOINFO* mpgv = (MPEG1VIDEOINFO*)pmt->pbFormat; pBMI = &mpgv->hdr.bmiHeader; } else if (pmt->formattype == FORMAT_MPEG2Video) { MPEG2VIDEOINFO* mpg2v = (MPEG2VIDEOINFO*)pmt->pbFormat; pBMI = &mpg2v->hdr.bmiHeader; bInterlacedFieldPerSample = mpg2v->hdr.dwInterlaceFlags & AMINTERLACE_IsInterlaced && mpg2v->hdr.dwInterlaceFlags & AMINTERLACE_1FieldPerSample; } else { return VFW_E_INVALIDMEDIATYPE; } if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO && bInterlacedFieldPerSample && m_nPCIVendor == PCIV_ATI) { m_bUseDXVA = false; } if (bChangeType) { m_bWaitKeyFrame = m_nCodecId == AV_CODEC_ID_VC1 || m_nCodecId == AV_CODEC_ID_VC1IMAGE || m_nCodecId == AV_CODEC_ID_WMV3 || m_nCodecId == AV_CODEC_ID_WMV3IMAGE || m_nCodecId == AV_CODEC_ID_MPEG2VIDEO || m_nCodecId == AV_CODEC_ID_RV30 || m_nCodecId == AV_CODEC_ID_RV40 || m_nCodecId == AV_CODEC_ID_VP3 || m_nCodecId == AV_CODEC_ID_THEORA || m_nCodecId == AV_CODEC_ID_MPEG4; } m_pAVCtx->codec_id = m_nCodecId; m_pAVCtx->codec_tag = pBMI->biCompression ? pBMI->biCompression : pmt->subtype.Data1; if (m_pAVCtx->codec_tag == MAKEFOURCC('m','p','g','2')) { m_pAVCtx->codec_tag = MAKEFOURCC('M','P','E','G'); } m_pAVCtx->coded_width = pBMI->biWidth; m_pAVCtx->coded_height = abs(pBMI->biHeight); m_pAVCtx->bits_per_coded_sample = pBMI->biBitCount; m_pAVCtx->workaround_bugs = FF_BUG_AUTODETECT; m_pAVCtx->skip_frame = (AVDiscard)m_nDiscardMode; m_pAVCtx->opaque = this; if (IsDXVASupported()) { m_pAVCtx->hwaccel_context = (dxva_context *)av_mallocz(sizeof(dxva_context)); m_pAVCtx->get_format = av_get_format; m_pAVCtx->get_buffer2 = av_get_buffer; m_pAVCtx->slice_flags |= SLICE_FLAG_ALLOW_FIELD; } AllocExtradata(pmt); AVDictionary* options = nullptr; if (m_nCodecId == AV_CODEC_ID_H264 && x264_build != -1) { av_dict_set_int(&options, "x264_build", x264_build, 0); } avcodec_lock; const int ret = avcodec_open2(m_pAVCtx, m_pAVCodec, &options); avcodec_unlock; if (options) { av_dict_free(&options); } if (ret < 0) { return VFW_E_INVALIDMEDIATYPE; } if (m_nCodecId == AV_CODEC_ID_AV1 && m_pAVCtx->extradata) { if (AVCodecParserContext* pParser = av_parser_init(m_nCodecId)) { BYTE* pOutBuffer = nullptr; int pOutLen = 0; int used_bytes = av_parser_parse2(pParser, m_pAVCtx, &pOutBuffer, &pOutLen, m_pAVCtx->extradata, m_pAVCtx->extradata_size, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); if (pOutLen > 0) { m_pAVCtx->pix_fmt = (enum AVPixelFormat)pParser->format; } av_parser_close(pParser); } } FillAVCodecProps(m_pAVCtx, pBMI); if (pFilter) { CComPtr<IExFilterInfo> pIExFilterInfo; if (SUCCEEDED(pFilter->QueryInterface(&pIExFilterInfo))) { if (m_nCodecId == AV_CODEC_ID_H264) { int value = 0; if (SUCCEEDED(pIExFilterInfo->GetPropertyInt("VIDEO_DELAY", &value))) { m_pAVCtx->has_b_frames = value; } } if (bChangeType) { m_FilterInfo.Clear(); int value = 0; if (SUCCEEDED(pIExFilterInfo->GetPropertyInt("VIDEO_PROFILE", &value))) { m_FilterInfo.profile = value; } if (SUCCEEDED(pIExFilterInfo->GetPropertyInt("VIDEO_PIXEL_FORMAT", &value))) { m_FilterInfo.pix_fmt = value; } if (SUCCEEDED(pIExFilterInfo->GetPropertyInt("VIDEO_INTERLACED", &value))) { m_FilterInfo.interlaced = value; } if (!m_bReorderBFrame && (m_nCodecId == AV_CODEC_ID_H264 || m_nCodecId == AV_CODEC_ID_HEVC)) { if (SUCCEEDED(pIExFilterInfo->GetPropertyInt("VIDEO_FLAG_ONLY_DTS", &value)) && value == 1) { m_bReorderBFrame = true; } } unsigned size = 0; LPVOID pData = nullptr; if (SUCCEEDED(pIExFilterInfo->GetPropertyBin("VIDEO_COLOR_SPACE", &pData, &size))) { if (size == sizeof(ColorSpace)) { auto const colorSpace = (ColorSpace*)pData; if (colorSpace->MatrixCoefficients < AVCOL_SPC_NB && colorSpace->MatrixCoefficients != AVCOL_SPC_RGB && colorSpace->MatrixCoefficients != AVCOL_SPC_UNSPECIFIED && colorSpace->MatrixCoefficients != AVCOL_SPC_RESERVED) { m_FilterInfo.colorspace = colorSpace->MatrixCoefficients; } if (colorSpace->Primaries < AVCOL_PRI_NB && colorSpace->Primaries != AVCOL_PRI_RESERVED0 && colorSpace->Primaries != AVCOL_PRI_UNSPECIFIED && colorSpace->Primaries != AVCOL_PRI_RESERVED) { m_FilterInfo.color_primaries = colorSpace->Primaries; } if (colorSpace->TransferCharacteristics < AVCOL_TRC_NB && colorSpace->TransferCharacteristics != AVCOL_TRC_RESERVED0 && colorSpace->TransferCharacteristics != AVCOL_TRC_UNSPECIFIED && colorSpace->TransferCharacteristics != AVCOL_TRC_RESERVED) { m_FilterInfo.color_trc = colorSpace->TransferCharacteristics; } if (colorSpace->ChromaLocation < AVCHROMA_LOC_NB && colorSpace->ChromaLocation != AVCHROMA_LOC_UNSPECIFIED) { m_FilterInfo.chroma_sample_location = colorSpace->ChromaLocation; } if (colorSpace->Range < AVCOL_RANGE_NB && colorSpace->Range != AVCOL_RANGE_UNSPECIFIED) { m_FilterInfo.color_range = colorSpace->Range; } } LocalFree(pData); } if (SUCCEEDED(pIExFilterInfo->GetPropertyBin("HDR_MASTERING_METADATA", &pData, &size))) { if (size == sizeof(MediaSideDataHDR)) { m_FilterInfo.masterDataHDR = DNew MediaSideDataHDR; memcpy(m_FilterInfo.masterDataHDR, pData, size); } LocalFree(pData); } if (SUCCEEDED(pIExFilterInfo->GetPropertyBin("HDR_CONTENT_LIGHT_LEVEL", &pData, &size))) { if (size == sizeof(MediaSideDataHDRContentLightLevel)) { m_FilterInfo.HDRContentLightLevel = DNew MediaSideDataHDRContentLightLevel; memcpy(m_FilterInfo.HDRContentLightLevel, pData, size); } LocalFree(pData); } if (SUCCEEDED(pIExFilterInfo->GetPropertyBin("PALETTE", &pData, &size))) { if (size == sizeof(m_Palette)) { m_bHasPalette = true; memcpy(m_Palette, pData, size); } LocalFree(pData); } } } } if (m_FilterInfo.profile != -1) { m_pAVCtx->profile = m_FilterInfo.profile; } if (m_FilterInfo.pix_fmt != AV_PIX_FMT_NONE) { m_pAVCtx->pix_fmt = (AVPixelFormat)m_FilterInfo.pix_fmt; } m_nAlign = 16; if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO) { m_nAlign <<= 1; } else if (m_nCodecId == AV_CODEC_ID_HEVC) { m_nAlign = 128; } m_nSurfaceWidth = FFALIGN(m_pAVCtx->coded_width, m_nAlign); m_nSurfaceHeight = FFALIGN(m_pAVCtx->coded_height, m_nAlign); const int depth = GetLumaBits(m_pAVCtx->pix_fmt); m_bHighBitdepth = (depth == 10) && ((m_nCodecId == AV_CODEC_ID_HEVC && m_pAVCtx->profile == FF_PROFILE_HEVC_MAIN_10) || (m_nCodecId == AV_CODEC_ID_VP9 && m_pAVCtx->profile == FF_PROFILE_VP9_2)); m_dxvaExtFormat = GetDXVA2ExtendedFormat(m_pAVCtx, m_pFrame); m_dxva_pix_fmt = m_pAVCtx->pix_fmt; if (bChangeType && IsDXVASupported()) { do { m_bDXVACompatible = false; if (!DXVACheckFramesize(m_nCodecId, PictWidth(), PictHeight(), m_nPCIVendor, m_nPCIDevice, m_VideoDriverVersion)) { // check frame size break; } if (m_nCodecId == AV_CODEC_ID_H264) { if (m_nDXVA_SD && m_nSurfaceWidth < 1280) { // check "Disable DXVA for SD" option break; } const int nCompat = FFH264CheckCompatibility(m_nSurfaceWidth, m_nSurfaceHeight, m_pAVCtx, m_nPCIVendor, m_nPCIDevice, m_VideoDriverVersion); if ((nCompat & DXVA_PROFILE_HIGHER_THAN_HIGH) || (nCompat & DXVA_HIGH_BIT)) { // DXVA unsupported break; } if (nCompat) { bool bDXVACompatible = true; switch (m_nDXVACheckCompatibility) { case 0: bDXVACompatible = false; break; case 1: bDXVACompatible = (nCompat == DXVA_UNSUPPORTED_LEVEL); break; case 2: bDXVACompatible = (nCompat == DXVA_TOO_MANY_REF_FRAMES); break; } if (!bDXVACompatible) { break; } } } else if (!check_dxva_compatible(m_nCodecId, m_pAVCtx->pix_fmt, m_pAVCtx->profile)) { break; } m_bDXVACompatible = true; } while (false); if (!m_bDXVACompatible) { goto redo; } } av_frame_unref(m_pFrame); if (UseDXVA2() && m_pDXVADecoder) { m_pDXVADecoder->FillHWContext(); } return S_OK; } static const VIDEO_OUTPUT_FORMATS DXVAFormats[] = { // DXVA2 8bit {&MEDIASUBTYPE_NV12, 1, 12, FCC('dxva')}, }; static const VIDEO_OUTPUT_FORMATS DXVAFormats10bit[] = { // DXVA2 10bit {&MEDIASUBTYPE_P010, 1, 24, FCC('dxva')}, }; void CMPCVideoDecFilter::BuildOutputFormat() { SAFE_DELETE_ARRAY(m_pVideoOutputFormat); // === New swscaler options int nSwIndex[PixFmt_count] = { 0 }; int nSwCount = 0; const enum AVPixelFormat pix_fmt = m_pMSDKDecoder ? AV_PIX_FMT_NV12 : (m_pAVCtx->sw_pix_fmt != AV_PIX_FMT_NONE ? m_pAVCtx->sw_pix_fmt : m_pAVCtx->pix_fmt); if (pix_fmt != AV_PIX_FMT_NONE) { const AVPixFmtDescriptor* av_pfdesc = av_pix_fmt_desc_get(pix_fmt); if (av_pfdesc) { int lumabits = av_pfdesc->comp[0].depth; const MPCPixelFormat* OutList = nullptr; if (av_pfdesc->nb_components <= 2) { // greyscale formats with and without alfa channel if (lumabits <= 8) { OutList = YUV420_8; } else if (lumabits <= 10) { OutList = YUV420_10; } else { OutList = YUV420_16; } } else if (av_pfdesc->flags & (AV_PIX_FMT_FLAG_RGB | AV_PIX_FMT_FLAG_PAL)) { if (lumabits <= 10) { OutList = RGB_8; } else { OutList = RGB_16; } } else if (av_pfdesc->nb_components >= 3) { if (av_pfdesc->log2_chroma_w == 1 && av_pfdesc->log2_chroma_h == 1) { // 4:2:0 if (lumabits <= 8) { OutList = YUV420_8; } else if (lumabits <= 10) { OutList = YUV420_10; } else { OutList = YUV420_16; } } else if (av_pfdesc->log2_chroma_w == 1 && av_pfdesc->log2_chroma_h == 0) { // 4:2:2 if (lumabits <= 8) { OutList = YUV422_8; } else if (lumabits <= 10) { OutList = YUV422_10; } else { OutList = YUV422_16; } } else if (av_pfdesc->log2_chroma_w == 0 && av_pfdesc->log2_chroma_h == 0) { // 4:4:4 if (lumabits <= 8) { OutList = YUV444_8; } else if (lumabits <= 10) { OutList = YUV444_10; } else { OutList = YUV444_16; } } } if (OutList == nullptr) { OutList = YUV420_8; } for (int i = 0; i < PixFmt_count; i++) { int index = OutList[i]; if (m_fPixFmts[index]) { nSwIndex[nSwCount++] = index; } } } } if (!m_fPixFmts[PixFmt_YUY2] || nSwCount == 0) { // if YUY2 has not been added yet, then add it to the end of the list nSwIndex[nSwCount++] = PixFmt_YUY2; } m_nVideoOutputCount = m_bUseFFmpeg ? nSwCount : 0; if (IsDXVASupported()) { m_nVideoOutputCount += m_bHighBitdepth ? _countof(DXVAFormats10bit) : _countof(DXVAFormats); } m_pVideoOutputFormat = DNew VIDEO_OUTPUT_FORMATS[m_nVideoOutputCount]; int nPos = 0; if (IsDXVASupported()) { if (m_bHighBitdepth) { memcpy(&m_pVideoOutputFormat[nPos], DXVAFormats10bit, sizeof(DXVAFormats10bit)); nPos += _countof(DXVAFormats10bit); } else { memcpy(&m_pVideoOutputFormat[nPos], DXVAFormats, sizeof(DXVAFormats)); nPos += _countof(DXVAFormats); } } // Software rendering if (m_bUseFFmpeg) { for (int i = 0; i < nSwCount; i++) { const SW_OUT_FMT* swof = GetSWOF(nSwIndex[i]); m_pVideoOutputFormat[nPos + i].subtype = swof->subtype; m_pVideoOutputFormat[nPos + i].biCompression = swof->biCompression; m_pVideoOutputFormat[nPos + i].biBitCount = swof->bpp; m_pVideoOutputFormat[nPos + i].biPlanes = 1; // This value must be set to 1. } } } void CMPCVideoDecFilter::GetOutputFormats(int& nNumber, VIDEO_OUTPUT_FORMATS** ppFormats) { nNumber = m_nVideoOutputCount; *ppFormats = m_pVideoOutputFormat; } static void ReconstructH264Extra(BYTE *extra, unsigned& extralen, int NALSize) { CH264Nalu Nalu; Nalu.SetBuffer(extra, extralen, NALSize); bool pps_present = false; bool bNeedReconstruct = false; while (Nalu.ReadNext()) { const NALU_TYPE nalu_type = Nalu.GetType(); if (nalu_type == NALU_TYPE_PPS) { pps_present = true; } else if (nalu_type == NALU_TYPE_SPS) { bNeedReconstruct = pps_present; break; } } if (bNeedReconstruct) { BYTE* dst = (uint8_t *)av_mallocz(extralen); if (!dst) { return; } size_t dstlen = 0; Nalu.SetBuffer(extra, extralen, NALSize); while (Nalu.ReadNext()) { if (Nalu.GetType() == NALU_TYPE_SPS) { memcpy(dst, Nalu.GetNALBuffer(), Nalu.GetLength()); dstlen += Nalu.GetLength(); break; } } Nalu.SetBuffer(extra, extralen, NALSize); while (Nalu.ReadNext()) { if (Nalu.GetType() != NALU_TYPE_SPS) { memcpy(dst + dstlen, Nalu.GetNALBuffer(), Nalu.GetLength()); dstlen += Nalu.GetLength(); } } memcpy(extra, dst, extralen); av_freep(&dst); } } void CMPCVideoDecFilter::AllocExtradata(const CMediaType* pmt) { // code from LAV ... // Process Extradata BYTE *extra = nullptr; unsigned extralen = 0; getExtraData((const BYTE *)pmt->Format(), pmt->FormatType(), pmt->FormatLength(), nullptr, &extralen); BOOL bH264avc = FALSE; if (pmt->formattype == FORMAT_MPEG2Video && (m_pAVCtx->codec_tag == MAKEFOURCC('a','v','c','1') || m_pAVCtx->codec_tag == MAKEFOURCC('A','V','C','1') || m_pAVCtx->codec_tag == MAKEFOURCC('C','C','V','1'))) { DLog(L"CMPCVideoDecFilter::AllocExtradata() : processing AVC1 extradata of %d bytes", extralen); // Reconstruct AVC1 extradata format MPEG2VIDEOINFO *mp2vi = (MPEG2VIDEOINFO *)pmt->Format(); extralen += 7; extra = (uint8_t *)av_mallocz(extralen + AV_INPUT_BUFFER_PADDING_SIZE); extra[0] = 1; extra[1] = (BYTE)mp2vi->dwProfile; extra[2] = 0; extra[3] = (BYTE)mp2vi->dwLevel; extra[4] = (BYTE)(mp2vi->dwFlags ? mp2vi->dwFlags : 4) - 1; // only process extradata if available uint8_t ps_count = 0; if (extralen > 7) { // Actually copy the metadata into our new buffer unsigned actual_len; getExtraData((const BYTE *)pmt->Format(), pmt->FormatType(), pmt->FormatLength(), extra + 6, &actual_len); ReconstructH264Extra(extra + 6, actual_len, 2); // Count the number of SPS/PPS in them and set the length // We'll put them all into one block and add a second block with 0 elements afterwards // The parsing logic does not care what type they are, it just expects 2 blocks. BYTE *p = extra + 6, *end = extra + 6 + actual_len; BOOL bSPS = FALSE, bPPS = FALSE; while (p + 1 < end) { unsigned len = (((unsigned)p[0] << 8) | p[1]) + 2; if (p + len > end) { break; } if ((p[2] & 0x1F) == 7) bSPS = TRUE; if ((p[2] & 0x1F) == 8) bPPS = TRUE; ps_count++; p += len; } } extra[5] = ps_count; extra[extralen - 1] = 0; bH264avc = TRUE; } else if (extralen > 0) { DLog(L"CMPCVideoDecFilter::AllocExtradata() : processing extradata of %d bytes", extralen); // Just copy extradata for other formats extra = (uint8_t *)av_mallocz(extralen + AV_INPUT_BUFFER_PADDING_SIZE); getExtraData((const BYTE *)pmt->Format(), pmt->FormatType(), pmt->FormatLength(), extra, nullptr); if (m_nCodecId == AV_CODEC_ID_H264) { ReconstructH264Extra(extra, extralen, 0); } else if (m_nCodecId == AV_CODEC_ID_HEVC) { // try Reconstruct NAL units sequence into NAL Units in Byte-Stream Format BYTE* dst = nullptr; int dst_len = 0; BOOL vps_present = FALSE, sps_present = FALSE, pps_present = FALSE; CH265Nalu Nalu; Nalu.SetBuffer(extra, extralen, 2); while (!(vps_present && sps_present && pps_present) && Nalu.ReadNext()) { const NALU_TYPE nalu_type = Nalu.GetType(); switch (nalu_type) { case NALU_TYPE_HEVC_VPS: case NALU_TYPE_HEVC_SPS: case NALU_TYPE_HEVC_PPS: if (nalu_type == NALU_TYPE_HEVC_VPS) { if (vps_present) continue; vc_params_t params = { 0 }; if (!HEVCParser::ParseVideoParameterSet(Nalu.GetDataBuffer() + 2, Nalu.GetDataLength() - 2, params)) { break; } vps_present = TRUE; } else if (nalu_type == NALU_TYPE_HEVC_SPS) { if (sps_present) continue; vc_params_t params = { 0 }; if (!HEVCParser::ParseSequenceParameterSet(Nalu.GetDataBuffer() + 2, Nalu.GetDataLength() - 2, params)) { break; } sps_present = TRUE; } else if (nalu_type == NALU_TYPE_HEVC_PPS) { if (pps_present) continue; pps_present = TRUE; } static const BYTE start_code[] = { 0, 0, 1 }; static const UINT start_code_size = sizeof(start_code); dst = (BYTE *)av_realloc_f(dst, dst_len + Nalu.GetDataLength() + start_code_size + AV_INPUT_BUFFER_PADDING_SIZE, 1); memcpy(dst + dst_len, start_code, start_code_size); dst_len += start_code_size; memcpy(dst + dst_len, Nalu.GetDataBuffer(), Nalu.GetDataLength()); dst_len += Nalu.GetDataLength(); } } if (vps_present && sps_present && pps_present) { av_freep(&extra); extra = dst; extralen = dst_len; } else { av_freep(&dst); } } else if (m_nCodecId == AV_CODEC_ID_VP9) { // use code from LAV // read custom vpcC headers if (extralen >= 16 && AV_RB32(extra) == 'vpcC' && AV_RB8(extra + 4) == 1) { m_pAVCtx->profile = AV_RB8(extra + 8); m_pAVCtx->color_primaries = (AVColorPrimaries)AV_RB8(extra + 11); m_pAVCtx->color_trc = (AVColorTransferCharacteristic)AV_RB8(extra + 12); m_pAVCtx->colorspace = (AVColorSpace)AV_RB8(extra + 13); m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV420P; int bitdepth = AV_RB8(extra + 10) >> 4; if (m_pAVCtx->profile == FF_PROFILE_VP9_2) { if (bitdepth == 10) { m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV420P10; } else if (bitdepth == 12) { m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV420P12; } } else if (m_pAVCtx->profile == FF_PROFILE_VP9_3) { if (bitdepth == 10) { m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV422P10; } else if (bitdepth == 12) { m_pAVCtx->pix_fmt = AV_PIX_FMT_YUV422P12; } } av_freep(&extra); extralen = 0; } } else if (m_nCodecId == AV_CODEC_ID_AV1) { if (extralen >= 8 && AV_RB32(extra) == 'av1C' && AV_RB8(extra + 4) == 0x81) { CGolombBuffer gb(extra + 5, extralen - 5); const unsigned seq_profile = gb.BitRead(3); gb.BitRead(5); // seq_level_idx gb.BitRead(1); // seq_tier const unsigned high_bitdepth = gb.BitRead(1); const unsigned twelve_bit = gb.BitRead(1); const unsigned monochrome = gb.BitRead(1); const unsigned chroma_subsampling_x = gb.BitRead(1); const unsigned chroma_subsampling_y = gb.BitRead(1); enum Dav1dPixelLayout { DAV1D_PIXEL_LAYOUT_I400, ///< monochrome DAV1D_PIXEL_LAYOUT_I420, ///< 4:2:0 planar DAV1D_PIXEL_LAYOUT_I422, ///< 4:2:2 planar DAV1D_PIXEL_LAYOUT_I444, ///< 4:4:4 planar }; enum Dav1dBitDepth { DAV1D_8BIT, DAV1D_10BIT, DAV1D_12BIT, }; static const enum AVPixelFormat pix_fmts[][3] = { { AV_PIX_FMT_GRAY8, AV_PIX_FMT_GRAY10, AV_PIX_FMT_GRAY12 }, { AV_PIX_FMT_YUV420P, AV_PIX_FMT_YUV420P10, AV_PIX_FMT_YUV420P12 }, { AV_PIX_FMT_YUV422P, AV_PIX_FMT_YUV422P10, AV_PIX_FMT_YUV422P12 }, { AV_PIX_FMT_YUV444P, AV_PIX_FMT_YUV444P10, AV_PIX_FMT_YUV444P12 }, }; Dav1dBitDepth bitdepth_index = DAV1D_8BIT; Dav1dPixelLayout layout = DAV1D_PIXEL_LAYOUT_I420; switch (seq_profile) { case FF_PROFILE_AV1_MAIN: bitdepth_index = high_bitdepth ? DAV1D_10BIT : DAV1D_8BIT; layout = monochrome ? DAV1D_PIXEL_LAYOUT_I400 : DAV1D_PIXEL_LAYOUT_I420; break; case FF_PROFILE_AV1_HIGH: bitdepth_index = high_bitdepth ? DAV1D_10BIT : DAV1D_8BIT; layout = DAV1D_PIXEL_LAYOUT_I444; break; case FF_PROFILE_AV1_PROFESSIONAL: bitdepth_index = high_bitdepth ? (twelve_bit ? DAV1D_12BIT : DAV1D_10BIT) : DAV1D_8BIT; if (monochrome) { layout = DAV1D_PIXEL_LAYOUT_I400; } else { if (bitdepth_index < DAV1D_12BIT) { layout = DAV1D_PIXEL_LAYOUT_I422; } else { if (chroma_subsampling_x && chroma_subsampling_y) { layout = DAV1D_PIXEL_LAYOUT_I420; } else if (chroma_subsampling_x && !chroma_subsampling_y) { layout = DAV1D_PIXEL_LAYOUT_I422; } else if (!chroma_subsampling_x && !chroma_subsampling_y) { layout = DAV1D_PIXEL_LAYOUT_I444; } } } break; } m_pAVCtx->profile = seq_profile; m_pAVCtx->pix_fmt = pix_fmts[layout][bitdepth_index]; av_freep(&extra); extralen = 0; } } } // Hack to discard invalid MP4 metadata with AnnexB style video if (m_nCodecId == AV_CODEC_ID_H264 && !bH264avc && extra && extra[0] == 1) { av_freep(&extra); extralen = 0; } m_pAVCtx->extradata = extra; m_pAVCtx->extradata_size = (int)extralen; } HRESULT CMPCVideoDecFilter::CompleteConnect(PIN_DIRECTION direction, IPin* pReceivePin) { if (direction == PINDIR_OUTPUT) { if (IsDXVASupported() && SUCCEEDED(ConfigureDXVA2(pReceivePin))) { HRESULT hr = E_FAIL; for (;;) { CComPtr<IDirectXVideoDecoderService> pDXVA2Service; hr = m_pDeviceManager->GetVideoService(m_hDevice, IID_PPV_ARGS(&pDXVA2Service)); if (FAILED(hr)) { DLog(L"CMPCVideoDecFilter::CompleteConnect() : IDirect3DDeviceManager9::GetVideoService() - FAILED (0x%08x)", hr); break; } if (!pDXVA2Service) { break; } const UINT numSurfaces = std::max(m_DXVA2Config.ConfigMinRenderTargetBuffCount, 1ui16); LPDIRECT3DSURFACE9 pSurfaces[DXVA2_MAX_SURFACES] = {}; hr = pDXVA2Service->CreateSurface( m_nSurfaceWidth, m_nSurfaceHeight, numSurfaces - 1, m_VideoDesc.Format, D3DPOOL_DEFAULT, 0, DXVA2_VideoDecoderRenderTarget, pSurfaces, nullptr); if (FAILED(hr)) { DLog(L"CMPCVideoDecFilter::CompleteConnect() : IDirectXVideoDecoderService::CreateSurface() - FAILED (0x%08x)", hr); break; } CComPtr<IDirectXVideoDecoder> pDirectXVideoDec; hr = m_pDecoderService->CreateVideoDecoder(m_DXVADecoderGUID, &m_VideoDesc, &m_DXVA2Config, pSurfaces, numSurfaces, &pDirectXVideoDec); if (FAILED(hr)) { DLog(L"CMPCVideoDecFilter::CompleteConnect() : IDirectXVideoDecoder::CreateVideoDecoder() - FAILED (0x%08x)", hr); } for (UINT i = 0; i < numSurfaces; i++) { SAFE_RELEASE(pSurfaces[i]); } if (SUCCEEDED(hr) && SUCCEEDED(SetEVRForDXVA2(pReceivePin))) { m_nDecoderMode = MODE_DXVA2; } break; } if (FAILED(hr)) { CleanDXVAVariable(); CleanupD3DResources(); SAFE_DELETE(m_pDXVADecoder); m_nDecoderMode = MODE_SOFTWARE; DXVAState::ClearState(); } } if (m_nDecoderMode == MODE_SOFTWARE) { if (!m_bUseFFmpeg) { return VFW_E_INVALIDMEDIATYPE; } if (IsDXVASupported()) { HRESULT hr; if (FAILED(hr = InitDecoder(&m_pCurrentMediaType))) { return hr; } ChangeOutputMediaFormat(2); } } DetectVideoCard_EVR(pReceivePin); if (m_pMSDKDecoder) { m_MVC_Base_View_R_flag = FALSE; BeginEnumFilters(m_pGraph, pEF, pBF) { if (CComQIPtr<IPropertyBag> pPB = pBF) { CComVariant var; if (SUCCEEDED(pPB->Read(L"STEREOSCOPIC3DMODE", &var, nullptr)) && var.vt == VT_BSTR) { CString mode(var.bstrVal); mode.MakeLower(); m_MVC_Base_View_R_flag = mode == L"mvc_rl"; break; } } } EndEnumFilters; } } return __super::CompleteConnect (direction, pReceivePin); } HRESULT CMPCVideoDecFilter::DecideBufferSize(IMemAllocator* pAllocator, ALLOCATOR_PROPERTIES* pProperties) { if (UseDXVA2()) { if (m_pInput->IsConnected() == FALSE) { return E_UNEXPECTED; } pProperties->cBuffers = 22; HRESULT hr = S_OK; ALLOCATOR_PROPERTIES Actual; if (FAILED(hr = pAllocator->SetProperties(pProperties, &Actual))) { return hr; } return pProperties->cBuffers > Actual.cBuffers || pProperties->cbBuffer > Actual.cbBuffer ? E_FAIL : NOERROR; } else { return __super::DecideBufferSize(pAllocator, pProperties); } } HRESULT CMPCVideoDecFilter::BeginFlush() { return __super::BeginFlush(); } HRESULT CMPCVideoDecFilter::EndFlush() { CAutoLock cAutoLock(&m_csReceive); HRESULT hr = __super::EndFlush(); if (m_pAVCtx && avcodec_is_open(m_pAVCtx)) { avcodec_flush_buffers(m_pAVCtx); } return hr; } HRESULT CMPCVideoDecFilter::NewSegment(REFERENCE_TIME rtStart, REFERENCE_TIME rtStop, double dRate) { DLog(L"CMPCVideoDecFilter::NewSegment()"); CAutoLock cAutoLock(&m_csReceive); if (m_pAVCtx) { avcodec_flush_buffers(m_pAVCtx); } if (m_pParser) { av_parser_close(m_pParser); m_pParser = av_parser_init(m_nCodecId); } if (m_pMSDKDecoder) { m_pMSDKDecoder->Flush(); } m_dRate = dRate; m_bWaitingForKeyFrame = TRUE; m_rtStartCache = INVALID_TIME; m_rtLastStop = 0; if (m_bReorderBFrame) { m_nBFramePos = 0; m_tBFrameDelay[0].rtStart = m_tBFrameDelay[0].rtStop = INVALID_TIME; m_tBFrameDelay[1].rtStart = m_tBFrameDelay[1].rtStop = INVALID_TIME; } if (m_bDecodingStart && m_pAVCtx) { if (m_nCodecId == AV_CODEC_ID_H264 || m_nCodecId == AV_CODEC_ID_MPEG2VIDEO) { InitDecoder(&m_pCurrentMediaType); } if (UseDXVA2() && m_nCodecId == AV_CODEC_ID_H264 && m_nPCIVendor == PCIV_ATI) { HRESULT hr = ReinitDXVA2Decoder(); if (FAILED(hr)) { return hr; } } } return __super::NewSegment(rtStart, rtStop, dRate); } HRESULT CMPCVideoDecFilter::EndOfStream() { CAutoLock cAutoLock(&m_csReceive); m_pMSDKDecoder ? m_pMSDKDecoder->EndOfStream() : Decode(nullptr, 0, INVALID_TIME, INVALID_TIME); return __super::EndOfStream(); } HRESULT CMPCVideoDecFilter::BreakConnect(PIN_DIRECTION dir) { if (dir == PINDIR_INPUT) { Cleanup(); } return __super::BreakConnect (dir); } void CMPCVideoDecFilter::SetTypeSpecificFlags(IMediaSample* pMS) { if (CComQIPtr<IMediaSample2> pMS2 = pMS) { AM_SAMPLE2_PROPERTIES props; if (SUCCEEDED(pMS2->GetProperties(sizeof(props), (BYTE*)&props))) { props.dwTypeSpecificFlags &= ~0x7f; switch (m_nScanType) { case SCAN_AUTO : if (m_nCodecId == AV_CODEC_ID_HEVC) { props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_WEAVE; } else if (m_FilterInfo.interlaced != -1) { switch (m_FilterInfo.interlaced) { case 0 : props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_WEAVE; break; case 1 : props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_FIELD1FIRST; break; } } else { if (!m_pFrame->interlaced_frame) { props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_WEAVE; } if (m_pFrame->top_field_first) { props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_FIELD1FIRST; } if (m_pFrame->repeat_pict) { props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_REPEAT_FIELD; } } break; case SCAN_PROGRESSIVE : props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_WEAVE; break; case SCAN_TOPFIELD : props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_FIELD1FIRST; break; } switch (m_pFrame->pict_type) { case AV_PICTURE_TYPE_I : case AV_PICTURE_TYPE_SI : props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_I_SAMPLE; break; case AV_PICTURE_TYPE_P : case AV_PICTURE_TYPE_SP : props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_P_SAMPLE; break; default : props.dwTypeSpecificFlags |= AM_VIDEO_FLAG_B_SAMPLE; break; } pMS2->SetProperties(sizeof(props), (BYTE*)&props); } } m_bInterlaced = m_pFrame->interlaced_frame; } // from LAVVideo DXVA2_ExtendedFormat CMPCVideoDecFilter::GetDXVA2ExtendedFormat(AVCodecContext *ctx, AVFrame *frame) { DXVA2_ExtendedFormat fmt = { 0 }; if (m_FormatConverter.GetOutPixFormat() == PixFmt_RGB32 || m_FormatConverter.GetOutPixFormat() == PixFmt_RGB48) { return fmt; } auto color_primaries = m_FilterInfo.color_primaries != -1 ? m_FilterInfo.color_primaries : ctx->color_primaries; auto colorspace = m_FilterInfo.colorspace != -1 ? m_FilterInfo.colorspace : ctx->colorspace; auto color_trc = m_FilterInfo.color_trc != -1 ? m_FilterInfo.color_trc : ctx->color_trc; auto chroma_sample_location = m_FilterInfo.chroma_sample_location != -1 ? m_FilterInfo.chroma_sample_location : ctx->chroma_sample_location; auto color_range = m_FilterInfo.color_range != -1 ? m_FilterInfo.color_range : ctx->color_range; // Color Primaries switch(color_primaries) { case AVCOL_PRI_BT709: fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT709; break; case AVCOL_PRI_BT470M: fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT470_2_SysM; break; case AVCOL_PRI_BT470BG: fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT470_2_SysBG; break; case AVCOL_PRI_SMPTE170M: fmt.VideoPrimaries = DXVA2_VideoPrimaries_SMPTE170M; break; case AVCOL_PRI_SMPTE240M: fmt.VideoPrimaries = DXVA2_VideoPrimaries_SMPTE240M; break; // Values from newer Windows SDK (MediaFoundation) case AVCOL_PRI_BT2020: fmt.VideoPrimaries = VIDEOPRIMARIES_BT2020; break; case AVCOL_PRI_SMPTE428: // XYZ fmt.VideoPrimaries = VIDEOPRIMARIES_XYZ; break; case AVCOL_PRI_SMPTE431: // DCI-P3 fmt.VideoPrimaries = VIDEOPRIMARIES_DCI_P3; break; } // Color Space / Transfer Matrix switch (colorspace) { case AVCOL_SPC_BT709: fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_BT709; break; case AVCOL_SPC_BT470BG: case AVCOL_SPC_SMPTE170M: fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_BT601; break; case AVCOL_SPC_SMPTE240M: fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_SMPTE240M; break; // Values from newer Windows SDK (MediaFoundation) case AVCOL_SPC_BT2020_CL: case AVCOL_SPC_BT2020_NCL: fmt.VideoTransferMatrix = VIDEOTRANSFERMATRIX_BT2020_10; break; // Custom values, not official standard, but understood by madVR, YCGCO understood by EVR-CP case AVCOL_SPC_FCC: fmt.VideoTransferMatrix = VIDEOTRANSFERMATRIX_FCC; break; case AVCOL_SPC_YCGCO: fmt.VideoTransferMatrix = VIDEOTRANSFERMATRIX_YCgCo; break; case AVCOL_SPC_UNSPECIFIED: if (ctx->width <= 1024 && ctx->height <= 576) { // SD fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_BT601; } else { // HD fmt.VideoTransferMatrix = DXVA2_VideoTransferMatrix_BT709; } } // Color Transfer Function switch(color_trc) { case AVCOL_TRC_BT709: case AVCOL_TRC_SMPTE170M: case AVCOL_TRC_BT2020_10: case AVCOL_TRC_BT2020_12: fmt.VideoTransferFunction = DXVA2_VideoTransFunc_709; break; case AVCOL_TRC_GAMMA22: fmt.VideoTransferFunction = DXVA2_VideoTransFunc_22; break; case AVCOL_TRC_GAMMA28: fmt.VideoTransferFunction = DXVA2_VideoTransFunc_28; break; case AVCOL_TRC_SMPTE240M: fmt.VideoTransferFunction = DXVA2_VideoTransFunc_240M; break; case AVCOL_TRC_LOG: fmt.VideoTransferFunction = MFVideoTransFunc_Log_100; break; case AVCOL_TRC_LOG_SQRT: fmt.VideoTransferFunction = MFVideoTransFunc_Log_316; break; // Values from newer Windows SDK (MediaFoundation) case AVCOL_TRC_SMPTEST2084: fmt.VideoTransferFunction = VIDEOTRANSFUNC_2084; break; case AVCOL_TRC_ARIB_STD_B67: fmt.VideoTransferFunction = VIDEOTRANSFUNC_HLG; break; } if (frame->format == AV_PIX_FMT_XYZ12LE || frame->format == AV_PIX_FMT_XYZ12BE) { fmt.VideoPrimaries = DXVA2_VideoPrimaries_BT709; } // Chroma location switch(chroma_sample_location) { case AVCHROMA_LOC_LEFT: fmt.VideoChromaSubsampling = DXVA2_VideoChromaSubsampling_MPEG2; break; case AVCHROMA_LOC_CENTER: fmt.VideoChromaSubsampling = DXVA2_VideoChromaSubsampling_MPEG1; break; case AVCHROMA_LOC_TOPLEFT: fmt.VideoChromaSubsampling = DXVA2_VideoChromaSubsampling_Cosited; break; } // Color Range, 0-255 or 16-235 if (color_range == AVCOL_RANGE_JPEG || frame->format == AV_PIX_FMT_YUVJ420P || frame->format == AV_PIX_FMT_YUVJ422P || frame->format == AV_PIX_FMT_YUVJ444P || frame->format == AV_PIX_FMT_YUVJ440P || frame->format == AV_PIX_FMT_YUVJ411P) { fmt.NominalRange = DXVA2_NominalRange_0_255; } else { fmt.NominalRange = DXVA2_NominalRange_16_235; } // HACK: 1280 is the value when only chroma location is set to MPEG2, do not bother to send this information, as its the same for basically every clip if ((fmt.value & ~0xff) != 0 && (fmt.value & ~0xff) != 1280) { fmt.SampleFormat = AMCONTROL_USED | AMCONTROL_COLORINFO_PRESENT; } else { fmt.value = 0; } return fmt; } static inline BOOL GOPFound(BYTE *buf, int len) { if (buf && len > 0) { CGolombBuffer gb(buf, len); BYTE state = 0x00; while (gb.NextMpegStartCode(state)) { if (state == 0xb8) { // GOP return TRUE; } } } return FALSE; } HRESULT CMPCVideoDecFilter::FillAVPacket(AVPacket *avpkt, const BYTE *buffer, int buflen) { int size = buflen; if (m_nCodecId == AV_CODEC_ID_PRORES) { // code from ffmpeg/libavutil/mem.c -> av_fast_realloc() size = (buflen + AV_INPUT_BUFFER_PADDING_SIZE) + (buflen + AV_INPUT_BUFFER_PADDING_SIZE) / 16 + 32; } if (av_new_packet(avpkt, size) < 0) { return E_OUTOFMEMORY; } memcpy(avpkt->data, buffer, buflen); if (size > buflen) { memset(avpkt->data + buflen, 0, size - buflen); } return S_OK; } #define Continue { av_frame_unref(m_pFrame); continue; } HRESULT CMPCVideoDecFilter::DecodeInternal(AVPacket *avpkt, REFERENCE_TIME rtStartIn, REFERENCE_TIME rtStopIn, BOOL bPreroll/* = FALSE*/) { if (avpkt) { if (m_bWaitingForKeyFrame) { if (m_nCodecId == AV_CODEC_ID_MPEG2VIDEO && GOPFound(avpkt->data, avpkt->size)) { m_bWaitingForKeyFrame = FALSE; } if (m_nCodecId == AV_CODEC_ID_VP8 || m_nCodecId == AV_CODEC_ID_VP9) { const BOOL bKeyFrame = m_nCodecId == AV_CODEC_ID_VP8 ? !(avpkt->data[0] & 1) : !(avpkt->data[0] & 4); if (bKeyFrame) { DLog(L"CMPCVideoDecFilter::DecodeInternal(): Found VP8/9 key-frame, resuming decoding"); m_bWaitingForKeyFrame = FALSE; } else { return S_OK; } } } if (m_bHasPalette) { m_bHasPalette = false; uint32_t *pal = (uint32_t *)av_packet_new_side_data(avpkt, AV_PKT_DATA_PALETTE, AVPALETTE_SIZE); memcpy(pal, m_Palette, AVPALETTE_SIZE); } } int ret = avcodec_send_packet(m_pAVCtx, avpkt); if (ret < 0 && ret != AVERROR(EAGAIN) && ret != AVERROR_EOF) { if (UseDXVA2() && !m_bDXVACompatible) { SAFE_DELETE(m_pDXVADecoder); m_nDecoderMode = MODE_SOFTWARE; DXVAState::ClearState(); InitDecoder(&m_pCurrentMediaType); ChangeOutputMediaFormat(2); } return S_FALSE; } for (;;) { ret = avcodec_receive_frame(m_pAVCtx, m_pFrame); if (ret < 0 && ret != AVERROR(EAGAIN)) { av_frame_unref(m_pFrame); return S_FALSE; } if (m_bWaitKeyFrame) { if (m_bWaitingForKeyFrame && ret >= 0) { if (m_pFrame->key_frame) { DLog(L"CMPCVideoDecFilter::DecodeInternal(): Found key-frame, resuming decoding"); m_bWaitingForKeyFrame = FALSE; } else { ret = AVERROR(EAGAIN); } } } if (ret < 0 || !m_pFrame->data[0]) { av_frame_unref(m_pFrame); break; } UpdateAspectRatio(); HRESULT hr = S_OK; if (UseDXVA2()) { hr = m_pDXVADecoder->DeliverFrame(); Continue; } GetFrameTimeStamp(m_pFrame, rtStartIn, rtStopIn); if (m_bRVDropBFrameTimings && m_pFrame->pict_type == AV_PICTURE_TYPE_B) { rtStartIn = m_rtLastStop; rtStopIn = INVALID_TIME; } bool bSampleTime = !(m_nCodecId == AV_CODEC_ID_MJPEG && rtStartIn == INVALID_TIME); UpdateFrameTime(rtStartIn, rtStopIn); if (bPreroll || rtStartIn < 0) { Continue; } CComPtr<IMediaSample> pOut; BYTE* pDataOut = nullptr; DXVA2_ExtendedFormat dxvaExtFormat = GetDXVA2ExtendedFormat(m_pAVCtx, m_pFrame); if (FAILED(hr = GetDeliveryBuffer(m_pAVCtx->width, m_pAVCtx->height, &pOut, GetFrameDuration(), &dxvaExtFormat)) || FAILED(hr = pOut->GetPointer(&pDataOut))) { Continue; } // Check alignment on rawvideo, which can be off depending on the source file AVFrame* pTmpFrame = nullptr; if (m_nCodecId == AV_CODEC_ID_RAWVIDEO) { for (size_t i = 0; i < 4; i++) { if ((intptr_t)m_pFrame->data[i] % 16u || m_pFrame->linesize[i] % 16u) { // copy the frame, its not aligned properly and would crash later pTmpFrame = av_frame_alloc(); pTmpFrame->format = m_pFrame->format; pTmpFrame->width = m_pFrame->width; pTmpFrame->height = m_pFrame->height; pTmpFrame->colorspace = m_pFrame->colorspace; pTmpFrame->color_range = m_pFrame->color_range; av_frame_get_buffer(pTmpFrame, AV_INPUT_BUFFER_PADDING_SIZE); av_image_copy(pTmpFrame->data, pTmpFrame->linesize, (const uint8_t**)m_pFrame->data, m_pFrame->linesize, (AVPixelFormat)m_pFrame->format, m_pFrame->width, m_pFrame->height); break; } } } if (pTmpFrame) { m_FormatConverter.Converting(pDataOut, pTmpFrame); av_frame_free(&pTmpFrame); } else { m_FormatConverter.Converting(pDataOut, m_pFrame); } if (bSampleTime) { pOut->SetTime(&rtStartIn, &rtStopIn); } pOut->SetMediaTime(nullptr, nullptr); SetTypeSpecificFlags(pOut); AddFrameSideData(pOut, m_pFrame); hr = m_pOutput->Deliver(pOut); av_frame_unref(m_pFrame); } return S_OK; } HRESULT CMPCVideoDecFilter::ParseInternal(const BYTE *buffer, int buflen, REFERENCE_TIME rtStartIn, REFERENCE_TIME rtStopIn, BOOL bPreroll) { BOOL bFlush = (buffer == nullptr); BYTE* pDataBuffer = (BYTE*)buffer; HRESULT hr = S_OK; while (buflen > 0 || bFlush) { REFERENCE_TIME rtStart = rtStartIn, rtStop = rtStopIn; BYTE *pOutBuffer = nullptr; int pOutLen = 0; int used_bytes = av_parser_parse2(m_pParser, m_pAVCtx, &pOutBuffer, &pOutLen, pDataBuffer, buflen, AV_NOPTS_VALUE, AV_NOPTS_VALUE, 0); if (used_bytes == 0 && pOutLen == 0 && !bFlush) { DLog(L"CMPCVideoDecFilter::ParseInternal() - could not process buffer, starving?"); break; } else if (used_bytes > 0) { buflen -= used_bytes; pDataBuffer += used_bytes; } // Update start time cache // If more data was read then output, update the cache (incomplete frame) // If output is bigger or equal, a frame was completed, update the actual rtStart with the cached value, and then overwrite the cache if (used_bytes > pOutLen) { if (rtStartIn != INVALID_TIME) { m_rtStartCache = rtStartIn; } /* } else if (used_bytes == pOutLen || ((used_bytes + 9) == pOutLen)) { // Why +9 above? // Well, apparently there are some broken MKV muxers that like to mux the MPEG-2 PICTURE_START_CODE block (which is 9 bytes) in the package with the previous frame // This would cause the frame timestamps to be delayed by one frame exactly, and cause timestamp reordering to go wrong. // So instead of failing on those samples, lets just assume that 9 bytes are that case exactly. m_rtStartCache = rtStartIn = INVALID_TIME; } else if (pOut_size > used_bytes) { */ } else { rtStart = m_rtStartCache; m_rtStartCache = rtStartIn; // The value was used once, don't use it for multiple frames, that ends up in weird timings rtStartIn = INVALID_TIME; } if (pOutLen > 0) { AVPacket *avpkt = av_packet_alloc(); if (FAILED(hr = FillAVPacket(avpkt, pOutBuffer, pOutLen))) { break; } avpkt->pts = rtStart; hr = DecodeInternal(avpkt, rtStartIn, rtStopIn, bPreroll); av_packet_free(&avpkt); if (FAILED(hr)) { break; } } else if (bFlush) { hr = DecodeInternal(nullptr, INVALID_TIME, INVALID_TIME); break; } } return hr; } HRESULT CMPCVideoDecFilter::Decode(const BYTE *buffer, int buflen, REFERENCE_TIME rtStartIn, REFERENCE_TIME rtStopIn, BOOL bSyncPoint/* = FALSE*/, BOOL bPreroll/* = FALSE*/) { HRESULT hr = S_OK; if (m_bReorderBFrame) { m_tBFrameDelay[m_nBFramePos].rtStart = rtStartIn; m_tBFrameDelay[m_nBFramePos].rtStop = rtStopIn; m_nBFramePos = !m_nBFramePos; } if (m_pParser) { hr = ParseInternal(buffer, buflen, rtStartIn, rtStopIn, bPreroll); } else { if (!buffer) { return DecodeInternal(nullptr, INVALID_TIME, INVALID_TIME); } AVPacket *avpkt = av_packet_alloc(); if (FAILED(FillAVPacket(avpkt, buffer, buflen))) { return E_OUTOFMEMORY; } avpkt->pts = rtStartIn; if (rtStartIn != INVALID_TIME && rtStopIn != INVALID_TIME) { avpkt->duration = rtStopIn - rtStartIn; } avpkt->flags = bSyncPoint ? AV_PKT_FLAG_KEY : 0; hr = DecodeInternal(avpkt, rtStartIn, rtStopIn, bPreroll); av_packet_free(&avpkt); } return hr; } // change colorspace details/output media format // 1 - change swscaler colorspace details // 2 - change output media format HRESULT CMPCVideoDecFilter::ChangeOutputMediaFormat(int nType) { HRESULT hr = S_OK; if (!m_pOutput || !m_pOutput->IsConnected()) { return hr; } // change swscaler colorspace details if (nType >= 1) { m_FormatConverter.SetOptions(m_nSwRGBLevels); } // change output media format if (nType == 2) { CAutoLock cObjectLock(m_pLock); BuildOutputFormat(); IPin* pPin = m_pOutput->GetConnected(); if (IsVideoRenderer(GetFilterFromPin(pPin))) { hr = NotifyEvent(EC_DISPLAY_CHANGED, (LONG_PTR)pPin, 0); if (S_OK != hr) { hr = E_FAIL; } } else { int nNumber; VIDEO_OUTPUT_FORMATS* pFormats; GetOutputFormats(nNumber, &pFormats); for (int i = 0; i < nNumber * 2; i++) { CMediaType mt; if (SUCCEEDED(GetMediaType(i, &mt))) { hr = pPin->QueryAccept(&mt); if (hr == S_OK) { hr = ReconnectPin(pPin, &mt); if (hr == S_OK) { return hr; } } } } return E_FAIL; } } return hr; } void CMPCVideoDecFilter::SetThreadCount() { if (m_pAVCtx) { if (IsDXVASupported() || m_nCodecId == AV_CODEC_ID_MPEG4) { m_pAVCtx->thread_count = 1; } else { int nThreadNumber = (m_nThreadNumber > 0) ? m_nThreadNumber : CPUInfo::GetProcessorNumber(); m_pAVCtx->thread_count = std::clamp(nThreadNumber, 1, MAX_AUTO_THREADS); if (m_nCodecId == AV_CODEC_ID_AV1) { av_opt_set_int(m_pAVCtx->priv_data, "tilethreads", m_pAVCtx->thread_count == 1 ? 1 : (m_pAVCtx->thread_count < 8 ? 2 : 4), 0); av_opt_set_int(m_pAVCtx->priv_data, "framethreads", m_pAVCtx->thread_count, 0); } } } } HRESULT CMPCVideoDecFilter::Transform(IMediaSample* pIn) { HRESULT hr; BYTE* buffer; int buflen; REFERENCE_TIME rtStart = INVALID_TIME; REFERENCE_TIME rtStop = INVALID_TIME; if (FAILED(hr = pIn->GetPointer(&buffer))) { return hr; } buflen = pIn->GetActualDataLength(); if (buflen == 0) { return S_OK; } hr = pIn->GetTime(&rtStart, &rtStop); if (FAILED(hr)) { rtStart = rtStop = INVALID_TIME; DLogIf(!m_bDecodingStart, L"CMPCVideoDecFilter::Transform(): input sample without timestamps!"); } else if (hr == VFW_S_NO_STOP_TIME || rtStop - 1 <= rtStart) { rtStop = INVALID_TIME; } if (UseDXVA2()) { CheckPointer(m_pDXVA2Allocator, E_UNEXPECTED); } hr = m_pMSDKDecoder ? m_pMSDKDecoder->Decode(buffer, buflen, rtStart, rtStop) : Decode(buffer, buflen, rtStart, rtStop, pIn->IsSyncPoint() == S_OK, pIn->IsPreroll() == S_OK); m_bDecodingStart = TRUE; return hr; } void CMPCVideoDecFilter::UpdateAspectRatio() { if (m_nARMode) { bool bSetAR = true; if (m_nARMode == 2) { CMediaType& mt = m_pInput->CurrentMediaType(); if (mt.formattype == FORMAT_VideoInfo2 || mt.formattype == FORMAT_MPEG2_VIDEO || mt.formattype == FORMAT_DiracVideoInfo) { VIDEOINFOHEADER2* vih2 = (VIDEOINFOHEADER2*)mt.pbFormat; bSetAR = (!vih2->dwPictAspectRatioX && !vih2->dwPictAspectRatioY); } if (!bSetAR && (m_nARX && m_nARY)) { CSize aspect(m_nARX, m_nARY); ReduceDim(aspect); SetAspect(aspect); } } if (bSetAR) { if (m_pAVCtx && (m_pAVCtx->sample_aspect_ratio.num > 0) && (m_pAVCtx->sample_aspect_ratio.den > 0)) { CSize aspect(m_pAVCtx->sample_aspect_ratio.num * m_pAVCtx->width, m_pAVCtx->sample_aspect_ratio.den * m_pAVCtx->height); ReduceDim(aspect); SetAspect(aspect); } } } else if (m_nARX && m_nARY) { CSize aspect(m_nARX, m_nARY); ReduceDim(aspect); SetAspect(aspect); } } void CMPCVideoDecFilter::FlushDXVADecoder() { if (m_pDXVADecoder) { CAutoLock cAutoLock(&m_csReceive); if (m_pAVCtx && avcodec_is_open(m_pAVCtx)) { avcodec_flush_buffers(m_pAVCtx); } } } void CMPCVideoDecFilter::FillInVideoDescription(DXVA2_VideoDesc& videoDesc, D3DFORMAT Format/* = D3DFMT_A8R8G8B8*/) { memset(&videoDesc, 0, sizeof(videoDesc)); videoDesc.SampleWidth = m_nSurfaceWidth; videoDesc.SampleHeight = m_nSurfaceHeight; videoDesc.Format = Format; videoDesc.UABProtectionLevel = 1; } BOOL CMPCVideoDecFilter::IsSupportedDecoderMode(const GUID& decoderGUID) { if (IsDXVASupported()) { for (int i = 0; i < _countof(DXVAModes); i++) { if (DXVAModes[i].nCodecId == m_nCodecId && DXVAModes[i].decoderGUID == decoderGUID && DXVAModes[i].bHighBitdepth == !!m_bHighBitdepth) { return true; } } } return FALSE; } BOOL CMPCVideoDecFilter::IsSupportedDecoderConfig(const D3DFORMAT& nD3DFormat, const DXVA2_ConfigPictureDecode& config, bool& bIsPrefered) { bIsPrefered = (config.ConfigBitstreamRaw == (m_nCodecId == AV_CODEC_ID_H264 ? 2 : 1)); return (m_bHighBitdepth && nD3DFormat == MAKEFOURCC('P', '0', '1', '0') || (!m_bHighBitdepth && (nD3DFormat == MAKEFOURCC('N', 'V', '1', '2') || nD3DFormat == MAKEFOURCC('I', 'M', 'C', '3')))); } HRESULT CMPCVideoDecFilter::FindDXVA2DecoderConfiguration(IDirectXVideoDecoderService *pDecoderService, const GUID& guidDecoder, DXVA2_ConfigPictureDecode *pSelectedConfig, BOOL *pbFoundDXVA2Configuration) { HRESULT hr = S_OK; UINT cFormats = 0; UINT cConfigurations = 0; bool bIsPrefered = false; D3DFORMAT *pFormats = nullptr; DXVA2_ConfigPictureDecode *pConfig = nullptr; // Find the valid render target formats for this decoder GUID. hr = pDecoderService->GetDecoderRenderTargets(guidDecoder, &cFormats, &pFormats); if (SUCCEEDED(hr)) { // Look for a format that matches our output format. for (UINT iFormat = 0; iFormat < cFormats; iFormat++) { // Fill in the video description. Set the width, height, format, and frame rate. DXVA2_VideoDesc VideoDesc; FillInVideoDescription(VideoDesc, pFormats[iFormat]); // Get the available configurations. hr = pDecoderService->GetDecoderConfigurations(guidDecoder, &VideoDesc, nullptr, &cConfigurations, &pConfig); if (FAILED(hr)) { continue; } // Find a supported configuration. for (UINT iConfig = 0; iConfig < cConfigurations; iConfig++) { if (IsSupportedDecoderConfig(pFormats[iFormat], pConfig[iConfig], bIsPrefered)) { // This configuration is good. if (bIsPrefered || !*pbFoundDXVA2Configuration) { *pbFoundDXVA2Configuration = TRUE; *pSelectedConfig = pConfig[iConfig]; FillInVideoDescription(m_VideoDesc, pFormats[iFormat]); } if (bIsPrefered) { break; } } } CoTaskMemFree(pConfig); } // End of formats loop. } CoTaskMemFree(pFormats); // Note: It is possible to return S_OK without finding a configuration. return hr; } HRESULT CMPCVideoDecFilter::ConfigureDXVA2(IPin *pPin) { HRESULT hr = S_OK; CleanupD3DResources(); CComPtr<IMFGetService> pGetService; // Query the pin for IMFGetService. hr = pPin->QueryInterface(IID_PPV_ARGS(&pGetService)); // Get the Direct3D device manager. if (SUCCEEDED(hr)) { hr = pGetService->GetService(MR_VIDEO_ACCELERATION_SERVICE, IID_PPV_ARGS(&m_pDeviceManager)); } // Open a new device handle. if (SUCCEEDED(hr)) { hr = m_pDeviceManager->OpenDeviceHandle(&m_hDevice); } // Get the video decoder service. if (SUCCEEDED(hr)) { hr = m_pDeviceManager->GetVideoService(m_hDevice, IID_PPV_ARGS(&m_pDecoderService)); } if (SUCCEEDED(hr)) { hr = FindDecoderConfiguration(); } if (FAILED(hr)) { CleanupD3DResources(); } return hr; } HRESULT CMPCVideoDecFilter::SetEVRForDXVA2(IPin *pPin) { CComPtr<IMFGetService> pGetService; HRESULT hr = pPin->QueryInterface(IID_PPV_ARGS(&pGetService)); if (SUCCEEDED(hr)) { CComPtr<IDirectXVideoMemoryConfiguration> pVideoConfig; hr = pGetService->GetService(MR_VIDEO_ACCELERATION_SERVICE, IID_PPV_ARGS(&pVideoConfig)); if (SUCCEEDED(hr)) { // Notify the EVR. DXVA2_SurfaceType surfaceType; DWORD dwTypeIndex = 0; for (;;) { hr = pVideoConfig->GetAvailableSurfaceTypeByIndex(dwTypeIndex, &surfaceType); if (FAILED(hr)) { break; } if (surfaceType == DXVA2_SurfaceType_DecoderRenderTarget) { hr = pVideoConfig->SetSurfaceType(DXVA2_SurfaceType_DecoderRenderTarget); break; } ++dwTypeIndex; } } } return hr; } HRESULT CMPCVideoDecFilter::CreateDXVA2Decoder(LPDIRECT3DSURFACE9* ppDecoderRenderTargets, UINT nNumRenderTargets) { DLog(L"CMPCVideoDecFilter::CreateDXVA2Decoder()"); HRESULT hr; CComPtr<IDirectXVideoDecoder> pDirectXVideoDec; SAFE_DELETE(m_pDXVADecoder); hr = m_pDecoderService->CreateVideoDecoder(m_DXVADecoderGUID, &m_VideoDesc, &m_DXVA2Config, ppDecoderRenderTargets, nNumRenderTargets, &pDirectXVideoDec); if (SUCCEEDED(hr)) { m_pDXVADecoder = DNew CDXVA2Decoder(this, pDirectXVideoDec, &m_DXVADecoderGUID, &m_DXVA2Config, ppDecoderRenderTargets, nNumRenderTargets); } if (FAILED(hr)) { CleanDXVAVariable(); } return hr; } HRESULT CMPCVideoDecFilter::ReinitDXVA2Decoder() { HRESULT hr = E_FAIL; SAFE_DELETE(m_pDXVADecoder); if (m_pDXVA2Allocator && IsDXVASupported() && SUCCEEDED(FindDecoderConfiguration())) { hr = RecommitAllocator(); } return hr; } HRESULT CMPCVideoDecFilter::InitAllocator(IMemAllocator **ppAlloc) { HRESULT hr = S_FALSE; m_pDXVA2Allocator = DNew CVideoDecDXVAAllocator(this, &hr); if (!m_pDXVA2Allocator) { return E_OUTOFMEMORY; } if (FAILED(hr)) { SAFE_DELETE(m_pDXVA2Allocator); return hr; } // Return the IMemAllocator interface. return m_pDXVA2Allocator->QueryInterface(IID_PPV_ARGS(ppAlloc)); } HRESULT CMPCVideoDecFilter::RecommitAllocator() { HRESULT hr = S_OK; if (m_pDXVA2Allocator) { // Re-Commit the allocator (creates surfaces and new decoder) hr = m_pDXVA2Allocator->Decommit(); if (m_pDXVA2Allocator->DecommitInProgress()) { DLog(L"CMPCVideoDecFilter::RecommitAllocator() : WARNING! DXVA2 Allocator is still busy, trying to flush downstream"); GetOutputPin()->GetConnected()->BeginFlush(); GetOutputPin()->GetConnected()->EndFlush(); if (m_pDXVA2Allocator->DecommitInProgress()) { DLog(L"CMPCVideoDecFilter::RecommitAllocator() : WARNING! Flush had no effect, decommit of the allocator still not complete"); } else { DLog(L"CMPCVideoDecFilter::RecommitAllocator() : Flush was successfull, decommit completed!"); } } hr = m_pDXVA2Allocator->Commit(); } return hr; } // ISpecifyPropertyPages2 STDMETHODIMP CMPCVideoDecFilter::GetPages(CAUUID* pPages) { CheckPointer(pPages, E_POINTER); #ifdef REGISTER_FILTER pPages->cElems = 2; #else pPages->cElems = 1; #endif pPages->pElems = (GUID*)CoTaskMemAlloc(sizeof(GUID) * pPages->cElems); pPages->pElems[0] = __uuidof(CMPCVideoDecSettingsWnd); #ifdef REGISTER_FILTER pPages->pElems[1] = __uuidof(CMPCVideoDecCodecWnd); #endif return S_OK; } STDMETHODIMP CMPCVideoDecFilter::CreatePage(const GUID& guid, IPropertyPage** ppPage) { CheckPointer(ppPage, E_POINTER); if (*ppPage != nullptr) { return E_INVALIDARG; } HRESULT hr; if (guid == __uuidof(CMPCVideoDecSettingsWnd)) { (*ppPage = DNew CInternalPropertyPageTempl<CMPCVideoDecSettingsWnd>(nullptr, &hr))->AddRef(); } #ifdef REGISTER_FILTER else if (guid == __uuidof(CMPCVideoDecCodecWnd)) { (*ppPage = DNew CInternalPropertyPageTempl<CMPCVideoDecCodecWnd>(nullptr, &hr))->AddRef(); } #endif return *ppPage ? S_OK : E_FAIL; } // EVR functions HRESULT CMPCVideoDecFilter::DetectVideoCard_EVR(IPin *pPin) { IMFGetService* pGetService; HRESULT hr = pPin->QueryInterface(IID_PPV_ARGS(&pGetService)); if (SUCCEEDED(hr)) { // Try to get the adapter description of the active DirectX 9 device. IDirect3DDeviceManager9* pDevMan9; hr = pGetService->GetService(MR_VIDEO_ACCELERATION_SERVICE, IID_PPV_ARGS(&pDevMan9)); if (SUCCEEDED(hr)) { HANDLE hDevice; hr = pDevMan9->OpenDeviceHandle(&hDevice); if (SUCCEEDED(hr)) { IDirect3DDevice9* pD3DDev9; hr = pDevMan9->LockDevice(hDevice, &pD3DDev9, TRUE); if (hr == DXVA2_E_NEW_VIDEO_DEVICE) { // Invalid device handle. Try to open a new device handle. hr = pDevMan9->CloseDeviceHandle(hDevice); if (SUCCEEDED(hr)) { hr = pDevMan9->OpenDeviceHandle(&hDevice); // Try to lock the device again. if (SUCCEEDED(hr)) { hr = pDevMan9->LockDevice(hDevice, &pD3DDev9, TRUE); } } } if (SUCCEEDED(hr)) { D3DDEVICE_CREATION_PARAMETERS DevPar9; hr = pD3DDev9->GetCreationParameters(&DevPar9); if (SUCCEEDED(hr)) { IDirect3D9* pD3D9; hr = pD3DDev9->GetDirect3D(&pD3D9); if (SUCCEEDED(hr)) { D3DADAPTER_IDENTIFIER9 AdapID9; hr = pD3D9->GetAdapterIdentifier(DevPar9.AdapterOrdinal, 0, &AdapID9); if (SUCCEEDED(hr)) { // copy adapter description m_nPCIVendor = AdapID9.VendorId; m_nPCIDevice = AdapID9.DeviceId; m_VideoDriverVersion = AdapID9.DriverVersion.QuadPart; if (SysVersion::IsWin81orLater() && (m_VideoDriverVersion & 0xffff00000000) == 0 && (m_VideoDriverVersion & 0xffff) == 0) { // fix bug in GetAdapterIdentifier() m_VideoDriverVersion = (m_VideoDriverVersion & 0xffff000000000000) | ((m_VideoDriverVersion & 0xffff0000) << 16) | 0xffffffff; } m_strDeviceDescription.Format(L"%S (%04X:%04X)", AdapID9.Description, m_nPCIVendor, m_nPCIDevice); } } pD3D9->Release(); } pD3DDev9->Release(); pDevMan9->UnlockDevice(hDevice, FALSE); } pDevMan9->CloseDeviceHandle(hDevice); } pDevMan9->Release(); } pGetService->Release(); } return hr; } HRESULT CMPCVideoDecFilter::SetFFMpegCodec(int nCodec, bool bEnabled) { CAutoLock cAutoLock(&m_csProps); if (nCodec < 0 || nCodec >= VDEC_COUNT) { return E_FAIL; } m_VideoFilters[nCodec] = bEnabled; return S_OK; } HRESULT CMPCVideoDecFilter::SetDXVACodec(int nCodec, bool bEnabled) { CAutoLock cAutoLock(&m_csProps); if (nCodec < 0 || nCodec >= VDEC_DXVA_COUNT) { return E_FAIL; } m_DXVAFilters[nCodec] = bEnabled; return S_OK; } // IFFmpegDecFilter STDMETHODIMP CMPCVideoDecFilter::SaveSettings() { #ifdef REGISTER_FILTER CRegKey key; if (ERROR_SUCCESS == key.Create(HKEY_CURRENT_USER, OPT_REGKEY_VideoDec)) { key.SetDWORDValue(OPT_ThreadNumber, m_nThreadNumber); key.SetDWORDValue(OPT_DiscardMode, m_nDiscardMode); key.SetDWORDValue(OPT_ScanType, (int)m_nScanType); key.SetDWORDValue(OPT_ARMode, m_nARMode); key.SetDWORDValue(OPT_DXVACheck, m_nDXVACheckCompatibility); key.SetDWORDValue(OPT_DisableDXVA_SD, m_nDXVA_SD); // === New swscaler options for (int i = 0; i < PixFmt_count; i++) { CString optname = OPT_SW_prefix; optname += GetSWOF(i)->name; key.SetDWORDValue(optname, m_fPixFmts[i]); } key.SetDWORDValue(OPT_SwRGBLevels, m_nSwRGBLevels); // } if (ERROR_SUCCESS == key.Create(HKEY_CURRENT_USER, OPT_REGKEY_VCodecs)) { for (size_t i = 0; i < _countof(vcodecs); i++) { DWORD dw = m_nActiveCodecs & vcodecs[i].flag ? 1 : 0; key.SetDWORDValue(vcodecs[i].opt_name, dw); } } #else CProfile& profile = AfxGetProfile(); profile.WriteInt(OPT_SECTION_VideoDec, OPT_ThreadNumber, m_nThreadNumber); profile.WriteInt(OPT_SECTION_VideoDec, OPT_DiscardMode, m_nDiscardMode); profile.WriteInt(OPT_SECTION_VideoDec, OPT_ScanType, (int)m_nScanType); profile.WriteInt(OPT_SECTION_VideoDec, OPT_ARMode, m_nARMode); profile.WriteInt(OPT_SECTION_VideoDec, OPT_DXVACheck, m_nDXVACheckCompatibility); profile.WriteInt(OPT_SECTION_VideoDec, OPT_DisableDXVA_SD, m_nDXVA_SD); profile.WriteInt(OPT_SECTION_VideoDec, OPT_SwRGBLevels, m_nSwRGBLevels); for (int i = 0; i < PixFmt_count; i++) { CString optname = OPT_SW_prefix; optname += GetSWOF(i)->name; profile.WriteBool(OPT_SECTION_VideoDec, optname, m_fPixFmts[i]); } #endif return S_OK; } // === IMPCVideoDecFilter STDMETHODIMP CMPCVideoDecFilter::SetThreadNumber(int nValue) { CAutoLock cAutoLock(&m_csProps); m_nThreadNumber = nValue; return S_OK; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetThreadNumber() { CAutoLock cAutoLock(&m_csProps); return m_nThreadNumber; } STDMETHODIMP CMPCVideoDecFilter::SetDiscardMode(int nValue) { if (nValue != AVDISCARD_DEFAULT && nValue != AVDISCARD_BIDIR) { return E_INVALIDARG; } CAutoLock cAutoLock(&m_csProps); m_nDiscardMode = nValue; if (m_pAVCtx) { m_pAVCtx->skip_frame = (AVDiscard)m_nDiscardMode; } return S_OK; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetDiscardMode() { CAutoLock cAutoLock(&m_csProps); return m_nDiscardMode; } STDMETHODIMP CMPCVideoDecFilter::SetScanType(MPC_SCAN_TYPE nValue) { CAutoLock cAutoLock(&m_csProps); m_nScanType = nValue; return S_OK; } STDMETHODIMP_(MPC_SCAN_TYPE) CMPCVideoDecFilter::GetScanType() { CAutoLock cAutoLock(&m_csProps); return m_nScanType; } STDMETHODIMP_(GUID*) CMPCVideoDecFilter::GetDXVADecoderGuid() { return m_pGraph && m_pDXVADecoder ? &m_DXVADecoderGUID : nullptr; } STDMETHODIMP CMPCVideoDecFilter::SetActiveCodecs(ULONGLONG nValue) { CAutoLock cAutoLock(&m_csProps); m_nActiveCodecs = nValue; return S_OK; } STDMETHODIMP_(ULONGLONG) CMPCVideoDecFilter::GetActiveCodecs() { CAutoLock cAutoLock(&m_csProps); return m_nActiveCodecs; } STDMETHODIMP CMPCVideoDecFilter::SetARMode(int nValue) { CAutoLock cAutoLock(&m_csProps); m_nARMode = nValue; return S_OK; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetARMode() { CAutoLock cAutoLock(&m_csProps); return m_nARMode; } STDMETHODIMP CMPCVideoDecFilter::SetDXVACheckCompatibility(int nValue) { CAutoLock cAutoLock(&m_csProps); m_nDXVACheckCompatibility = nValue; return S_OK; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetDXVACheckCompatibility() { CAutoLock cAutoLock(&m_csProps); return m_nDXVACheckCompatibility; } STDMETHODIMP CMPCVideoDecFilter::SetDXVA_SD(int nValue) { CAutoLock cAutoLock(&m_csProps); m_nDXVA_SD = nValue; return S_OK; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetDXVA_SD() { CAutoLock cAutoLock(&m_csProps); return m_nDXVA_SD; } // === New swscaler options STDMETHODIMP CMPCVideoDecFilter::SetSwRefresh(int nValue) { CAutoLock cAutoLock(&m_csProps); if (nValue && ((m_pAVCtx && m_nDecoderMode == MODE_SOFTWARE) || m_pMSDKDecoder)) { ChangeOutputMediaFormat(nValue); } return S_OK; } STDMETHODIMP CMPCVideoDecFilter::SetSwPixelFormat(MPCPixelFormat pf, bool enable) { CAutoLock cAutoLock(&m_csProps); if (pf < 0 || pf >= PixFmt_count) { return E_INVALIDARG; } m_fPixFmts[pf] = enable; return S_OK; } STDMETHODIMP_(bool) CMPCVideoDecFilter::GetSwPixelFormat(MPCPixelFormat pf) { CAutoLock cAutoLock(&m_csProps); if (pf < 0 || pf >= PixFmt_count) { return false; } return m_fPixFmts[pf]; } STDMETHODIMP CMPCVideoDecFilter::SetSwRGBLevels(int nValue) { CAutoLock cAutoLock(&m_csProps); m_nSwRGBLevels = nValue; return S_OK; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetSwRGBLevels() { CAutoLock cAutoLock(&m_csProps); return m_nSwRGBLevels; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetColorSpaceConversion() { CAutoLock cAutoLock(&m_csProps); if (!m_pAVCtx) { return -1; // no decoder } if (m_nDecoderMode != MODE_SOFTWARE || m_pAVCtx->pix_fmt == AV_PIX_FMT_NONE || m_FormatConverter.GetOutPixFormat() == PixFmt_None) { return -2; // no conversion } const AVPixFmtDescriptor* av_pfdesc = av_pix_fmt_desc_get(m_pAVCtx->pix_fmt); if (!av_pfdesc) { return -2; } bool in_rgb = !!(av_pfdesc->flags & (AV_PIX_FMT_FLAG_RGB|AV_PIX_FMT_FLAG_PAL)); bool out_rgb = (m_FormatConverter.GetOutPixFormat() == PixFmt_RGB32 || m_FormatConverter.GetOutPixFormat() == PixFmt_RGB48); if (in_rgb < out_rgb) { return 1; // YUV->RGB conversion } if (in_rgb > out_rgb) { return 2; // RGB->YUV conversion } return 0; // YUV->YUV or RGB->RGB conversion } STDMETHODIMP CMPCVideoDecFilter::SetMvcOutputMode(int nMode, bool bSwapLR) { CAutoLock cAutoLock(&m_csProps); if (nMode < 0 || nMode > MVC_OUTPUT_TopBottom) { return E_INVALIDARG; } m_iMvcOutputMode = nMode; m_bMvcSwapLR = bSwapLR; if (m_pMSDKDecoder) { m_pMSDKDecoder->SetOutputMode(nMode, bSwapLR); } return S_OK; } STDMETHODIMP_(int) CMPCVideoDecFilter::GetMvcActive() { return (m_pMSDKDecoder != nullptr) ? 1 + m_pMSDKDecoder->GetHwAcceleration() : 0; } STDMETHODIMP_(CString) CMPCVideoDecFilter::GetInformation(MPCInfo index) { CAutoLock cAutoLock(&m_csProps); CString infostr; switch (index) { case INFO_MPCVersion: infostr.Format(L"%s (build %d)", MPC_VERSION_WSTR, MPC_VERSION_REV); break; case INFO_InputFormat: if (m_pAVCtx) { const auto& pix_fmt = m_pDXVADecoder ? m_pAVCtx->sw_pix_fmt : m_pAVCtx->pix_fmt; infostr = m_pAVCtx->codec_descriptor->name; if (m_pAVCtx->codec_id == AV_CODEC_ID_RAWVIDEO) { infostr.AppendFormat(L" '%s'", FourccToWStr(m_pAVCtx->codec_tag)); } if (const AVPixFmtDescriptor* desc = av_pix_fmt_desc_get(pix_fmt)) { if (desc->flags & AV_PIX_FMT_FLAG_PAL) { infostr.Append(L", palettized RGB"); } else if (desc->nb_components == 1 || desc->nb_components == 2) { infostr.AppendFormat(L", Gray %d-bit", GetLumaBits(pix_fmt)); } else if(desc->flags & AV_PIX_FMT_FLAG_RGB) { int bidepth = 0; for (int i = 0; i < desc->nb_components; i++) { bidepth += desc->comp[i].depth; } infostr.Append(desc->flags & AV_PIX_FMT_FLAG_ALPHA ? L", RGBA" : L", RGB"); infostr.AppendFormat(L" %dbpp", bidepth); } else if (desc->nb_components == 0) { // unknown } else { infostr.Append(desc->flags & AV_PIX_FMT_FLAG_ALPHA ? L", YUVA" : L", YUV"); infostr.AppendFormat(L" %d-bit %s", GetLumaBits(pix_fmt), GetChromaSubsamplingStr(pix_fmt)); if (desc->name && !strncmp(desc->name, "yuvj", 4)) { infostr.Append(L" full range"); } } } } else if (m_pMSDKDecoder) { infostr = L"h264(MVC 3D), YUV 8-bit, 4:2:0"; } break; case INFO_FrameSize: if (m_win && m_hin) { __int64 sarx = (__int64)m_arx * m_hin; __int64 sary = (__int64)m_ary * m_win; ReduceDim(sarx, sary); infostr.Format(L"%dx%d, SAR %d:%d, DAR %d:%d", m_win, m_hin, (int)sarx, (int)sary, m_arx, m_ary); } break; case INFO_OutputFormat: if (GUID* DxvaGuid = GetDXVADecoderGuid()) { infostr.Format(L"DXVA2 (%s)", GetDXVAMode(*DxvaGuid)); break; } if (const SW_OUT_FMT* swof = GetSWOF(m_FormatConverter.GetOutPixFormat())) { infostr.Format(L"%s (%d-bit %s)", swof->name, swof->luma_bits, GetChromaSubsamplingStr(swof->av_pix_fmt)); } break; case INFO_GraphicsAdapter: infostr = m_strDeviceDescription; break; } return infostr; } HRESULT CMPCVideoDecFilter::CheckDXVA2Decoder(AVCodecContext *c) { CheckPointer(m_pAVCtx, E_POINTER); HRESULT hr = S_OK; if (m_pDXVADecoder) { if ((m_nSurfaceWidth != FFALIGN(c->coded_width, m_nAlign) || m_nSurfaceHeight != FFALIGN(c->coded_height, m_nAlign)) || ((m_nCodecId == AV_CODEC_ID_HEVC || m_nCodecId == AV_CODEC_ID_VP9) && m_dxva_pix_fmt != m_pAVCtx->sw_pix_fmt)) { const int depth = GetLumaBits(m_pAVCtx->sw_pix_fmt); const BOOL bHighBitdepth = (depth == 10) && ((m_nCodecId == AV_CODEC_ID_HEVC && m_pAVCtx->profile == FF_PROFILE_HEVC_MAIN_10) || (m_nCodecId == AV_CODEC_ID_VP9 && m_pAVCtx->profile == FF_PROFILE_VP9_2)); const auto bBitdepthChanged = (m_bHighBitdepth != bHighBitdepth); m_nSurfaceWidth = FFALIGN(c->coded_width, m_nAlign); m_nSurfaceHeight = FFALIGN(c->coded_height, m_nAlign); m_bHighBitdepth = bHighBitdepth; avcodec_flush_buffers(c); if (SUCCEEDED(hr = FindDecoderConfiguration())) { if (bBitdepthChanged) { ChangeOutputMediaFormat(2); } hr = RecommitAllocator(); } if (FAILED(hr)) { SAFE_DELETE(m_pDXVADecoder); m_nDecoderMode = MODE_SOFTWARE; DXVAState::ClearState(); InitDecoder(&m_pCurrentMediaType); ChangeOutputMediaFormat(2); } m_dxva_pix_fmt = m_pAVCtx->sw_pix_fmt; } } return hr; } int CMPCVideoDecFilter::av_get_buffer(struct AVCodecContext *c, AVFrame *pic, int flags) { CMPCVideoDecFilter* pFilter = static_cast<CMPCVideoDecFilter*>(c->opaque); CheckPointer(pFilter->m_pDXVADecoder, -1); if (!check_dxva_compatible(c->codec_id, c->sw_pix_fmt, c->profile)) { pFilter->m_bDXVACompatible = false; return -1; } if (FAILED(pFilter->CheckDXVA2Decoder(c))) { return -1; } return pFilter->m_pDXVADecoder->get_buffer_dxva(pic); } enum AVPixelFormat CMPCVideoDecFilter::av_get_format(struct AVCodecContext *c, const enum AVPixelFormat * pix_fmts) { CMPCVideoDecFilter* pFilter = static_cast<CMPCVideoDecFilter*>(c->opaque); const enum AVPixelFormat *p; for (p = pix_fmts; *p != -1; p++) { const AVPixFmtDescriptor *desc = av_pix_fmt_desc_get(*p); if (!desc || !(desc->flags & AV_PIX_FMT_FLAG_HWACCEL)) break; if (*p == AV_PIX_FMT_DXVA2_VLD) { if (FAILED(pFilter->CheckDXVA2Decoder(c))) { continue; } break; } } return *p; } // CVideoDecOutputPin CVideoDecOutputPin::CVideoDecOutputPin(TCHAR* pObjectName, CBaseVideoFilter* pFilter, HRESULT* phr, LPCWSTR pName) : CBaseVideoOutputPin(pObjectName, pFilter, phr, pName) , m_pVideoDecFilter(static_cast<CMPCVideoDecFilter*>(pFilter)) { } CVideoDecOutputPin::~CVideoDecOutputPin() { } HRESULT CVideoDecOutputPin::InitAllocator(IMemAllocator **ppAlloc) { if (m_pVideoDecFilter && m_pVideoDecFilter->UseDXVA2()) { return m_pVideoDecFilter->InitAllocator(ppAlloc); } return __super::InitAllocator(ppAlloc); } namespace MPCVideoDec { void GetSupportedFormatList(FORMATS& fmts) { fmts.clear(); for (size_t i = 0; i < _countof(sudPinTypesIn); i++) { FORMAT fmt = { sudPinTypesIn[i].clsMajorType, ffCodecs[i].clsMinorType, ffCodecs[i].FFMPEGCode, ffCodecs[i].DXVACode }; fmts.push_back(fmt); } } } // namespace MPCVideoDec
31.857347
250
0.707311
1aq
565fc0923bd94d8fe5517012355b458a73609f61
839
hpp
C++
user.hpp
chenillax/E4C_Challenge_Carbozer
3c23b9f106d6b148b84ff2af7e87f8a4ece8b771
[ "Apache-2.0" ]
null
null
null
user.hpp
chenillax/E4C_Challenge_Carbozer
3c23b9f106d6b148b84ff2af7e87f8a4ece8b771
[ "Apache-2.0" ]
null
null
null
user.hpp
chenillax/E4C_Challenge_Carbozer
3c23b9f106d6b148b84ff2af7e87f8a4ece8b771
[ "Apache-2.0" ]
null
null
null
#ifndef __USER__ #define __USER__ #include <cstdio> #include <cstdlib> #include <iostream> #include <vector> #include <string> /* The differents enumerations we need to our algortithm */ enum class Terminal_device { Phone, Pc, ChromeCast, Tablet}; enum class Quality { Auto, p144, p240, p360,p480,p720,p1080}; enum class Stream { Wifi, Net}; enum class Localisation {France, Germany, Spain, GreatBritain, Italy,Norway, Sweden,Poland,Belgium,Portugal}; class Terminal { public: Terminal_device device; public : Terminal(){}; Terminal(Terminal_device device); //returns the embedded emission of the device double embedded_emission(); //returns the emission the device consumes (gC02eq/hours) (We chose thant the "auto mode" is the mean of each quality.) double emission_per_hours(); }; #endif
24.676471
123
0.724672
chenillax
56630015bb06d9de967c4e747d9407f2d116dd69
1,086
cpp
C++
cpp/src/main.cpp
cnloni/othello
f80f190e505b6a4dd2b2bd49054651dbea4f00fa
[ "Apache-2.0" ]
1
2021-01-16T03:34:06.000Z
2021-01-16T03:34:06.000Z
cpp/src/main.cpp
cnloni/othello
f80f190e505b6a4dd2b2bd49054651dbea4f00fa
[ "Apache-2.0" ]
null
null
null
cpp/src/main.cpp
cnloni/othello
f80f190e505b6a4dd2b2bd49054651dbea4f00fa
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "b36.hpp" #include "board.hpp" using namespace std; void execute(uint64_t bp, uint64_t wp, int turn, int alpha, int beta) { Board<B36> board; int result = board.getBestResult(bp, wp, turn, alpha, beta); cout << board.getFinalBoardString() << endl; cout << "Initial = " << board.getInitialNodeString() << endl; cout << "Final = " << board.getFinalNodeString() << endl; cout << "Result = " << result << endl; cout << "Moves = " << board.getMoveListString() << endl; cout << "Count = " << board.getNodeCount() << endl; cout << "Elapsed = " << board.getElapsedTime() << endl; } //12駒から int main12() { execute(1753344, 81854976, 0, -6, -2); return 0; } //14駒から int main14() { execute(551158016, 69329408, 0, -6, -2); return 0; } //16駒から int main16() { execute(550219776, 70271748, 0, -6, -2); return 0; } int main(int narg, char** argv) { int sel = 12; if (narg > 1) { sel = atoi(argv[1]); } cout << "Selected = " << sel << endl; switch(sel) { case 14: return main14(); case 16: return main16(); default: return main12(); } }
21.72
71
0.617864
cnloni
5664c4ef1c5b2b7b8b5d2ca9902fd2afaa132a88
23,964
cpp
C++
basecode/debugger/environment.cpp
Alaboudi1/bootstrap
4ec4629424ad6fe70c84d95d79b2132f24832379
[ "MIT" ]
32
2018-05-14T23:26:54.000Z
2020-06-14T10:13:20.000Z
basecode/debugger/environment.cpp
Alaboudi1/bootstrap
4ec4629424ad6fe70c84d95d79b2132f24832379
[ "MIT" ]
79
2018-08-01T11:50:45.000Z
2020-11-17T13:40:06.000Z
basecode/debugger/environment.cpp
Alaboudi1/bootstrap
4ec4629424ad6fe70c84d95d79b2132f24832379
[ "MIT" ]
14
2021-01-08T05:05:19.000Z
2022-03-27T14:56:56.000Z
// ---------------------------------------------------------------------------- // // Basecode Bootstrap Compiler // Copyright (C) 2018 Jeff Panici // All rights reserved. // // This software source file is licensed under the terms of MIT license. // For details, please read the LICENSE file. // // ---------------------------------------------------------------------------- #include <vm/terp.h> #include <vm/label.h> #include <vm/assembler.h> #include <common/defer.h> #include <parser/token.h> #include <compiler/session.h> #include <common/string_support.h> #include "environment.h" #include "stack_window.h" #include "header_window.h" #include "footer_window.h" #include "output_window.h" #include "memory_window.h" #include "errors_window.h" #include "command_window.h" #include "assembly_window.h" #include "registers_window.h" namespace basecode::debugger { std::unordered_map<command_type_t, command_handler_function_t> environment::s_command_handlers = { {command_type_t::help, std::bind(&environment::on_help, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, {command_type_t::find, std::bind(&environment::on_find, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, {command_type_t::goto_line, std::bind(&environment::on_goto_line, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, {command_type_t::show_memory, std::bind(&environment::on_show_memory, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, {command_type_t::read_memory, std::bind(&environment::on_read_memory, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, {command_type_t::write_memory, std::bind(&environment::on_write_memory, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)}, }; /////////////////////////////////////////////////////////////////////////// environment::environment(compiler::session& session) :_session(session) { } environment::~environment() { delete _stack_window; delete _output_window; delete _header_window; delete _footer_window; delete _memory_window; delete _command_window; delete _assembly_window; delete _registers_window; } int environment::ch() const { return _ch; } void environment::draw_all() { _header_window->draw(*this); _footer_window->draw(*this); _assembly_window->draw(*this); _registers_window->draw(*this); _memory_window->draw(*this); _output_window->draw(*this); _stack_window->draw(*this); _command_window->draw(*this); _errors_window->draw(*this); refresh(); } void environment::pop_state() { if (_state_stack.empty()) return; _state_stack.pop(); } void environment::cancel_command() { if (current_state() != debugger_state_t::command_entry) return; pop_state(); _header_window->mark_dirty(); _command_window->mark_dirty(); draw_all(); } bool environment::run(common::result& r) { auto& terp = _session.terp(); _output_window->start_redirect(); while (true) { auto pc = terp.register_file().r[vm::register_pc].qw; auto bp = breakpoint(pc); if (bp != nullptr && bp->enabled && current_state() != debugger_state_t::break_s) { push_state(debugger_state_t::break_s); _header_window->mark_dirty(); _assembly_window->mark_dirty(); } auto user_step = false; _ch = getch(); switch (_ch) { case KEY_F(1): { push_state(debugger_state_t::command_entry); _header_window->mark_dirty(); _command_window->reset(); break; } case KEY_F(2): { terp.reset(); pc = terp.register_file().r[vm::register_pc].qw; unwind_state_stack(); _output_window->clear(); _stack_window->mark_dirty(); _header_window->mark_dirty(); _memory_window->mark_dirty(); _registers_window->mark_dirty(); _assembly_window->move_to_address(pc); break; } case KEY_F(3): { goto _exit; } case KEY_F(8): { if (current_state() == debugger_state_t::break_s) { pop_state(); if (current_state() == debugger_state_t::running) { pop_state(); push_state(debugger_state_t::single_step); } } if (current_state() == debugger_state_t::single_step) { user_step = true; } else { // XXX: state error } break; } case KEY_F(9): { switch (current_state()) { case debugger_state_t::ended: case debugger_state_t::errored: case debugger_state_t::running: case debugger_state_t::command_entry: case debugger_state_t::command_execute: { break; } case debugger_state_t::stopped: { push_state(debugger_state_t::single_step); _assembly_window->move_to_address(pc); break; } case debugger_state_t::break_s: { pop_state(); if (current_state() == debugger_state_t::single_step) { pop_state(); push_state(debugger_state_t::running); } break; } case debugger_state_t::single_step: { pop_state(); push_state(debugger_state_t::running); break; } } _header_window->mark_dirty(); break; } case CTRL('c'): { if (current_state() == debugger_state_t::running) pop_state(); _stack_window->mark_dirty(); _header_window->mark_dirty(); _output_window->mark_dirty(); _memory_window->mark_dirty(); _assembly_window->mark_dirty(); _registers_window->mark_dirty(); break; } case CTRL('r'): { _registers_window->update(*this); break; } case ERR: { break; } default: { switch (current_state()) { case debugger_state_t::errored: { _errors_window->update(*this); _errors_window->mark_dirty(); break; } case debugger_state_t::command_entry: _command_window->update(*this); _command_window->mark_dirty(); _header_window->mark_dirty(); break; default: _assembly_window->update(*this); break; } break; } } bool execute_next_step; if (user_step) { execute_next_step = current_state() == debugger_state_t::single_step; } else { execute_next_step = current_state() == debugger_state_t::running; }; if (execute_next_step) { common::result step_result {}; auto success = terp.step(step_result); if (!success) { pop_state(); push_state(debugger_state_t::errored); _errors_window->visible(true); } else { pc = terp.register_file().r[vm::register_pc].qw; if (terp.has_exited()) { pop_state(); push_state(debugger_state_t::ended); } else { _assembly_window->move_to_address(pc); } } _stack_window->mark_dirty(); _header_window->mark_dirty(); _memory_window->mark_dirty(); _registers_window->mark_dirty(); } _output_window->process_buffers(); draw_all(); refresh(); } _exit: _output_window->stop_redirect(); return true; } void environment::unwind_state_stack() { while (!_state_stack.empty()) _state_stack.pop(); } breakpoint_t* environment::add_breakpoint( uint64_t address, breakpoint_type_t type) { auto bp = breakpoint(address); if (bp != nullptr) return bp; auto it = _breakpoints.insert(std::make_pair( address, breakpoint_t{true, address, type})); return &it.first->second; } compiler::session& environment::session() { return _session; } bool environment::shutdown(common::result& r) { endwin(); return true; } bool environment::initialize(common::result& r) { initscr(); start_color(); raw(); keypad(stdscr, true); noecho(); nodelay(stdscr, true); init_pair(1, COLOR_BLUE, COLOR_WHITE); init_pair(2, COLOR_BLUE, COLOR_YELLOW); init_pair(3, COLOR_RED, COLOR_WHITE); init_pair(4, COLOR_CYAN, COLOR_WHITE); _main_window = new window(nullptr, stdscr); _main_window->initialize(); _header_window = new header_window( _main_window, 0, 0, _main_window->max_width(), 1); _header_window->initialize(); _footer_window = new footer_window( _main_window, 0, _main_window->max_height() - 1, _main_window->max_width(), 1); _footer_window->initialize(); _command_window = new command_window( _main_window, 0, _main_window->max_height() - 2, _main_window->max_width(), 1); _command_window->initialize(); _assembly_window = new assembly_window( _main_window, 0, 1, _main_window->max_width() - 23, _main_window->max_height() - 15); _assembly_window->initialize(); _registers_window = new registers_window( _main_window, _main_window->max_width() - 23, 1, 23, _main_window->max_height() - 15); _registers_window->initialize(); _stack_window = new stack_window( _main_window, _main_window->max_width() - 44, _main_window->max_height() - 14, 44, 12); _stack_window->initialize(); auto left_section = _main_window->max_width() - _stack_window->width(); _memory_window = new memory_window( _main_window, 0, _main_window->max_height() - 14, left_section / 2, 12); _memory_window->address(reinterpret_cast<uint64_t>(_session.terp().heap())); _memory_window->initialize(); _output_window = new output_window( _main_window, _memory_window->x() + _memory_window->width(), _memory_window->y(), _memory_window->width(), _memory_window->height()); _output_window->initialize(); _errors_window = new errors_window( _main_window, 2, 2, _main_window->max_width() - 2, _main_window->max_height() - 2); _errors_window->visible(false); _errors_window->initialize(); // XXX: since we only have the one listing source file for now // automatically select it. auto& listing = _session.assembler().listing(); auto file_names = listing.file_names(); if (!file_names.empty()) _assembly_window->source_file(listing.source_file(file_names.front())); refresh(); draw_all(); return true; } debugger_state_t environment::current_state() const { if (_state_stack.empty()) return debugger_state_t::stopped; return _state_stack.top(); } void environment::push_state(debugger_state_t state) { _state_stack.push(state); } void environment::remove_breakpoint(uint64_t address) { _breakpoints.erase(address); } breakpoint_t* environment::breakpoint(uint64_t address) { auto it = _breakpoints.find(address); if (it == _breakpoints.end()) return nullptr; return &it->second; } bool environment::execute_command(const std::string& input) { if (input.empty()) { cancel_command(); return true; } common::result result {}; push_state(debugger_state_t::command_execute); _header_window->mark_dirty(); _command_window->mark_dirty(); draw_all(); defer({ pop_state(); _command_window->reset(); _header_window->mark_dirty(); _command_window->mark_dirty(); draw_all(); }); std::string part {}; std::vector<std::string> parts {}; size_t index = 0; auto in_quotes = false; while (index < input.size()) { auto c = input[index]; if (isspace(c)) { if (!in_quotes) { parts.emplace_back(part); part.clear(); } else { part += " "; } } else if (isalnum(c) || c == '_' || c == '$' || c == '.' || c == ':' || c == ';' || c == '/' || c == '%' || c == '-' || c == ',' || c == '@') { part += c; } else if (c == '\"' || c == '\'') { if (in_quotes) { part += '\''; parts.emplace_back(part); part.clear(); in_quotes = false; } else { part += '\''; in_quotes = true; } } ++index; } if (!part.empty()) parts.emplace_back(part); command_data_t cmd_data {}; cmd_data.name = parts[0]; if (!cmd_data.parse(result)) return false; command_t cmd {}; cmd.command = cmd_data; index = 1; for (const auto& kvp : cmd.command.prototype.params) { if (kvp.second.required && index < parts.size()) { auto param = parts[index]; auto first_char = param[0]; auto upper_first_char = std::toupper(param[0]); if (first_char == '@') { number_data_t data {}; data.radix = 8; data.input = param; if (data.parse(data.value) != syntax::conversion_result_t::success) break; cmd.arguments.insert(std::make_pair(kvp.first, data)); } else if (first_char == '%') { number_data_t data {}; data.radix = 2; data.input = param; if (data.parse(data.value) != syntax::conversion_result_t::success) return false; cmd.arguments.insert(std::make_pair(kvp.first, data)); } else if (first_char == '$') { number_data_t data {}; data.radix = 16; data.input = param; if (data.parse(data.value) != syntax::conversion_result_t::success) return false; cmd.arguments.insert(std::make_pair(kvp.first, data)); } else if (isdigit(first_char)) { number_data_t data {}; data.radix = 10; data.input = param; if (data.parse(data.value) != syntax::conversion_result_t::success) return false; cmd.arguments.insert(std::make_pair(kvp.first, data)); } else if (first_char == '\'') { string_data_t data {}; data.input = param.substr(1, param.length() - 1); cmd.arguments.insert(std::make_pair(kvp.first, data)); } else if (first_char == '_') { symbol_data_t data {}; data.input = param; } else if (upper_first_char == 'I' || upper_first_char == 'F' || upper_first_char == 'S' || upper_first_char == 'P') { register_data_t data {}; data.input = param; common::result r; if (!data.parse(r)) { symbol_data_t symbol_data {}; symbol_data.input = param; cmd.arguments.insert(std::make_pair(kvp.first, symbol_data)); } else { cmd.arguments.insert(std::make_pair(kvp.first, data)); } } else { result.error( "X000", fmt::format( "unrecognized parameter '{}' value: {}", kvp.second.name, param)); break; } } else { result.error( "X000", fmt::format("missing required parameter: {}", kvp.second.name)); break; } ++index; } if (result.is_failed()) { return false; } auto handler_it = s_command_handlers.find(cmd.command.prototype.type); if (handler_it == s_command_handlers.end()) { result.error( "X000", fmt::format("no command handler: {}", cmd.command.name)); return false; } return handler_it->second(this, result, cmd); } uint64_t environment::get_address(const command_argument_t* arg) const { uint64_t address = 0; switch (arg->type()) { case command_parameter_type_t::symbol: { auto sym = arg->data<symbol_data_t>(); if (sym != nullptr) { auto& assembler = _session.assembler(); auto label = assembler.find_label(sym->input); if (label != nullptr) address = label->address(); } break; } case command_parameter_type_t::number: { auto number = arg->data<number_data_t>(); if (number != nullptr) address = number->value; break; } case command_parameter_type_t::register_t: { auto reg = arg->data<register_data_t>(); if (reg != nullptr) address = register_value(*reg); break; } default: { break; } } return address; } uint64_t environment::register_value(const register_data_t& reg) const { auto& terp = _session.terp(); auto register_file = terp.register_file(); uint64_t value = 0; switch (reg.value) { case vm::registers_t::pc: { value = register_file.r[vm::register_pc].qw + reg.offset; break; } case vm::registers_t::sp: { value = register_file.r[vm::register_sp].qw + reg.offset; break; } case vm::registers_t::fp: { value = register_file.r[vm::register_fp].qw + reg.offset; break; } case vm::registers_t::sr: { value = register_file.r[vm::register_sr].qw + reg.offset; break; } default: { if (reg.type == vm::register_type_t::integer) { value = register_file.r[vm::register_integer_start + reg.value].qw + reg.offset; } else { value = register_file.r[vm::register_float_start + reg.value].qw + reg.offset; } break; } } return value; } bool environment::on_help(common::result& r, const command_t& command) { return true; } bool environment::on_find(common::result& r, const command_t& command) { return true; } bool environment::on_goto_line(common::result& r, const command_t& command) { auto line_number_arg = command.arg("line_number"); if (line_number_arg != nullptr) { auto line_number = line_number_arg->data<number_data_t>(); _assembly_window->move_to_line(line_number->value); } return true; } bool environment::on_show_memory(common::result& r, const command_t& command) { auto address_arg = command.arg("address"); if (address_arg != nullptr) { auto address = get_address(address_arg); if (address != 0) { _memory_window->address(address); } } return true; } bool environment::on_read_memory(common::result& r, const command_t& command) { auto address_arg = command.arg("address"); if (address_arg != nullptr) { auto& terp = _session.terp(); auto address = get_address(address_arg); if (address != 0) { auto value = terp.read(command.command.size, address); fmt::print("\n*read memory\n*-----------\n"); fmt::print("*${:016X}: ", address); auto value_ptr = reinterpret_cast<uint8_t*>(&value); for (size_t i = 0; i < vm::op_size_in_bytes(command.command.size); i++) fmt::print("{:02X} ", *value_ptr++); fmt::print("\n"); } } return true; } bool environment::on_write_memory(common::result& r, const command_t& command) { return true; } };
34.780842
151
0.473919
Alaboudi1
566d612e789c06c43ad236e9688c509257bc4523
7,764
hpp
C++
libraries/belle/Source/Core/Prim/Complex.hpp
jogawebb/Spaghettis
78f21ba3065ce316ef0cb84e94aecc9e8787343d
[ "Zlib", "BSD-2-Clause", "BSD-3-Clause" ]
47
2017-09-05T02:49:22.000Z
2022-01-20T08:11:47.000Z
libraries/belle/Source/Core/Prim/Complex.hpp
jogawebb/Spaghettis
78f21ba3065ce316ef0cb84e94aecc9e8787343d
[ "Zlib", "BSD-2-Clause", "BSD-3-Clause" ]
106
2018-05-16T14:58:52.000Z
2022-01-12T13:57:24.000Z
libraries/belle/Source/Core/Prim/Complex.hpp
jogawebb/Spaghettis
78f21ba3065ce316ef0cb84e94aecc9e8787343d
[ "Zlib", "BSD-2-Clause", "BSD-3-Clause" ]
11
2018-05-16T06:44:51.000Z
2021-11-10T07:04:46.000Z
/* Copyright (c) 2007-2013 William Andrew Burnson. Copyright (c) 2013-2020 Nicolas Danet. */ /* < http://opensource.org/licenses/BSD-2-Clause > */ // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- namespace prim { // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - template < class T > class Complex { // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: Complex (T x = T(), T y = T()) : x_ (x), y_ (y) { } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- #if PRIM_CPP11 public: Complex (const Complex < T > &) = default; Complex (Complex < T > &&) = default; Complex < T > & operator = (const Complex < T > &) = default; Complex < T > & operator = (Complex < T > &&) = default; #endif // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: T& getX() { return x_; } const T& getX() const { return x_; } T& getY() { return y_; } const T& getY() const { return y_; } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: const Complex < T > operator += (Complex < T > c) { x_ += c.x_; y_ += c.y_; return *this; } const Complex < T > operator -= (Complex < T > c) { x_ -= c.x_; y_ -= c.y_; return *this; } const Complex < T > operator *= (Complex < T > c) { T x = (x_ * c.x_ - y_ * c.y_); T y = (x_ * c.y_ + c.x_ * y_); x_ = x; y_ = y; return *this; } const Complex < T > operator /= (Complex < T > c) { double d = (c.x_ * c.x_) + (c.y_ * c.y_); T x = static_cast < T > ((x_ * c.x_ + y_ * c.y_) / d); T y = static_cast < T > ((c.x_ * y_ - x_ * c.y_) / d); x_ = x; y_ = y; return *this; } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: double angle() const { double t = atan2 (y_, x_); if (t < 0.0) { t += kTwoPi; } return t; } double magnitude() const { double x = static_cast < double > (x_); double y = static_cast < double > (y_); return sqrt (x * x + y * y); } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: void setAngle (double a) { setPolar (a, magnitude()); } void setMagnitude (double m) { setPolar (angle(), m); } void setPolar (double a, double m) { *this = Complex < T >::withPolar (a, m); } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: const Complex < T > operator -() { return Complex (-x_, -y_); } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - public: static Complex < T > withPolar (double a, double m) { return Complex < T > (T (std::cos (a) * m), T (std::sin (a) * m)); } private: T x_; T y_; private: PRIM_LEAK_DETECTOR (Complex) // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - friend bool operator != (Complex < T > a, Complex < T > b) { return !(a == b); } friend bool operator == (Complex < T > a, Complex < T > b) { return (a.x_ == b.x_) && (a.y_ == b.y_); } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - friend const Complex < T > operator + (Complex < T > a, Complex < T > b) { return a += b; } friend const Complex < T > operator - (Complex < T > a, Complex < T > b) { return a -= b; } friend const Complex < T > operator * (Complex < T > a, Complex < T > b) { return a *= b; } friend const Complex < T > operator / (Complex < T > a, Complex < T > b) { return a /= b; } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- /* < http://www.cs.princeton.edu/~rs/AlgsDS07/16Geometric.pdf > */ // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- // MARK: - friend int clockwiseOrder (Complex < T > a, Complex < T > b, Complex < T > c) { double t1 = (static_cast < double > (b.x_) - static_cast < double > (a.x_)); double t2 = (static_cast < double > (c.y_) - static_cast < double > (a.y_)); double t3 = (static_cast < double > (b.y_) - static_cast < double > (a.y_)); double t4 = (static_cast < double > (c.x_) - static_cast < double > (a.x_)); double d = (t1 * t2) - (t3 * t4); if (d < 0) { return 1; } /* Clockwise. */ else if (d > 0) { return -1; } /* Counterclockwise. */ else { return 0; /* Collinear. */ } } // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- }; // ----------------------------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------------------------- } // namespace prim // ----------------------------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------------------------
30.687747
110
0.238408
jogawebb
566f3a6aa4a7d3ed0971e84c8c6282ffa26cafea
1,910
hpp
C++
framework/graphics/graphics/render_target/render_target.hpp
YiJiangFengYun/vulkan-graphics-examples
e7b788b8f47dd238b08840c019940c7c52335a54
[ "MIT" ]
1
2018-03-01T01:05:25.000Z
2018-03-01T01:05:25.000Z
framework/graphics/graphics/render_target/render_target.hpp
YiJiangFengYun/vulkan-graphics-examples
e7b788b8f47dd238b08840c019940c7c52335a54
[ "MIT" ]
null
null
null
framework/graphics/graphics/render_target/render_target.hpp
YiJiangFengYun/vulkan-graphics-examples
e7b788b8f47dd238b08840c019940c7c52335a54
[ "MIT" ]
null
null
null
#ifndef VG_RENDER_TARGET_HPP #define VG_RENDER_TARGET_HPP #include "graphics/global.hpp" namespace vg { class BaseRenderTarget { public: BaseRenderTarget(uint32_t framebufferWidth = 0u , uint32_t framebufferHeight = 0u ); uint32_t getFramebufferWidth() const; uint32_t getFramebufferHeight() const; const fd::Rect2D & getRenderArea() const; void setRenderArea(const fd::Rect2D & area); uint32_t getClearValueCount() const; const vk::ClearValue *getClearValues() const; void setClearValues(const vk::ClearValue *pClearValue, uint32_t clearValueCount); protected: uint32_t m_framebufferWidth; uint32_t m_framebufferHeight; fd::Rect2D m_renderArea; std::vector<vk::ClearValue> m_clearValues; }; class OnceRenderTarget : public BaseRenderTarget { public: OnceRenderTarget(uint32_t framebufferWidth = 0u , uint32_t framebufferHeight = 0u ); const vk::RenderPass * getRenderPass() const; const vk::Framebuffer * getFramebuffer() const; protected: vk::RenderPass *m_pRenderPass; vk::Framebuffer *m_pFramebuffer; }; class MultiRenderTarget : public BaseRenderTarget { public: MultiRenderTarget(uint32_t framebufferWidth = 0u , uint32_t framebufferHeight = 0u ); const vk::RenderPass * getFirstRenderPass() const; const vk::RenderPass * getSecondRenderPass() const; const vk::Framebuffer * getFirstFramebuffer() const; const vk::Framebuffer * getSecondFramebuffer() const; protected: vk::RenderPass *m_pFirstRenderPass; vk::RenderPass *m_pSecondRenderPass; vk::Framebuffer *m_pFirstFramebuffer; vk::Framebuffer *m_pSecondFramebuffer; }; } //vg #endif //VG_RENDER_TARGET_HPP
32.372881
89
0.66178
YiJiangFengYun
56720c144b05a88018c932b433a8c585033f0131
2,041
cpp
C++
src/Settings.cpp
gottyduke/BunnyHopperOfSkyrim
0b7539298bd0899060cc926bf3fc2b5758835014
[ "MIT" ]
2
2021-03-24T20:39:02.000Z
2021-08-09T02:12:10.000Z
src/Settings.cpp
gottyduke/BunnyHopperOfSkyrim
0b7539298bd0899060cc926bf3fc2b5758835014
[ "MIT" ]
null
null
null
src/Settings.cpp
gottyduke/BunnyHopperOfSkyrim
0b7539298bd0899060cc926bf3fc2b5758835014
[ "MIT" ]
2
2021-03-24T20:39:04.000Z
2021-08-09T02:12:15.000Z
#include "Settings.h" bool Settings::LoadSettings(const bool a_dumpParse) { auto [log, success] = J2S::load_settings(FILE_NAME, a_dumpParse); if (!log.empty()) { _ERROR("%s", log.c_str()); } return success; } decltype(Settings::globalSpeedMult) Settings::globalSpeedMult("globalSpeedMult", 1.0f); decltype(Settings::maxSpeed) Settings::maxSpeed("maxSpeed", 450.0f); decltype(Settings::misttepAllowed) Settings::misttepAllowed("misstepAllowed", 4); decltype(Settings::baseSpeedBoost) Settings::baseSpeedBoost("baseSpeedBoost", 1.0f); decltype(Settings::baseSpeedMult) Settings::baseSpeedMult("baseSpeedMult", 1.0f); decltype(Settings::minStrafeAngle) Settings::minStrafeAngle("minStrafeAngle", 35.0f); decltype(Settings::maxStrafeAngle) Settings::maxStrafeAngle("maxStrafeAngle", 95.0f); decltype(Settings::strafeDeadzone) Settings::strafeDeadzone("strafeDeadzone", 35.0f); decltype(Settings::strafeSpeedMult) Settings::strafeSpeedMult("strafeSpeedMult", 0.5f); decltype(Settings::minHeightLaunch) Settings::minHeightLaunch("minHeightLaunch", 140.0f); decltype(Settings::heightLaunchMult) Settings::heightLaunchMult("heightLaunchMult", 0.5f); decltype(Settings::crouchSpeedBoost) Settings::crouchSpeedBoost("crouchSpeedBoost", 32.0f); decltype(Settings::crouchBoostMult) Settings::crouchBoostMult("crouchBoostMult", 1.0f); decltype(Settings::crouchBoostCooldown) Settings::crouchBoostCooldown("crouchBoostCooldown", 6); decltype(Settings::ramDamage) Settings::ramDamage("ramDamage", 5.0f); decltype(Settings::ramDamageMult) Settings::ramDamageMult("ramDamageMult", 0.3f); decltype(Settings::ramSpeedThreshold) Settings::ramSpeedThreshold("ramSpeedThreshold", 220.0f); decltype(Settings::ramSpeedReduction) Settings::ramSpeedReduction("ramSpeedReduction", 0.5f); decltype(Settings::enableJumpFeedback) Settings::enableJumpFeedback("enableJumpFeedback", true); decltype(Settings::enableFovZoom) Settings::enableFovZoom("enableFovZoom", true); decltype(Settings::enableTremble) Settings::enableTremble("enableTremble", false);
47.465116
96
0.799118
gottyduke
56796e2def726508cf2edce78e7c18190d9ceeb1
1,905
inl
C++
dependencies/gl++/framebuffer/Framebuffer.inl
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
6
2015-12-29T07:21:01.000Z
2020-05-29T10:47:38.000Z
dependencies/gl++/framebuffer/Framebuffer.inl
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
null
null
null
dependencies/gl++/framebuffer/Framebuffer.inl
jaredhoberock/gotham
e3551cc355646530574d086d7cc2b82e41e8f798
[ "Apache-2.0" ]
null
null
null
/*! \file Framebuffer.inl * \author Jared Hoberock * \brief Inline file for Framebuffer.h. */ #include "Framebuffer.h" Framebuffer::Framebuffer(void):Parent() { setTarget(GL_FRAMEBUFFER_EXT); } // end Framebuffer::Framebuffer() void Framebuffer::attachTexture(const GLenum textureTarget, const GLenum attachment, const GLuint texture, const GLint level) { glFramebufferTexture2DEXT(getTarget(), attachment, textureTarget, texture, level); } // end Framebuffer::attachTexture() void Framebuffer::attachTextureLayer(const GLenum attachment, const GLuint texture, const GLint layer, const GLint level) { #ifdef WIN32 glFramebufferTextureLayerEXT(getTarget(), attachment, texture, level, layer); #else std::cerr << "Not implemented on Ubuntu yet." << std::endl; #endif // WIN32 } // end Framebuffer::attachTextureLayer() void Framebuffer::attachRenderbuffer(const GLenum renderbufferTarget, const GLenum attachment, const GLuint renderbuffer) { glFramebufferRenderbufferEXT(getTarget(), attachment, renderbufferTarget, renderbuffer); } // end Framebuffer::attachRenderbuffer() void Framebuffer::detach(const GLenum attachment) { glFramebufferTexture2DEXT(getTarget(), attachment, GL_TEXTURE_RECTANGLE_NV, 0, 0); } // end Framebuffer::detach() bool Framebuffer::isComplete(void) const { return GL_FRAMEBUFFER_COMPLETE_EXT == glCheckFramebufferStatusEXT(getTarget()); } // end Framebuffer::isComplete()
34.636364
82
0.580577
jaredhoberock
5683b9d1393d2d9026b43d7ac0d9abaff4b5a99a
6,028
hpp
C++
source/sema/sema_node_visitor.hpp
stryku/cmakesl
e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326
[ "BSD-3-Clause" ]
51
2019-05-06T01:33:34.000Z
2021-11-17T11:44:54.000Z
source/sema/sema_node_visitor.hpp
stryku/cmakesl
e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326
[ "BSD-3-Clause" ]
191
2019-05-06T18:31:24.000Z
2020-06-19T06:48:06.000Z
source/sema/sema_node_visitor.hpp
stryku/cmakesl
e53bffed62ae9ca68c0c2de0de8e2a94bfe4d326
[ "BSD-3-Clause" ]
3
2019-10-12T21:03:29.000Z
2020-06-19T06:22:25.000Z
#pragma once namespace cmsl::sema { class add_declarative_file_node; class add_subdirectory_node; class add_subdirectory_with_declarative_script_node; class add_subdirectory_with_old_script_node; class binary_operator_node; class block_node; class bool_value_node; class break_node; class cast_to_reference_node; class cast_to_reference_to_base_node; class cast_to_base_value_node; class cast_to_value_node; class class_member_access_node; class class_node; class conditional_node; class constructor_call_node; class designated_initializers_node; class double_value_node; class enum_constant_access_node; class enum_node; class for_node; class function_call_node; class function_node; class id_node; class if_else_node; class implicit_member_function_call_node; class implicit_return_node; class import_node; class initializer_list_node; class int_value_node; class member_function_call_node; class namespace_node; class return_node; class sema_node; class string_value_node; class ternary_operator_node; class translation_unit_node; class unary_operator_node; class variable_declaration_node; class while_node; class sema_node_visitor { public: virtual ~sema_node_visitor() = default; virtual void visit(const initializer_list_node& node) = 0; virtual void visit(const add_declarative_file_node& node) = 0; virtual void visit(const add_subdirectory_node& node) = 0; virtual void visit( const add_subdirectory_with_declarative_script_node& node) = 0; virtual void visit(const add_subdirectory_with_old_script_node& node) = 0; virtual void visit(const binary_operator_node& node) = 0; virtual void visit(const block_node& node) = 0; virtual void visit(const bool_value_node& node) = 0; virtual void visit(const break_node& node) = 0; virtual void visit(const cast_to_reference_node& node) = 0; virtual void visit(const cast_to_value_node& node) = 0; virtual void visit(const cast_to_reference_to_base_node& node) = 0; virtual void visit(const cast_to_base_value_node& node) = 0; virtual void visit(const class_member_access_node& node) = 0; virtual void visit(const class_node& node) = 0; virtual void visit(const conditional_node& node) = 0; virtual void visit(const constructor_call_node& node) = 0; virtual void visit(const designated_initializers_node& node) = 0; virtual void visit(const double_value_node& node) = 0; virtual void visit(const enum_constant_access_node& node) = 0; virtual void visit(const enum_node& node) = 0; virtual void visit(const for_node& node) = 0; virtual void visit(const function_call_node& node) = 0; virtual void visit(const function_node& node) = 0; virtual void visit(const id_node& node) = 0; virtual void visit(const if_else_node& node) = 0; virtual void visit(const implicit_member_function_call_node& node) = 0; virtual void visit(const implicit_return_node& node) = 0; virtual void visit(const import_node& node) = 0; virtual void visit(const int_value_node& node) = 0; virtual void visit(const member_function_call_node& node) = 0; virtual void visit(const namespace_node& node) = 0; virtual void visit(const return_node& node) = 0; virtual void visit(const string_value_node& node) = 0; virtual void visit(const ternary_operator_node& node) = 0; virtual void visit(const translation_unit_node& node) = 0; virtual void visit(const unary_operator_node& node) = 0; virtual void visit(const variable_declaration_node& node) = 0; virtual void visit(const while_node& node) = 0; }; class empty_sema_node_visitor : public sema_node_visitor { public: virtual ~empty_sema_node_visitor() = default; virtual void visit(const add_declarative_file_node&) override {} virtual void visit(const add_subdirectory_node&) override {} virtual void visit(const add_subdirectory_with_old_script_node&) override {} virtual void visit( const add_subdirectory_with_declarative_script_node& node) override { } virtual void visit(const binary_operator_node&) override {} virtual void visit(const block_node&) override {} virtual void visit(const bool_value_node&) override {} virtual void visit(const break_node&) override {} virtual void visit(const cast_to_reference_to_base_node&) override {} virtual void visit(const cast_to_base_value_node&) override {} virtual void visit(const cast_to_reference_node&) override {} virtual void visit(const cast_to_value_node&) override {} virtual void visit(const class_member_access_node&) override {} virtual void visit(const class_node&) override {} virtual void visit(const conditional_node&) override {} virtual void visit(const constructor_call_node&) override {} virtual void visit(const designated_initializers_node&) override {} virtual void visit(const double_value_node&) override {} virtual void visit(const enum_constant_access_node&) override {} virtual void visit(const enum_node&) override {} virtual void visit(const for_node&) override {} virtual void visit(const function_call_node&) override {} virtual void visit(const function_node&) override {} virtual void visit(const id_node&) override {} virtual void visit(const if_else_node&) override {} virtual void visit(const implicit_member_function_call_node&) override {} virtual void visit(const implicit_return_node&) override {} virtual void visit(const import_node&) override {} virtual void visit(const initializer_list_node&) override {} virtual void visit(const int_value_node&) override {} virtual void visit(const member_function_call_node&) override {} virtual void visit(const namespace_node&) override {} virtual void visit(const return_node&) override {} virtual void visit(const string_value_node&) override {} virtual void visit(const ternary_operator_node&) override {} virtual void visit(const translation_unit_node&) override {} virtual void visit(const unary_operator_node&) override {} virtual void visit(const variable_declaration_node&) override {} virtual void visit(const while_node&) override {} }; }
42.751773
78
0.7928
stryku
5693400ae915eb521f4cda991780ee13e607e42f
13,436
cc
C++
cpp/src/arrow/compute/exec/task_util.cc
karldw/arrow
0d995486e6eb4c94a64f03578731aad05c151596
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
1
2020-09-30T02:48:39.000Z
2020-09-30T02:48:39.000Z
cpp/src/arrow/compute/exec/task_util.cc
karldw/arrow
0d995486e6eb4c94a64f03578731aad05c151596
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
20
2021-05-09T06:53:01.000Z
2022-03-27T22:21:50.000Z
cpp/src/arrow/compute/exec/task_util.cc
karldw/arrow
0d995486e6eb4c94a64f03578731aad05c151596
[ "CC-BY-3.0", "Apache-2.0", "CC0-1.0", "MIT" ]
2
2021-08-05T14:58:01.000Z
2021-08-10T14:16:01.000Z
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "arrow/compute/exec/task_util.h" #include <algorithm> #include <mutex> #include "arrow/util/logging.h" namespace arrow { namespace compute { class TaskSchedulerImpl : public TaskScheduler { public: TaskSchedulerImpl(); int RegisterTaskGroup(TaskImpl task_impl, TaskGroupContinuationImpl cont_impl) override; void RegisterEnd() override; Status StartTaskGroup(size_t thread_id, int group_id, int64_t total_num_tasks) override; Status ExecuteMore(size_t thread_id, int num_tasks_to_execute, bool execute_all) override; Status StartScheduling(size_t thread_id, ScheduleImpl schedule_impl, int num_concurrent_tasks, bool use_sync_execution) override; void Abort(AbortContinuationImpl impl) override; private: // Task group state transitions progress one way. // Seeing an old version of the state by a thread is a valid situation. // enum class TaskGroupState : int { NOT_READY, READY, ALL_TASKS_STARTED, ALL_TASKS_FINISHED }; struct TaskGroup { TaskGroup(TaskImpl task_impl, TaskGroupContinuationImpl cont_impl) : task_impl_(std::move(task_impl)), cont_impl_(std::move(cont_impl)), state_(TaskGroupState::NOT_READY), num_tasks_present_(0) { num_tasks_started_.value.store(0); num_tasks_finished_.value.store(0); } TaskGroup(const TaskGroup& src) : task_impl_(src.task_impl_), cont_impl_(src.cont_impl_), state_(TaskGroupState::NOT_READY), num_tasks_present_(0) { ARROW_DCHECK(src.state_ == TaskGroupState::NOT_READY); num_tasks_started_.value.store(0); num_tasks_finished_.value.store(0); } TaskImpl task_impl_; TaskGroupContinuationImpl cont_impl_; TaskGroupState state_; int64_t num_tasks_present_; AtomicWithPadding<int64_t> num_tasks_started_; AtomicWithPadding<int64_t> num_tasks_finished_; }; std::vector<std::pair<int, int64_t>> PickTasks(int num_tasks, int start_task_group = 0); Status ExecuteTask(size_t thread_id, int group_id, int64_t task_id, bool* task_group_finished); bool PostExecuteTask(size_t thread_id, int group_id); Status OnTaskGroupFinished(size_t thread_id, int group_id, bool* all_task_groups_finished); Status ScheduleMore(size_t thread_id, int num_tasks_finished = 0); bool use_sync_execution_; int num_concurrent_tasks_; ScheduleImpl schedule_impl_; AbortContinuationImpl abort_cont_impl_; std::vector<TaskGroup> task_groups_; bool aborted_; bool register_finished_; std::mutex mutex_; // Mutex protecting task_groups_ (state_ and num_tasks_present_ // fields), aborted_ flag and register_finished_ flag AtomicWithPadding<int> num_tasks_to_schedule_; }; TaskSchedulerImpl::TaskSchedulerImpl() : use_sync_execution_(false), num_concurrent_tasks_(0), aborted_(false), register_finished_(false) { num_tasks_to_schedule_.value.store(0); } int TaskSchedulerImpl::RegisterTaskGroup(TaskImpl task_impl, TaskGroupContinuationImpl cont_impl) { int result = static_cast<int>(task_groups_.size()); task_groups_.emplace_back(std::move(task_impl), std::move(cont_impl)); return result; } void TaskSchedulerImpl::RegisterEnd() { std::lock_guard<std::mutex> lock(mutex_); register_finished_ = true; } Status TaskSchedulerImpl::StartTaskGroup(size_t thread_id, int group_id, int64_t total_num_tasks) { ARROW_DCHECK(group_id >= 0 && group_id < static_cast<int>(task_groups_.size())); TaskGroup& task_group = task_groups_[group_id]; bool aborted = false; bool all_tasks_finished = false; { std::lock_guard<std::mutex> lock(mutex_); aborted = aborted_; if (task_group.state_ == TaskGroupState::NOT_READY) { task_group.num_tasks_present_ = total_num_tasks; if (total_num_tasks == 0) { task_group.state_ = TaskGroupState::ALL_TASKS_FINISHED; all_tasks_finished = true; } task_group.state_ = TaskGroupState::READY; } } if (!aborted && all_tasks_finished) { bool all_task_groups_finished = false; RETURN_NOT_OK(OnTaskGroupFinished(thread_id, group_id, &all_task_groups_finished)); if (all_task_groups_finished) { return Status::OK(); } } if (!aborted) { return ScheduleMore(thread_id); } else { return Status::Cancelled("Scheduler cancelled"); } } std::vector<std::pair<int, int64_t>> TaskSchedulerImpl::PickTasks(int num_tasks, int start_task_group) { std::vector<std::pair<int, int64_t>> result; for (size_t i = 0; i < task_groups_.size(); ++i) { int task_group_id = static_cast<int>((start_task_group + i) % (task_groups_.size())); TaskGroup& task_group = task_groups_[task_group_id]; if (task_group.state_ != TaskGroupState::READY) { continue; } int num_tasks_remaining = num_tasks - static_cast<int>(result.size()); int64_t start_task = task_group.num_tasks_started_.value.fetch_add(num_tasks_remaining); if (start_task >= task_group.num_tasks_present_) { continue; } int num_tasks_current_group = num_tasks_remaining; if (start_task + num_tasks_current_group >= task_group.num_tasks_present_) { { std::lock_guard<std::mutex> lock(mutex_); if (task_group.state_ == TaskGroupState::READY) { task_group.state_ = TaskGroupState::ALL_TASKS_STARTED; } } num_tasks_current_group = static_cast<int>(task_group.num_tasks_present_ - start_task); } for (int64_t task_id = start_task; task_id < start_task + num_tasks_current_group; ++task_id) { result.push_back(std::make_pair(task_group_id, task_id)); } if (static_cast<int>(result.size()) == num_tasks) { break; } } return result; } Status TaskSchedulerImpl::ExecuteTask(size_t thread_id, int group_id, int64_t task_id, bool* task_group_finished) { if (!aborted_) { RETURN_NOT_OK(task_groups_[group_id].task_impl_(thread_id, task_id)); } *task_group_finished = PostExecuteTask(thread_id, group_id); return Status::OK(); } bool TaskSchedulerImpl::PostExecuteTask(size_t thread_id, int group_id) { int64_t total = task_groups_[group_id].num_tasks_present_; int64_t prev_finished = task_groups_[group_id].num_tasks_finished_.value.fetch_add(1); bool all_tasks_finished = (prev_finished + 1 == total); return all_tasks_finished; } Status TaskSchedulerImpl::OnTaskGroupFinished(size_t thread_id, int group_id, bool* all_task_groups_finished) { bool aborted = false; { std::lock_guard<std::mutex> lock(mutex_); aborted = aborted_; TaskGroup& task_group = task_groups_[group_id]; task_group.state_ = TaskGroupState::ALL_TASKS_FINISHED; *all_task_groups_finished = true; for (size_t i = 0; i < task_groups_.size(); ++i) { if (task_groups_[i].state_ != TaskGroupState::ALL_TASKS_FINISHED) { *all_task_groups_finished = false; break; } } } if (aborted && *all_task_groups_finished) { abort_cont_impl_(); return Status::Cancelled("Scheduler cancelled"); } if (!aborted) { RETURN_NOT_OK(task_groups_[group_id].cont_impl_(thread_id)); } return Status::OK(); } Status TaskSchedulerImpl::ExecuteMore(size_t thread_id, int num_tasks_to_execute, bool execute_all) { num_tasks_to_execute = std::max(1, num_tasks_to_execute); int last_id = 0; for (;;) { if (aborted_) { return Status::Cancelled("Scheduler cancelled"); } // Pick next bundle of tasks const auto& tasks = PickTasks(num_tasks_to_execute, last_id); if (tasks.empty()) { break; } last_id = tasks.back().first; // Execute picked tasks immediately for (size_t i = 0; i < tasks.size(); ++i) { int group_id = tasks[i].first; int64_t task_id = tasks[i].second; bool task_group_finished = false; Status status = ExecuteTask(thread_id, group_id, task_id, &task_group_finished); if (!status.ok()) { // Mark the remaining picked tasks as finished for (size_t j = i + 1; j < tasks.size(); ++j) { if (PostExecuteTask(thread_id, tasks[j].first)) { bool all_task_groups_finished = false; RETURN_NOT_OK( OnTaskGroupFinished(thread_id, group_id, &all_task_groups_finished)); if (all_task_groups_finished) { return Status::OK(); } } } return status; } else { if (task_group_finished) { bool all_task_groups_finished = false; RETURN_NOT_OK( OnTaskGroupFinished(thread_id, group_id, &all_task_groups_finished)); if (all_task_groups_finished) { return Status::OK(); } } } } if (!execute_all) { num_tasks_to_execute -= static_cast<int>(tasks.size()); if (num_tasks_to_execute == 0) { break; } } } return Status::OK(); } Status TaskSchedulerImpl::StartScheduling(size_t thread_id, ScheduleImpl schedule_impl, int num_concurrent_tasks, bool use_sync_execution) { schedule_impl_ = std::move(schedule_impl); use_sync_execution_ = use_sync_execution; num_concurrent_tasks_ = num_concurrent_tasks; num_tasks_to_schedule_.value += num_concurrent_tasks; return ScheduleMore(thread_id); } Status TaskSchedulerImpl::ScheduleMore(size_t thread_id, int num_tasks_finished) { if (aborted_) { return Status::Cancelled("Scheduler cancelled"); } ARROW_DCHECK(register_finished_); if (use_sync_execution_) { return ExecuteMore(thread_id, 1, true); } int num_new_tasks = num_tasks_finished; for (;;) { int expected = num_tasks_to_schedule_.value.load(); if (num_tasks_to_schedule_.value.compare_exchange_strong(expected, 0)) { num_new_tasks += expected; break; } } if (num_new_tasks == 0) { return Status::OK(); } const auto& tasks = PickTasks(num_new_tasks); if (static_cast<int>(tasks.size()) < num_new_tasks) { num_tasks_to_schedule_.value += num_new_tasks - static_cast<int>(tasks.size()); } for (size_t i = 0; i < tasks.size(); ++i) { int group_id = tasks[i].first; int64_t task_id = tasks[i].second; RETURN_NOT_OK(schedule_impl_([this, group_id, task_id](size_t thread_id) -> Status { RETURN_NOT_OK(ScheduleMore(thread_id, 1)); bool task_group_finished = false; RETURN_NOT_OK(ExecuteTask(thread_id, group_id, task_id, &task_group_finished)); if (task_group_finished) { bool all_task_groups_finished = false; return OnTaskGroupFinished(thread_id, group_id, &all_task_groups_finished); } return Status::OK(); })); } return Status::OK(); } void TaskSchedulerImpl::Abort(AbortContinuationImpl impl) { bool all_finished = true; { std::lock_guard<std::mutex> lock(mutex_); aborted_ = true; abort_cont_impl_ = std::move(impl); if (register_finished_) { for (size_t i = 0; i < task_groups_.size(); ++i) { TaskGroup& task_group = task_groups_[i]; if (task_group.state_ == TaskGroupState::NOT_READY) { task_group.state_ = TaskGroupState::ALL_TASKS_FINISHED; } else if (task_group.state_ == TaskGroupState::READY) { int64_t expected = task_group.num_tasks_started_.value.load(); for (;;) { if (task_group.num_tasks_started_.value.compare_exchange_strong( expected, task_group.num_tasks_present_)) { break; } } int64_t before_add = task_group.num_tasks_finished_.value.fetch_add( task_group.num_tasks_present_ - expected); if (before_add >= expected) { task_group.state_ = TaskGroupState::ALL_TASKS_FINISHED; } else { all_finished = false; task_group.state_ = TaskGroupState::ALL_TASKS_STARTED; } } } } } if (all_finished) { abort_cont_impl_(); } } std::unique_ptr<TaskScheduler> TaskScheduler::Make() { std::unique_ptr<TaskSchedulerImpl> impl{new TaskSchedulerImpl()}; return std::move(impl); } } // namespace compute } // namespace arrow
33.012285
90
0.670735
karldw
5696b9aa3e2c61a83029c42663ffd8eb0d19ff5f
2,305
cpp
C++
Few Course Reader Exercises/Cap8-Exercises/Ex3/cap8_ex3.cpp
diogoamvasconcelos/CS106b-eroberts2015-solutions
8964130bb872990b809e74ed489237e0c1c96604
[ "MIT" ]
4
2017-06-26T09:44:28.000Z
2020-01-19T05:42:41.000Z
Few Course Reader Exercises/Cap8-Exercises/Ex3/cap8_ex3.cpp
diogoamvasconcelos/CS106b-eroberts2015-solutions
8964130bb872990b809e74ed489237e0c1c96604
[ "MIT" ]
null
null
null
Few Course Reader Exercises/Cap8-Exercises/Ex3/cap8_ex3.cpp
diogoamvasconcelos/CS106b-eroberts2015-solutions
8964130bb872990b809e74ed489237e0c1c96604
[ "MIT" ]
1
2020-10-08T08:26:07.000Z
2020-10-08T08:26:07.000Z
#include <iostream> #include "console.h" #include "simpio.h" #include "stack.h" using namespace std; struct HanoiTask { int num_disks; char start_pile; char finish_pile; char temp_pile; }; const char PILE_A = 'A'; const char PILE_B = 'B'; const char PILE_C = 'C'; void MoveHanoiTower(int n); void MoveSingleDisk(char start, char finish); int main() { while(true) { int n = getInteger("Hanoi n:"); if(n < 1) break; MoveHanoiTower(n); } return 0; } void MoveHanoiTower(int n) { Stack<HanoiTask> tasks_stack; HanoiTask starting_task; starting_task.num_disks = n; starting_task.start_pile = PILE_A; starting_task.finish_pile = PILE_B; starting_task.temp_pile = PILE_C; tasks_stack.push(starting_task); while(tasks_stack.size() > 0) { HanoiTask current_task = tasks_stack.pop(); if(current_task.num_disks < 2) { MoveSingleDisk(current_task.start_pile, current_task.finish_pile); } else { HanoiTask move_from_top_task; move_from_top_task.num_disks = current_task.num_disks - 1; move_from_top_task.start_pile = current_task.start_pile; move_from_top_task.finish_pile = current_task.temp_pile; move_from_top_task.temp_pile = current_task.finish_pile; HanoiTask move_single_disk_task; move_single_disk_task.num_disks = 1; move_single_disk_task.start_pile = current_task.start_pile; move_single_disk_task.finish_pile = current_task.finish_pile; move_single_disk_task.temp_pile = current_task.temp_pile; HanoiTask move_back_task; move_back_task.num_disks = current_task.num_disks - 1; move_back_task.start_pile = current_task.temp_pile; move_back_task.finish_pile = current_task.finish_pile; move_back_task.temp_pile = current_task.start_pile; //Stack, first in last out, so tasks need to be correctly stacked tasks_stack.push(move_back_task); tasks_stack.push(move_single_disk_task); tasks_stack.push(move_from_top_task); } } } void MoveSingleDisk(char start, char finish) { cout << start << "->" << finish << endl; }
25.898876
78
0.660738
diogoamvasconcelos
5698e98f860d2e7e16e6b35725e4ad8d1ad5bc0e
2,682
cpp
C++
lib-src/vgui/ProgressBar.cpp
Velaron/vgui_dll
9ebb9ab4abf49ba3bd4aad8d102923a0d61d139b
[ "BSD-3-Clause" ]
22
2017-02-21T04:30:12.000Z
2022-02-13T22:40:39.000Z
lib-src/vgui/ProgressBar.cpp
FWGS/vgui_dll
4a677fc844f3d92c1b83c6a0f748242a2601286e
[ "BSD-3-Clause" ]
1
2017-05-08T18:31:26.000Z
2017-05-08T18:31:26.000Z
lib-src/vgui/ProgressBar.cpp
nagist/vgui_dll
acf73ec95a4499b229d68854819fb5e951de1759
[ "BSD-3-Clause" ]
12
2017-02-18T16:03:05.000Z
2021-12-30T16:34:27.000Z
/* * BSD 3-Clause License * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * 3. Neither the name of the copyright holder nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 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<math.h> #include<VGUI_ProgressBar.h> using namespace vgui; ProgressBar::ProgressBar(int segmentCount) { _segmentCount=segmentCount; _progress=0; } void ProgressBar::paintBackground() { int wide,tall; getPaintSize(wide,tall); drawSetColor(Scheme::sc_secondary2); drawFilledRect(0,0,wide,tall); const int segmentGap=2; int segmentWide=wide/_segmentCount-segmentGap; const float rr=0; const float gg=0; const float bb=100; int x=0; int litSeg=(int)floor(_progress); for(int i=litSeg;i>0;i--) { drawSetColor((int)rr,(int)gg,(int)bb,0); drawFilledRect(x,0,x+segmentWide,tall); x+=segmentWide+segmentGap; } if(_segmentCount>_progress) { float frac=_progress-(float)floor(_progress); float r=0; float g=255-(frac*155); float b=0; drawSetColor((int)r,(int)g,(int)b,0); drawFilledRect(x,0,x+segmentWide,tall); } } void ProgressBar::setProgress(float progress) { if(_progress!=progress) { _progress=progress; repaint(); } } int ProgressBar::getSegmentCount() { return _segmentCount; }
29.472527
82
0.722222
Velaron
569aae33732ac9c6f639809ca8468c3ca1e3d69b
3,150
hh
C++
src/NodeList/FixedSmoothingScale.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/NodeList/FixedSmoothingScale.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/NodeList/FixedSmoothingScale.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // FixedSmoothingScale // // Implements the static fixed smoothing scale option. // // Created by JMO, Wed Sep 14 13:50:49 PDT 2005 //----------------------------------------------------------------------------// #ifndef __Spheral_NodeSpace_FixedSmooothingScale__ #define __Spheral_NodeSpace_FixedSmooothingScale__ #include "SmoothingScaleBase.hh" namespace Spheral { template<typename Dimension> class FixedSmoothingScale: public SmoothingScaleBase<Dimension> { public: //--------------------------- Public Interface ---------------------------// typedef typename Dimension::Scalar Scalar; typedef typename Dimension::Vector Vector; typedef typename Dimension::Tensor Tensor; typedef typename Dimension::SymTensor SymTensor; // Constructors, destructor. FixedSmoothingScale(); FixedSmoothingScale(const FixedSmoothingScale& rhs); FixedSmoothingScale& operator=(const FixedSmoothingScale& rhs); virtual ~FixedSmoothingScale(); // Time derivative of the smoothing scale. virtual SymTensor smoothingScaleDerivative(const SymTensor& H, const Vector& pos, const Tensor& DvDx, const Scalar hmin, const Scalar hmax, const Scalar hminratio, const Scalar nPerh) const; // Return a new H, with limiting based on the old value. virtual SymTensor newSmoothingScale(const SymTensor& H, const Vector& pos, const Scalar zerothMoment, const SymTensor& secondMoment, const TableKernel<Dimension>& W, const Scalar hmin, const Scalar hmax, const Scalar hminratio, const Scalar nPerh, const ConnectivityMap<Dimension>& connectivityMap, const unsigned nodeListi, const unsigned i) const; // Determine an "ideal" H for the given moments. virtual SymTensor idealSmoothingScale(const SymTensor& H, const Vector& pos, const Scalar zerothMoment, const SymTensor& secondMoment, const TableKernel<Dimension>& W, const Scalar hmin, const Scalar hmax, const Scalar hminratio, const Scalar nPerh, const ConnectivityMap<Dimension>& connectivityMap, const unsigned nodeListi, const unsigned i) const; // Compute the new H tensors for a tessellation. virtual SymTensor idealSmoothingScale(const SymTensor& H, const Mesh<Dimension>& mesh, const typename Mesh<Dimension>::Zone& zone, const Scalar hmin, const Scalar hmax, const Scalar hminratio, const Scalar nPerh) const; }; } #endif
35.795455
80
0.546984
jmikeowen
569d1bc85900ccbadf1d6542ed46ef40ad524806
2,252
cpp
C++
Verkehrssituation/src/tests/Verkehrssituation.cpp
DavidHeiss/vs2
a00a58acab582e22e426a290eff9dd251edda992
[ "MIT" ]
null
null
null
Verkehrssituation/src/tests/Verkehrssituation.cpp
DavidHeiss/vs2
a00a58acab582e22e426a290eff9dd251edda992
[ "MIT" ]
null
null
null
Verkehrssituation/src/tests/Verkehrssituation.cpp
DavidHeiss/vs2
a00a58acab582e22e426a290eff9dd251edda992
[ "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "../Verkehrssituation.h" class VerkehrssituationTest : public testing::Test { protected: void SetUp() override { verkehrssituation = Sensor::Verkehrssitation(); } Sensor::Verkehrssitation verkehrssituation; }; TEST_F(VerkehrssituationTest , has_data) { auto message = verkehrssituation.generateMessage(); ASSERT_TRUE(message.has_data()); } TEST_F(VerkehrssituationTest, has_from_address) { auto message = verkehrssituation.generateMessage(); ASSERT_FALSE(message.has_from_address()); } TEST_F(VerkehrssituationTest, has_from_port) { auto message = verkehrssituation.generateMessage(); ASSERT_FALSE(message.has_from_port()); } TEST_F(VerkehrssituationTest, has_latency) { auto message = verkehrssituation.generateMessage(); ASSERT_FALSE(message.has_latency()); } TEST_F(VerkehrssituationTest, has_received) { auto message = verkehrssituation.generateMessage(); ASSERT_FALSE(message.has_received()); } TEST_F(VerkehrssituationTest, has_round_trip) { auto message = verkehrssituation.generateMessage(); ASSERT_FALSE(message.has_round_trip()); } TEST_F(VerkehrssituationTest, has_send) { auto message = verkehrssituation.generateMessage(); ASSERT_TRUE(message.has_send()); } TEST_F(VerkehrssituationTest, has_to_address) { auto message = verkehrssituation.generateMessage(); ASSERT_FALSE(message.has_to_address()); } TEST_F(VerkehrssituationTest, has_to_port) { auto message = verkehrssituation.generateMessage(); ASSERT_FALSE(message.has_to_port()); } TEST_F(VerkehrssituationTest, has_numeric_value) { auto data = verkehrssituation.generateMessage().data(); ASSERT_TRUE(data.has_numeric_value()); } TEST_F(VerkehrssituationTest, has_rising) { auto data = verkehrssituation.generateMessage().data(); ASSERT_TRUE(data.has_rising()); } TEST_F(VerkehrssituationTest, has_type) { auto data = verkehrssituation.generateMessage().data(); ASSERT_TRUE(data.has_type()); } TEST_F(VerkehrssituationTest, has_value) { auto data = verkehrssituation.generateMessage().data(); ASSERT_TRUE(data.has_value()); } int main() { testing::InitGoogleTest(); return RUN_ALL_TESTS(); }
21.245283
59
0.746892
DavidHeiss
56a06f3fe2fa251050dd996c7bc7fdc016d33694
4,924
cpp
C++
src/box2ddestructionlistener.cpp
bobweaver/qml-box2d
905841c01d6603678d34f0f8aaaf6843b70dc08a
[ "Zlib" ]
1
2022-02-09T19:14:01.000Z
2022-02-09T19:14:01.000Z
src/box2ddestructionlistener.cpp
bobweaver/qml-box2d
905841c01d6603678d34f0f8aaaf6843b70dc08a
[ "Zlib" ]
null
null
null
src/box2ddestructionlistener.cpp
bobweaver/qml-box2d
905841c01d6603678d34f0f8aaaf6843b70dc08a
[ "Zlib" ]
null
null
null
/* * box2ddestructionlistener.cpp * Copyright (c) 2011 Joonas Erkinheimo <[email protected]> * Copyright (c) 2011 Thorbjørn Lindeijer <[email protected]> * * This file is part of the Box2D QML plugin. * * This software is provided 'as-is', without any express or implied warranty. * In no event will the authors be held liable for any damages arising from * the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software in * a product, an acknowledgment in the product documentation would be * appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source distribution. */ #include "box2ddestructionlistener.h" #include "box2djoint.h" #include "box2dfixture.h" /*! \class Box2DDestructionListener \title DestructionListener Class \brief Box2D doesn't use reference counting. So if you destroy a body it is really gone. Accessing a pointer to a destroyed body has undefined behavior. In other words, your program will likely crash and burn. To help fix these problems, the debug build memory manager fills destroyed entities with FDFDFDFD. This can help find problems more easily in some cases. If you destroy a Box2D entity, it is up to you to make sure you remove all references to the destroyed object. This is easy if you only have a single reference to the entity. If you have multiple references, you might consider implementing a handle class to wrap the raw pointer. Often when using Box2D you will create and destroy many bodies, shapes, and joints. Managing these entities is somewhat automated by Box2D. If you destroy a body then all associated shapes and joints are automatically destroyed. This is called implicit destruction. When you destroy a body, all its attached shapes, joints, and contacts are destroyed. This is called implicit destruction. Any body connected to one of those joints and/or contacts is woken. This process is usually convenient. However, you must be aware of one crucial issue: Caution When a body is destroyed, all fixtures and joints attached to the body are automatically destroyed. You must nullify any pointers you have to those shapes and joints. Otherwise, your program will die horribly if you try to access or destroy those shapes or joints later. To help you nullify your joint pointers, Box2D provides a listener class named b2DestructionListener that you can implement and provide to your world object. Then the world object will notify you when a joint is going to be implicitly destroyed Note that there no notification when a joint or fixture is explicitly destroyed. In this case ownership is clear and you can perform the necessary cleanup on the spot. If you like, you can call your own implementation of b2DestructionListener to keep cleanup code centralized. Implicit destruction is a great convenience in many cases. It can also make your program fall apart. You may store pointers to shapes and joints somewhere in your code. These pointers become orphaned when an associated body is destroyed. The situation becomes worse when you consider that joints are often created by a part of the code unrelated to management of the associated body. For example, the testbed creates a b2MouseJoint for interactive manipulation of bodies on the screen. Box2D provides a callback mechanism to inform your application when implicit destruction occurs. This gives your application a chance to nullify the orphaned pointers. This callback mechanism is described later in this manual. You can implement a b2DestructionListener that allows b2World to inform you when a shape or joint is implicitly destroyed because an associated body was destroyed. This will help prevent your code from accessing orphaned pointers. class MyDestructionListener : public b2DestructionListener { void SayGoodbye(b2Joint* joint) { // remove all references to joint. } }; You can then register an instance of your destruction listener with your world object. You should do this during world initialization. myWorld->SetListener(myDestructionListener); */ Box2DDestructionListener::Box2DDestructionListener(QObject *parent) : QObject(parent) { } void Box2DDestructionListener::SayGoodbye(b2Joint *joint) { if (joint->GetUserData()) { Box2DJoint *temp = toBox2DJoint(joint); temp->nullifyJoint(); delete temp; } } void Box2DDestructionListener::SayGoodbye(b2Fixture *fixture) { emit fixtureDestroyed(toBox2DFixture(fixture)); }
49.24
108
0.791024
bobweaver
56a5da54a9181d31831549916dddaef3e59252fd
616
cpp
C++
factory.cpp
iambillzhao/Movie-Store
fdd8aea26a3169844ad011a43b8271d7cb2ed6f0
[ "MIT" ]
1
2020-07-10T06:48:34.000Z
2020-07-10T06:48:34.000Z
factory.cpp
iambillzhao/Movie-Store
fdd8aea26a3169844ad011a43b8271d7cb2ed6f0
[ "MIT" ]
null
null
null
factory.cpp
iambillzhao/Movie-Store
fdd8aea26a3169844ad011a43b8271d7cb2ed6f0
[ "MIT" ]
null
null
null
/* * factory.cpp is part of the Movie Store Simulator, a C++ program that * offers the function of borrow, return, or stock with up to 10,000 * customers and 26 genres of movies * * @author Bill Zhao, Lucas Bradley * @date March 12th */ #include "factory.h" #include <iostream> // buildMovie takes a string Input and builds the // movie according to specifications Movie *Factory::buildMovie(std::string Input) { char Type = Input[0]; if (Type == 'F') return new Comedy(Input); if (Type == 'C') return new Classic(Input); if (Type == 'D') return new Drama(Input); return nullptr; }
22
71
0.672078
iambillzhao
56a7158d66e5a8137e78fd42274f43080a4a3243
554
cpp
C++
test/predict/main.cpp
coffee-lord/angonoka
a8a4a79da4092630c5243c2081f92ba39d0b056c
[ "MIT" ]
2
2019-10-23T18:05:25.000Z
2022-02-21T21:53:24.000Z
test/predict/main.cpp
coffee-lord/angonoka
a8a4a79da4092630c5243c2081f92ba39d0b056c
[ "MIT" ]
3
2022-02-12T19:52:27.000Z
2022-02-12T19:55:52.000Z
test/stun/stochastic_tunneling/main.cpp
coffee-lord/angonoka
a8a4a79da4092630c5243c2081f92ba39d0b056c
[ "MIT" ]
null
null
null
#include <boost/ut.hpp> // boost::ut relies on static destructors so if // we don't defer LLVM coverage report until after // ut's destructor we won't get any coverage. #if defined(__llvm__) && defined(ANGONOKA_COVERAGE) extern "C" { int __llvm_profile_runtime; void __llvm_profile_initialize_file(void); int __llvm_profile_write_file(void); }; namespace { struct on_exit { ~on_exit() noexcept { __llvm_profile_initialize_file(); __llvm_profile_write_file(); }; }; constinit on_exit _; }; // namespace #endif int main() { }
22.16
51
0.718412
coffee-lord
56a9d5b4f56c4c293fe2f0c7bb6f54377a4c2296
2,791
cpp
C++
jmtpfs/src/jmtpfs-0.5/src/MtpMetadataCache.cpp
akshaykumar23399/DOTS
e7779f7c849e4d7f08eec5adce4fa8317d04b80d
[ "Unlicense" ]
null
null
null
jmtpfs/src/jmtpfs-0.5/src/MtpMetadataCache.cpp
akshaykumar23399/DOTS
e7779f7c849e4d7f08eec5adce4fa8317d04b80d
[ "Unlicense" ]
null
null
null
jmtpfs/src/jmtpfs-0.5/src/MtpMetadataCache.cpp
akshaykumar23399/DOTS
e7779f7c849e4d7f08eec5adce4fa8317d04b80d
[ "Unlicense" ]
null
null
null
/* * MtpMetadataCache.cpp * * Author: Jason Ferrara * * This software is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 3 as published by the Free Software Foundation. * * This software 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 library; if not, write to the * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02111-1301, USA. * [email protected] */ #include "MtpMetadataCache.h" #include <time.h> #include <assert.h> MtpMetadataCacheFiller::~MtpMetadataCacheFiller() { } MtpMetadataCache::MtpMetadataCache() { } MtpMetadataCache::~MtpMetadataCache() { for(local_file_cache_type::iterator i = m_localFileCache.begin(); i != m_localFileCache.end(); i++) { delete i->second; } } MtpNodeMetadata MtpMetadataCache::getItem(uint32_t id, MtpMetadataCacheFiller& source) { clearOld(); cache_lookup_type::iterator i = m_cacheLookup.find(id); if (i != m_cacheLookup.end()) return i->second->data; CacheEntry newData; newData.data = source.getMetadata(); assert(newData.data.self.id == id); newData.whenCreated = time(0); m_cacheLookup[id] = m_cache.insert(m_cache.end(), newData); return newData.data; } void MtpMetadataCache::clearItem(uint32_t id) { cache_lookup_type::iterator i = m_cacheLookup.find(id); if (i != m_cacheLookup.end()) { m_cache.erase(i->second); m_cacheLookup.erase(i); } } void MtpMetadataCache::clearOld() { time_t now = time(0); for(cache_type::iterator i = m_cache.begin(); i != m_cache.end();) { if ((now - i->whenCreated) > 5) { m_cacheLookup.erase(m_cacheLookup.find(i->data.self.id)); i = m_cache.erase(i); } else return; } } MtpLocalFileCopy* MtpMetadataCache::openFile(MtpDevice& device, uint32_t id) { local_file_cache_type::iterator i = m_localFileCache.find(id); if (i != m_localFileCache.end()) return i->second; MtpLocalFileCopy* newFile = new MtpLocalFileCopy(device, id); m_localFileCache[id] = newFile; return newFile; } MtpLocalFileCopy* MtpMetadataCache::getOpenedFile(uint32_t id) { local_file_cache_type::iterator i = m_localFileCache.find(id); if (i != m_localFileCache.end()) return i->second; else return 0; } uint32_t MtpMetadataCache::closeFile(uint32_t id) { local_file_cache_type::iterator i = m_localFileCache.find(id); if (i != m_localFileCache.end()) { uint32_t newId = i->second->close(); delete i->second; m_localFileCache.erase(i); return newId; } return id; }
23.652542
100
0.724113
akshaykumar23399
56abeca03db4452942dae28104ef62327d65de85
4,176
hpp
C++
core/src/Simulation/AssetManager.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
36
2015-03-12T10:42:36.000Z
2022-01-12T04:20:40.000Z
core/src/Simulation/AssetManager.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
1
2015-12-17T00:25:43.000Z
2016-02-20T12:00:57.000Z
core/src/Simulation/AssetManager.hpp
hhsaez/crimild
e3efee09489939338df55e8af9a1f9ddc01301f7
[ "BSD-3-Clause" ]
6
2017-06-17T07:57:53.000Z
2019-04-09T21:11:24.000Z
/* * Copyright (c) 2013, Hernan Saez * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the <organization> nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> 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. */ #ifndef CRIMILD_CORE_SIMULATION_ASSET_MANAGER_ #define CRIMILD_CORE_SIMULATION_ASSET_MANAGER_ #include "Foundation/SharedObject.hpp" #include "Foundation/Macros.hpp" #include "Foundation/Singleton.hpp" #include "Visitors/ShallowCopy.hpp" #include <memory> #include <map> #include <string> #include <mutex> namespace crimild { class Texture; class AssetManager : public NonCopyable, public DynamicSingleton< AssetManager > { private: using Mutex = std::mutex; using ScopedLock = std::lock_guard< Mutex >; public: static constexpr const char *FONT_DEFAULT = "fonts/default"; static constexpr const char *FONT_SYSTEM = "fonts/system"; public: AssetManager( void ); virtual ~AssetManager( void ); void set( std::string name, SharedPointer< SharedObject > const &asset, bool isPersistent = false ) { ScopedLock lock( _mutex ); if ( isPersistent ) { _persistentAssets[ name ] = asset; } else { _assets[ name ] = asset; } } template< class T > T *get( std::string name ) { ScopedLock lock( _mutex ); auto &asset = _assets[ name ]; if ( asset == nullptr ) { asset = _persistentAssets[ name ]; } return static_cast< T * >( crimild::get_ptr( asset ) ); } template< class T > SharedPointer< T > clone( std::string filename ) { // No need for lock once we get the prototype auto assetProto = get< T >( filename ); assert( assetProto != nullptr && ( filename + " does not exist in Asset Manager cache" ).c_str() ); ShallowCopy shallowCopy; assetProto->perform( shallowCopy ); return shallowCopy.getResult< T >(); } void clear( bool clearAll = false ) { ScopedLock lock( _mutex ); _assets.clear(); if ( clearAll ) { _persistentAssets.clear(); } } private: std::map< std::string, SharedPointer< SharedObject > > _assets; std::map< std::string, SharedPointer< SharedObject > > _persistentAssets; Mutex _mutex; public: void loadFont( std::string name, std::string fileName ); }; template<> Texture *AssetManager::get< Texture >( std::string name ); } #endif
33.677419
111
0.625479
hhsaez
56afadad706c7d38fce2265cb20214649b49db93
548
hpp
C++
PP/decompose_const.hpp
Petkr/PP
646cc156603a6a9461e74d8f54786c0d5a9c32d2
[ "MIT" ]
3
2019-07-12T23:12:24.000Z
2019-09-05T07:57:45.000Z
PP/decompose_const.hpp
Petkr/PP
646cc156603a6a9461e74d8f54786c0d5a9c32d2
[ "MIT" ]
null
null
null
PP/decompose_const.hpp
Petkr/PP
646cc156603a6a9461e74d8f54786c0d5a9c32d2
[ "MIT" ]
null
null
null
#pragma once #include <PP/compose.hpp> #include <PP/cv_qualifier.hpp> #include <PP/decompose_pair.hpp> #include <PP/overloaded.hpp> #include <PP/to_type_t.hpp> #include <PP/value_t.hpp> namespace PP { PP_CIA decompose_const = compose( overloaded( []<typename T>(type_t<const T>) { return make_decompose_pair(type<T>, PP::value<cv_qualifier::Const>); }, []<typename T>(type_t<T>) { return make_decompose_pair(type<T>, PP::value<cv_qualifier::none>); }), to_type_t); }
23.826087
80
0.625912
Petkr
56b205ff002447e58f3296486d4f79983530a652
989
cpp
C++
MNO/MATCHORDER/yujungee.cpp
Queue-ri/Advanced-Algorithm-Study
f44a75e55fffedcd988bfe8301eac224462c872d
[ "MIT" ]
5
2022-01-13T08:21:54.000Z
2022-01-31T03:37:14.000Z
MNO/MATCHORDER/yujungee.cpp
Queue-ri/Advanced-Algorithm-Study
f44a75e55fffedcd988bfe8301eac224462c872d
[ "MIT" ]
115
2022-01-13T07:37:23.000Z
2022-03-13T14:09:15.000Z
MNO/MATCHORDER/yujungee.cpp
Queue-ri/Advanced-Algorithm-Study
f44a75e55fffedcd988bfe8301eac224462c872d
[ "MIT" ]
2
2022-01-27T02:10:23.000Z
2022-02-09T14:37:04.000Z
// // matchOrder.cpp // study6 // // Created by yujeong on 2021/03/05. // #include <iostream> #include <algorithm> #include <vector> using namespace std; int tc , n; int rus_r[100], kor_r[100]; vector<int> russian; vector<int> korean; int match() { sort(korean.begin(), korean.end()); int res = 0; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { if (korean[j] >= russian[i]) { res++; korean[j] = 0; break; } } } return res; } int main() { cin >> tc; while (tc--) { cin >> n; korean = russian = vector<int>(n); for (int i = 0; i < n; i++) { cin >> russian[i]; } for (int i = 0; i < n; i++) { cin >> korean[i]; } // 정렬 후 함수에 넣기 sort(russian.begin(), russian.end()); sort(korean.begin(), korean.end()); cout << match() << endl; } return 0; }
18.314815
45
0.436805
Queue-ri
56c5ba9bd8562df759d553e5f6081d2b713ebc66
4,417
hpp
C++
test/logdataprocessor.hpp
Bembelbots/particlefilter
7fc67763da217639de403485abf8a72029c5025a
[ "FSFAP" ]
null
null
null
test/logdataprocessor.hpp
Bembelbots/particlefilter
7fc67763da217639de403485abf8a72029c5025a
[ "FSFAP" ]
null
null
null
test/logdataprocessor.hpp
Bembelbots/particlefilter
7fc67763da217639de403485abf8a72029c5025a
[ "FSFAP" ]
null
null
null
#include <iostream> #include <string> #include <fstream> #include <definitions.h> #include <coords.h> #include <particlefilter.h> #include <random> struct LogData { int stamp; std::vector<Robot> poseEstimates; Robot wcs; std::vector<Robot> hypos; std::vector<DirectedCoord> odo; std::vector<VisionResult> visionResults; std::vector<std::string> s; std::vector<ParticleFilter::tLocalizationEvent> event; }; class LogDataset { public: std::vector<LogData> data; std::vector<LogData> output; //if multiple visualizations per output are needed LogDataset(const std::string &fn){ std::ifstream input(fn); LogData ld; //one cognition step in dataset for (std::string line; std::getline(input, line);) { if (line.size() < 3) { continue; } if (line.find("(") != 0) { continue; } int stamp = atoi(line.substr(1, line.find(")")).c_str()); ld.stamp = stamp; std::string s = line.substr(line.find(")") + 2); if (s.find("enter new cognition step:") == 0) { int step = atoi(s.substr(s.find(": ") + 2).c_str()); // add as new log data element data.push_back(ld); ld = LogData(); continue; } if (s.find("WCS: ") != std::string::npos) { ld.wcs.setFromString(s.substr(5)); continue; } if (s.find("Odometry: ") != std::string::npos) { size_t pos1 = s.find(";"); size_t pos2 = s.find(";", pos1 + 1); float x = atof(s.substr(10, pos1 - 10).c_str()); float y = atof(s.substr(pos1 + 1, pos2 - pos1 - 1).c_str()); float a = atof(s.substr(pos2 + 1).c_str()); ld.odo.push_back(DirectedCoord(x, y, a)); continue; } if (s.find("Measurement: ") != std::string::npos) { Robot r; r.setFromString(s.substr(13)); ld.poseEstimates.push_back(r); continue; } if (s.find("VisionResult: ") != std::string::npos) { VisionResult vr(s.substr(14)); ld.visionResults.push_back(vr); continue; } if (s.find("Emit event: ") != std::string::npos) { size_t pos = s.find(":"); ld.event.push_back(static_cast<ParticleFilter::tLocalizationEvent>(atoi(s.substr(pos+1).c_str()))); continue; } } std::cout << "read " << data.size() << " cognition steps from logfile " << std::endl; } void logtoFile(const std::string filename){ std::ofstream out(filename); int cognition_step = 0; for (auto d: output) { if (cognition_step %500 == 0){ std::cout<<cognition_step <<std::endl; } //start output with new declaration of cognition step out << "(" << d.stamp << ")" << " enter new cognition step: "<< cognition_step << std::endl; //outpus Robot position out << "(" << d.stamp << ") WCS: "<< d.wcs << std::endl; //output vision results for (auto vr : d.visionResults){ out<< "(" << d.stamp << ") " << "VisionResult: " << vr << std::endl; } //outpus measurement( pose estimations from landmarks) for (auto meas : d.poseEstimates){ out << "(" << d.stamp << ") Measurement: "<< meas << std::endl; } //output particle filter hypos for (auto hypo : d.hypos){ out << "(" << d.stamp << ") Hypo: "<< hypo << std::endl; } //output odometry for (auto odo:d.odo) { out << "(" << d.stamp << ") Odometry: "<< odo.coord.x << ";" << odo.coord.y << ";" << odo.angle.rad << std::endl; } //output localizationevent for (auto event : d.event){ out << "(" << d.stamp << ") Emit event: "<< (int) event << std::endl; } cognition_step ++; } out.close(); } };
35.620968
115
0.465927
Bembelbots
08cb00f666f1316b124ce7bd517dd7f05c8e0ca6
473
cpp
C++
src/buffers/Vb0BufferVec2.cpp
MrMCG/MGL
894a336505b510d18dc28e3adae747fd6938816a
[ "MIT" ]
null
null
null
src/buffers/Vb0BufferVec2.cpp
MrMCG/MGL
894a336505b510d18dc28e3adae747fd6938816a
[ "MIT" ]
null
null
null
src/buffers/Vb0BufferVec2.cpp
MrMCG/MGL
894a336505b510d18dc28e3adae747fd6938816a
[ "MIT" ]
null
null
null
#include <GL/glew.h> #include "VboBufferVec2.hpp" namespace MGL { VboBufferVec2::VboBufferVec2(std::vector<Vec2> const& data) : m_data(data) {} void VboBufferVec2::bufferData(int const location) const { bind(); glBufferData(GL_ARRAY_BUFFER, m_data.size() * sizeof(Vec2), &m_data.at(0), GL_STATIC_DRAW); glVertexAttribPointer(location, 2, GL_FLOAT, GL_FALSE, 2 * sizeof(float), 0); glEnableVertexAttribArray(location); // unbind(); // needed? } } // MGL
23.65
93
0.710359
MrMCG
08cd1078eabbff7aaf5922dd8add205a48ea0fa8
4,515
cpp
C++
src/test/accounting_tests.cpp
gabriel-eiger/bitcredit
4f8306d98116420e7e80008426006e9fd23ee7db
[ "MIT" ]
1
2015-04-23T04:45:46.000Z
2015-04-23T04:45:46.000Z
src/test/accounting_tests.cpp
gabriel-eiger/bitcredit
4f8306d98116420e7e80008426006e9fd23ee7db
[ "MIT" ]
null
null
null
src/test/accounting_tests.cpp
gabriel-eiger/bitcredit
4f8306d98116420e7e80008426006e9fd23ee7db
[ "MIT" ]
null
null
null
// Copyright (c) 2012-2014 The Bitcoin Core developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "wallet.h" #include "walletdb.h" #include <stdint.h> #include <boost/foreach.hpp> #include <boost/test/unit_test.hpp> #ifdef ENABLE_WALLET extern uint64_t bitcredit_nAccountingEntryNumber; extern Credits_CDBEnv bitcredit_bitdb; #endif extern Credits_CWallet* bitcredit_pwalletMain; BOOST_AUTO_TEST_SUITE(accounting_tests) static void GetResults(Credits_CWalletDB& walletdb, std::map<int64_t, CAccountingEntry>& results) { std::list<CAccountingEntry> aes; results.clear(); BOOST_CHECK(walletdb.ReorderTransactions(bitcredit_pwalletMain) == CREDITS_DB_LOAD_OK); walletdb.ListAccountCreditDebit("", aes); BOOST_FOREACH(CAccountingEntry& ae, aes) { results[ae.nOrderPos] = ae; } } BOOST_AUTO_TEST_CASE(acc_orderupgrade) { Credits_CWalletDB walletdb(bitcredit_pwalletMain->strWalletFile, &bitcredit_bitdb); std::vector<Credits_CWalletTx*> vpwtx; Credits_CWalletTx wtx; CAccountingEntry ae; std::map<int64_t, CAccountingEntry> results; LOCK(bitcredit_pwalletMain->cs_wallet); ae.strAccount = ""; ae.nCreditDebit = 1; ae.nTime = 1333333333; ae.strOtherAccount = "b"; ae.strComment = ""; walletdb.WriteAccountingEntry(ae, bitcredit_nAccountingEntryNumber); wtx.mapValue["comment"] = "z"; bitcredit_pwalletMain->AddToWallet(wtx); vpwtx.push_back(&bitcredit_pwalletMain->mapWallet[wtx.GetHash()]); vpwtx[0]->nTimeReceived = (unsigned int)1333333335; vpwtx[0]->nOrderPos = -1; ae.nTime = 1333333336; ae.strOtherAccount = "c"; walletdb.WriteAccountingEntry(ae, bitcredit_nAccountingEntryNumber); GetResults(walletdb, results); BOOST_CHECK(bitcredit_pwalletMain->nOrderPosNext == 3); BOOST_CHECK(2 == results.size()); BOOST_CHECK(results[0].nTime == 1333333333); BOOST_CHECK(results[0].strComment.empty()); BOOST_CHECK(1 == vpwtx[0]->nOrderPos); BOOST_CHECK(results[2].nTime == 1333333336); BOOST_CHECK(results[2].strOtherAccount == "c"); ae.nTime = 1333333330; ae.strOtherAccount = "d"; ae.nOrderPos = bitcredit_pwalletMain->IncOrderPosNext(); walletdb.WriteAccountingEntry(ae, bitcredit_nAccountingEntryNumber); GetResults(walletdb, results); BOOST_CHECK(results.size() == 3); BOOST_CHECK(bitcredit_pwalletMain->nOrderPosNext == 4); BOOST_CHECK(results[0].nTime == 1333333333); BOOST_CHECK(1 == vpwtx[0]->nOrderPos); BOOST_CHECK(results[2].nTime == 1333333336); BOOST_CHECK(results[3].nTime == 1333333330); BOOST_CHECK(results[3].strComment.empty()); wtx.mapValue["comment"] = "y"; --wtx.nLockTime; // Just to change the hash :) bitcredit_pwalletMain->AddToWallet(wtx); vpwtx.push_back(&bitcredit_pwalletMain->mapWallet[wtx.GetHash()]); vpwtx[1]->nTimeReceived = (unsigned int)1333333336; wtx.mapValue["comment"] = "x"; --wtx.nLockTime; // Just to change the hash :) bitcredit_pwalletMain->AddToWallet(wtx); vpwtx.push_back(&bitcredit_pwalletMain->mapWallet[wtx.GetHash()]); vpwtx[2]->nTimeReceived = (unsigned int)1333333329; vpwtx[2]->nOrderPos = -1; GetResults(walletdb, results); BOOST_CHECK(results.size() == 3); BOOST_CHECK(bitcredit_pwalletMain->nOrderPosNext == 6); BOOST_CHECK(0 == vpwtx[2]->nOrderPos); BOOST_CHECK(results[1].nTime == 1333333333); BOOST_CHECK(2 == vpwtx[0]->nOrderPos); BOOST_CHECK(results[3].nTime == 1333333336); BOOST_CHECK(results[4].nTime == 1333333330); BOOST_CHECK(results[4].strComment.empty()); BOOST_CHECK(5 == vpwtx[1]->nOrderPos); ae.nTime = 1333333334; ae.strOtherAccount = "e"; ae.nOrderPos = -1; walletdb.WriteAccountingEntry(ae, bitcredit_nAccountingEntryNumber); GetResults(walletdb, results); BOOST_CHECK(results.size() == 4); BOOST_CHECK(bitcredit_pwalletMain->nOrderPosNext == 7); BOOST_CHECK(0 == vpwtx[2]->nOrderPos); BOOST_CHECK(results[1].nTime == 1333333333); BOOST_CHECK(2 == vpwtx[0]->nOrderPos); BOOST_CHECK(results[3].nTime == 1333333336); BOOST_CHECK(results[3].strComment.empty()); BOOST_CHECK(results[4].nTime == 1333333330); BOOST_CHECK(results[4].strComment.empty()); BOOST_CHECK(results[5].nTime == 1333333334); BOOST_CHECK(6 == vpwtx[1]->nOrderPos); } BOOST_AUTO_TEST_SUITE_END()
32.956204
91
0.712514
gabriel-eiger
08cea99638e5b48abdbc36e54f88f24ef9a3ddc5
6,202
cpp
C++
src/Alarm/AlarmEntry.cpp
diqiu50/value
019e430ae1da9dc132369ff53b8ab7bcaedd09d7
[ "Apache-2.0" ]
1
2018-04-13T09:41:53.000Z
2018-04-13T09:41:53.000Z
src/Alarm/AlarmEntry.cpp
diqiu50/value
019e430ae1da9dc132369ff53b8ab7bcaedd09d7
[ "Apache-2.0" ]
null
null
null
src/Alarm/AlarmEntry.cpp
diqiu50/value
019e430ae1da9dc132369ff53b8ab7bcaedd09d7
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////// // // Copyright (C) 2005 // Packet Engineering, Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification is not permitted unless authorized in writing by a duly // appointed officer of Packet Engineering, Inc. or its derivatives // // File Name: Alarm.cpp // Description: // // // Modification History: //////////////////////////////////////////////////////////////////////////// #include "Alarm/AlarmEntry.h" #include "Alarm/AlarmMgr.h" #include "AppMgr/App.h" #include "Debug/Debug.h" #include "Porting/ThreadDef.h" #include "Porting/Sleep.h" #include "Util1/Time.h" #include <execinfo.h> OmnAlarmEntry & OmnAlarmEntry::operator << (const OmnEndError) { OmnAlarmMgr::closeEntry(*this); return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const OmnString &errMsg) { mErrMsg += errMsg; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const std::string &errMsg) { mErrMsg += errMsg; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const char *errmsg) { mErrMsg += errmsg; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const u8 *msg) { return *this << (const char *)msg; } OmnAlarmEntry & OmnAlarmEntry::operator << (const int value) { mErrMsg << value; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const u8 value) { mErrMsg << value; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const u32 value) { mErrMsg << value; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const u64 value) { mErrMsg << value; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const int64_t value) { mErrMsg << value; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (const double value) { mErrMsg << value; return *this; } OmnAlarmEntry & OmnAlarmEntry::operator << (void *ptr) { char buf[100]; sprintf(buf, "%ld", (unsigned long)ptr); mErrMsg += buf; return *this; } bool OmnAlarmEntry::toString( const int num_alarms, char *data, const int length) const { if (mErrorId == OmnErrId::eSynErr) { return toString_SynErr(num_alarms, data, length); } return toString_Alarm(num_alarms, data, length); } bool OmnAlarmEntry::toString_Alarm( const int num_alarms, char *data, const int length) const { // // Write the alarm in the following form: // // "\n\n<" // << OmnTime::getSecTick() // << "> ******* Alarm Entry **********" // "\nFile: " << mFile << // "\nLine: " << mLine << // "\nAlarm ID: " << mErrorId << // "\nSeqno: " << mAlarmSeqno << // "\nTrigger Thread ID: " << OmnGetCurrentThreadId() << // "\nTrigger Time: " << mTime << // "\nError Message: " << mErrMsg << // "\n*************************\n"; // // Note that we did not use OmnString in order not to generate any alarms // while converting this entry into a string. // OmnString addrs; if (!OmnAlarmMgr::isPrintFullBacktrace()) { void *buff[100]; int sizes = backtrace(buff, 100); char addrStr[100]; for(int i=0; i<sizes; i++) { sprintf(addrStr, "0x%lx", (u64)buff[i]); if (i == sizes - 1) addrs << addrStr << "\n"; else addrs << addrStr << " "; } } else { void *buff[100]; int sizes = backtrace(buff, 100); std::vector<string> tmps; OmnAlarmMgr::getBacktrace(tmps); if (sizes + 1 != tmps.size() || sizes <= 3) return false; char addrStr[100]; for (size_t i=3; i<tmps.size(); i++) { sprintf(addrStr, "0x%lx", (u64)buff[i-1]); addrs << "[" << (i - 3) << "] " << "[" << addrStr << "] " << tmps[i] << "\n"; } } addrs << "--------------------"; int index = 0; if (!addChar(data, length, index, "\n<")) return false; if (!addInt(data, length, index, OmnTime::getSecTick())) return false; OmnString aa = "> ***** Alarm Entry "; aa << mFile << ":" << mLine << ":" << num_alarms << " ******"; if (!addChar(data, length, index, aa.data())) return false; if (!addChar(data, length, index, "\nError Id: ")) return false; if (!addInt(data, length, index, mErrorId)) return false; if (!addChar(data, length, index, "\nSeqno: ")) return false; if (!addInt(data, length, index, mAlarmSeqno)) return false; if (!addChar(data, length, index, "\nTrigger Time: ")) return false; if (!addChar(data, length, index, mTime.data())) return false; if (!addChar(data, length, index, "\nStackAddr:-----------\n")) return false; if (!addChar(data, length, index, addrs.data())) return false; if (!addChar(data, length, index, "\nError Message: ")) return false; if (!addChar(data, length, index, mErrMsg.data())) return false; if (!addChar(data, length, index, "\n*************************\n")) return false; return true; } bool OmnAlarmEntry::toString_SynErr( const int num_alarms, char *data, const int length) const { // // Write the alarm in the following form: // // "\n\n<" // << OmnTime::getSecTick() // << "> [Syntax Error][File:Line]"<< // "\nTrigger Thread ID: " << OmnGetCurrentThreadId() << // "\nTrigger Time: " << mTime << // "\nError Message: " << mErrMsg << // "\n\n"; // // Note that we did not use OmnString in order not to generate any alarms // while converting this entry into a string. // int index = 0; if (!addChar(data, length, index, "\n\n<")) return false; if (!addInt(data, length, index, OmnTime::getSecTick())) return false; OmnString aa = "> [Syntax Error]["; aa << mFile << ":" << mLine << ":" << num_alarms << "]"; if (!addChar(data, length, index, aa.data())) return false; if (!addChar(data, length, index, "\nThread ID: ")) return false; if (!addIntHex(data, length, index, OmnGetCurrentThreadId())) return false; if (!addChar(data, length, index, "\nTrigger Time: ")) return false; if (!addChar(data, length, index, mTime.data())) return false; if (!addChar(data, length, index, "\nError Message: ")) return false; if (!addChar(data, length, index, mErrMsg.data())) return false; if (!addChar(data, length, index, "\n\n")) return false; return true; }
23.055762
82
0.60158
diqiu50
08d5a67101b5f6c210a2b2213e641905cf404ba9
573
hpp
C++
Chip8lib/font/fontLoader.hpp
tstibro/chip8
fa342b8641737780e20b259f6df9dcb51127786a
[ "MIT" ]
null
null
null
Chip8lib/font/fontLoader.hpp
tstibro/chip8
fa342b8641737780e20b259f6df9dcb51127786a
[ "MIT" ]
null
null
null
Chip8lib/font/fontLoader.hpp
tstibro/chip8
fa342b8641737780e20b259f6df9dcb51127786a
[ "MIT" ]
null
null
null
/* * fontLoader.hpp * * Created on: Jul 23, 2016 * Author: Tomas Stibrany */ #ifndef FONT_FONTLOADER_HPP_ #define FONT_FONTLOADER_HPP_ #include "../chip8Types.hpp" namespace chip8 { namespace core { namespace memory { class RAM; } } } namespace chip8 { namespace font { class Font; } } using namespace chip8::core::memory; using namespace chip8::font; namespace chip8 { namespace font { class FontLoader { private: public: FontLoader(); ~FontLoader(); void LoadTo(RAM *ram, Font *font); }; }} #endif /* FONT_FONTLOADER_HPP_ */
12.191489
36
0.670157
tstibro
08df8e684b33864a1b60ea7bd33b533968ba656f
20,057
ipp
C++
include/External/stlib/packages/cpt/Face3.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/External/stlib/packages/cpt/Face3.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
include/External/stlib/packages/cpt/Face3.ipp
bxl295/m4extreme
2a4a20ebb5b4e971698f7c981de140d31a5e550c
[ "BSD-3-Clause" ]
null
null
null
// -*- C++ -*- #if !defined(__cpt_Face3_ipp__) #error This file is an implementation detail of the class Face. #endif namespace cpt { //! A 3-D face on a b-rep. template<typename T> class Face<3, T> { public: // // Public types. // //! The number type. typedef T Number; //! A Cartesian point. typedef std::tr1::array<Number, 3> Point; //! An indexed edge polyhedron type. typedef geom::IndexedEdgePolyhedron<Number> Polyhedron; private: //! The representation of a plane in 3 dimensions. typedef geom::Plane<Number> Plane; private: // // Member Data // //! The three vertices of the face. std::tr1::array<Point, 3> _vertices; //! The supporting plane of the face. Plane _supportingPlane; /*! The three planes which are incident on the three edges and orthogonal to the face. These planes have inward pointing normals. */ std::tr1::array<Plane, 3> _sides; //! The index of this face. std::size_t _index; //! An epsilon that is appropriate for the edge lengths. Number _epsilon; public: //------------------------------------------------------------------------- //! \name Constructors, etc. //@{ //! Default constructor. Unititialized memory. Face() : _vertices(), _supportingPlane(), _sides(), _index(), _epsilon() {} //! Construct a face from three vertices, a normal and the face index. Face(const Point& vertex1, const Point& vertex2, const Point& vertex3, const Point& normal, const std::size_t index) { make(vertex1, vertex2, vertex3, normal, index); } //! Copy constructor. Face(const Face& other) : _vertices(other._vertices), _supportingPlane(other._supportingPlane), _sides(other._sides), _index(other._index), _epsilon(other._epsilon) {} //! Assignment operator. Face& operator=(const Face& other); //! Make a face from three vertices, a normal and the face index. void make(const Point& vertex1, const Point& vertex2, const Point& vertex3, const Point& normal, const std::size_t index); //! Trivial destructor. ~Face() {} //@} //------------------------------------------------------------------------- //! \name Accessors. //@{ //! Return the vertices. const std::tr1::array<Point, 3>& getVertices() const { return _vertices; } //! Return the face. const Plane& getSupportingPlane() const { return _supportingPlane; } //! Return the sides. const std::tr1::array<Plane, 3>& getSides() const { return _sides; } //! Return the normal to the face. const Point& getNormal() const { return _supportingPlane.getNormal(); } //! Return the i_th side normal. const Point& getSideNormal(const std::size_t i) const { return _sides[i].getNormal(); } //! Return the index of this face in the b-rep. std::size_t getFaceIndex() const { return _index; } //@} //------------------------------------------------------------------------- //! \name Mathematical operations. //@{ //! Return true if the face is valid. bool isValid() const; //! Return the signed distance to the supporting plane of the face. Number computeDistance(const Point& p) const { return _supportingPlane.computeSignedDistance(p); } //! Compute distance with checking. /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeDistanceChecked(const Point& p) const; //! Return the unsigned distance to the supporting plane of the face. Number computeDistanceUnsigned(const Point& p) const { return std::abs(computeDistance(p)); } //! Return the unsigned distance to the face. /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeDistanceUnsignedChecked(const Point& p) const { return std::abs(computeDistanceChecked(p)); } //! Return the distance and find the closest point. Number computeClosestPoint(const Point& p, Point* cp) const { return _supportingPlane.computeSignedDistanceAndClosestPoint(p, cp); } //! Return the distance and find the closest point. /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeClosestPointChecked(const Point& p, Point* cp) const; //! Return the unsigned distance and find the closest point. Number computeClosestPointUnsigned(const Point& p, Point* cp) const { return std::abs(computeClosestPoint(p, cp)); } //! Return the unsigned distance and find the closest point. /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeClosestPointUnsignedChecked(const Point& p, Point* cp) const { return std::abs(computeClosestPointChecked(p, cp)); } //! Return the distance and find the gradient of the distance. Number computeGradient(const Point& p, Point* grad) const; //! Return the distance and find the gradient of the distance. /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeGradientChecked(const Point& p, Point* grad) const; //! Return the unsigned distance and find the gradient of the unsigned distance. Number computeGradientUnsigned(const Point& p, Point* grad) const; //! Return the unsigned distance and find the gradient of the unsigned distance. /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeGradientUnsignedChecked(const Point& p, Point* grad) const; //! Return the distance and find the closest point and gradient of distance Number computeClosestPointAndGradient(const Point& p, Point* cp, Point* grad) const; //! Return the distance and find the closest point and gradient of distance /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeClosestPointAndGradientChecked(const Point& p, Point* cp, Point* grad) const; //! Return the distance and find the closest point and gradient of distance Number computeClosestPointAndGradientUnsigned(const Point& p, Point* cp, Point* grad) const; //! Return the distance and find the closest point and gradient of distance /*! The points that are closest to the face lie in a triangular prizm. If the point, p, is within a distance, delta, of being inside the prizm then return the distance. Otherwise return infinity. */ Number computeClosestPointAndGradientUnsignedChecked(const Point& p, Point* cp, Point* grad) const; //! Make the characteristic polyhedron containing the closest points. /*! The face is a triangle. Consider the larger triangle made by moving the sides outward by delta. Make a triangular prizm of height, 2 * height, with the given triangle at its center. */ void buildCharacteristicPolyhedron(Polyhedron* polyhedron, const Number height) const; //@} private: //! Return true if the point is within delta of being inside the prizm of closest points bool isInside(const Point& p, const Number delta) const { return (_sides[0].computeSignedDistance(p) >= - delta && _sides[1].computeSignedDistance(p) >= - delta && _sides[2].computeSignedDistance(p) >= - delta); } //! Return true if the point is (close to being) inside the prizm of closest points bool isInside(const Point& p) const { return isInside(p, _epsilon); } }; // // Assignment operator. // template<typename T> inline Face<3, T>& Face<3, T>:: operator=(const Face& other) { // Avoid assignment to self if (&other != this) { _vertices = other._vertices; _supportingPlane = other._supportingPlane; _sides = other._sides; _index = other._index; _epsilon = other._epsilon; } // Return *this so assignments can chain return *this; } // // Make. // template<typename T> inline void Face<3, T>:: make(const Point& a, const Point& b, const Point& c, const Point& nm, const std::size_t index) { // The three vertices comprising the face. _vertices[0] = a; _vertices[1] = b; _vertices[2] = c; // Make the face plane from a point and the normal. _supportingPlane = Plane(a, nm); // Make the sides of the prizm from three points each. _sides[0] = Plane(b, a, a + _supportingPlane.getNormal()); _sides[1] = Plane(c, b, b + _supportingPlane.getNormal()); _sides[2] = Plane(a, c, c + _supportingPlane.getNormal()); // The index of this face. _index = index; // An appropriate epsilon for this face. max_length * sqrt(eps) _epsilon = std::sqrt(ads::max(squaredDistance(a, b), squaredDistance(b, c), squaredDistance(c, a)) * std::numeric_limits<Number>::epsilon()); } // // Mathematical Operations // template<typename T> inline bool Face<3, T>:: isValid() const { // Check the plane of the face. if (! _supportingPlane.isValid()) { return false; } // Check the planes of the sides. for (std::size_t i = 0; i < 3; ++i) { if (! _sides[i].isValid()) { return false; } } // Check that the normal points in the correct direction. const Number eps = 10 * std::numeric_limits<Number>::epsilon(); if (std::abs(dot(_supportingPlane.getNormal(), _vertices[0] - _vertices[1])) > eps || std::abs(dot(_supportingPlane.getNormal(), _vertices[1] - _vertices[2])) > eps || std::abs(dot(_supportingPlane.getNormal(), _vertices[2] - _vertices[0])) > eps) { return false; } // Check that the side normals point in the correct direction. if (std::abs(dot(_supportingPlane.getNormal(), _sides[0].getNormal())) > eps || std::abs(dot(_supportingPlane.getNormal(), _sides[1].getNormal())) > eps || std::abs(dot(_supportingPlane.getNormal(), _sides[2].getNormal())) > eps) { return false; } if (std::abs(dot(_sides[0].getNormal(), _vertices[0] - _vertices[1])) > eps || std::abs(dot(_sides[1].getNormal(), _vertices[1] - _vertices[2])) > eps || std::abs(dot(_sides[2].getNormal(), _vertices[2] - _vertices[0])) > eps) { return false; } return true; } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeDistanceChecked(const Point& p) const { // If the point is inside the characteristic prizm. if (isInside(p)) { // Then compute the distance. return computeDistance(p); } // Otherwise, return infinity. return std::numeric_limits<Number>::max(); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeClosestPointChecked(const Point& p, Point* cp) const { // If the point is inside the characteristic prizm. if (isInside(p)) { // Then compute the distance and closest point to the supporting plane // of the face. return computeClosestPoint(p, cp); } // Otherwise, return infinity. return std::numeric_limits<Number>::max(); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeGradient(const Point& p, Point* grad) const { *grad = getNormal(); return _supportingPlane.computeSignedDistance(p); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeGradientChecked(const Point& p, Point* grad) const { // If the point is inside the characteristic prizm. if (isInside(p)) { // Then compute the distance and gradient. return computeGradient(p, grad); } // Otherwise, return infinity. return std::numeric_limits<Number>::max(); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeGradientUnsigned(const Point& p, Point* grad) const { const Number signedDistance = _supportingPlane.computeSignedDistance(p); *grad = getNormal(); if (signedDistance < 0) { negateElements(grad); } return std::abs(signedDistance); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeGradientUnsignedChecked(const Point& p, Point* grad) const { // If the point is inside the characteristic prizm. if (isInside(p)) { // Then compute the distance and gradient. return computeGradientUnsigned(p, grad); } // Otherwise, return infinity. return std::numeric_limits<Number>::max(); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeClosestPointAndGradient(const Point& p, Point* cp, Point* grad) const { *grad = getNormal(); return _supportingPlane.computeSignedDistanceAndClosestPoint(p, cp); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeClosestPointAndGradientChecked(const Point& p, Point* cp, Point* grad) const { // If the point is inside the characteristic prizm. if (isInside(p)) { // Then compute the distance, closest point, and gradient. return computeClosestPointAndGradient(p, cp, grad); } // Otherwise, return infinity. return std::numeric_limits<Number>::max(); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeClosestPointAndGradientUnsigned(const Point& p, Point* cp, Point* grad) const { Number signedDistance = _supportingPlane.computeSignedDistanceAndClosestPoint(p, cp); *grad = getNormal(); if (signedDistance < 0) { negateElements(grad); } return std::abs(signedDistance); } template<typename T> inline typename Face<3, T>::Number Face<3, T>:: computeClosestPointAndGradientUnsignedChecked(const Point& p, Point* cp, Point* grad) const { // If the point is inside the characteristic prizm. if (isInside(p)) { // Then compute the distance, closest point, and gradient. return computeClosestPointAndGradientUnsigned(p, cp, grad); } // Otherwise, return infinity. return std::numeric_limits<Number>::max(); } // Utility Function. // Offset of a point so that the sides with normals n1 and n2 are moved // a distance of delta. template<typename T> std::tr1::array<T, 3> offsetOutward(const std::tr1::array<T, 3>& n1, const std::tr1::array<T, 3>& n2, const T delta) { std::tr1::array<T, 3> outward(n1 + n2); normalize(&outward); T den = dot(outward, n1); if (den != 0) { return (outward *(delta / den)); } return ext::make_array<T>(0, 0, 0); } /* The face is a triangle. Consider the larger triangle made by moving the sides outward by delta. Make a triangular prizm of height, 2 * height, with the given triangle at its center. */ template<typename T> inline void Face<3, T>:: buildCharacteristicPolyhedron(Polyhedron* polyhedron, const Number height) const { polyhedron->clear(); // The initial triangular face. Points on the bottom of the prizm. Point heightOffset = height * getNormal(); Point bot0(getVertices()[0]); bot0 -= heightOffset; Point bot1(getVertices()[1]); bot1 -= heightOffset; Point bot2(getVertices()[2]); bot2 -= heightOffset; // Compute the amount (delta) to enlarge the triangle. Number maximumCoordinate = 1.0; // Loop over the three vertices. for (std::size_t i = 0; i != 3; ++i) { // Loop over the space coordinates. for (std::size_t j = 0; j != 3; ++j) { maximumCoordinate = std::max(maximumCoordinate, std::abs(getVertices()[i][j])); } } // Below, 10 is the fudge factor. const Number delta = maximumCoordinate * 10.0 * std::numeric_limits<Number>::epsilon(); // Enlarge the triangle. Point out0(getSideNormal(0)); negateElements(&out0); Point out1(getSideNormal(1)); negateElements(&out1); Point out2(getSideNormal(2)); negateElements(&out2); bot0 += offsetOutward(out0, out2, delta); bot1 += offsetOutward(out1, out0, delta); bot2 += offsetOutward(out2, out1, delta); // Make the top of the prizm. heightOffset = 2 * height * getNormal(); Point top0(bot0 + heightOffset); Point top1(bot1 + heightOffset); Point top2(bot2 + heightOffset); // Add the vertices of the triangular prizm. polyhedron->insertVertex(bot0); // 0 polyhedron->insertVertex(bot1); // 1 polyhedron->insertVertex(bot2); // 2 polyhedron->insertVertex(top0); // 3 polyhedron->insertVertex(top1); // 4 polyhedron->insertVertex(top2); // 5 // Add the edges of the triangular prizm. polyhedron->insertEdge(0, 1); polyhedron->insertEdge(1, 2); polyhedron->insertEdge(2, 0); polyhedron->insertEdge(3, 4); polyhedron->insertEdge(4, 5); polyhedron->insertEdge(5, 3); polyhedron->insertEdge(0, 3); polyhedron->insertEdge(1, 4); polyhedron->insertEdge(2, 5); } // // Equality / Inequality // template<typename T> inline bool operator==(const Face<3, T>& f1, const Face<3, T>& f2) { if (f1.getVertices()[0] == f2.getVertices()[0] && f1.getVertices()[1] == f2.getVertices()[1] && f1.getVertices()[2] == f2.getVertices()[2] && f1.getSupportingPlane() == f2.getSupportingPlane() && f1.getSides()[0] == f2.getSides()[0] && f1.getSides()[1] == f2.getSides()[1] && f1.getSides()[2] == f2.getSides()[2] && f1.getFaceIndex() == f2.getFaceIndex()) { return true; } return false; } // // File I/O // template<typename T> inline std::ostream& operator<<(std::ostream& out, const Face<3, T>& face) { out << "Vertices:" << '\n' << face.getVertices() << '\n' << "Supporting Plane:" << '\n' << face.getSupportingPlane() << '\n' << "Sides:" << '\n' << face.getSides() << '\n' << "Face index:" << '\n' << face.getFaceIndex() << '\n'; return out; } } // namespace cpt
28.490057
92
0.610311
bxl295
08e08cd072855ce935cf1840a2215b955421a32e
953
hpp
C++
color_detector/leds.hpp
Merryashji/TI-Individual-Propedeuse-Assessment
a9fccff323a4a667811c9917ef7d1b5c1237e478
[ "BSL-1.0" ]
null
null
null
color_detector/leds.hpp
Merryashji/TI-Individual-Propedeuse-Assessment
a9fccff323a4a667811c9917ef7d1b5c1237e478
[ "BSL-1.0" ]
null
null
null
color_detector/leds.hpp
Merryashji/TI-Individual-Propedeuse-Assessment
a9fccff323a4a667811c9917ef7d1b5c1237e478
[ "BSL-1.0" ]
null
null
null
#ifndef LEDS_HPP #define LEDS_HPP #include "hwlib.hpp" /// @file /// \brief /// leds class /// \details /// This is a class for color for 5 leds. class leds{ private: hwlib::pin_out & l1; hwlib::pin_out & l2; hwlib::pin_out & l3; hwlib::pin_out & l4; hwlib::pin_out & l5; /// \brief /// class public /// \details /// the public part contains the constructor of the leds color and the member functions. public: leds( hwlib::pin_out & l1 , hwlib::pin_out & l2 , hwlib::pin_out & l3 , hwlib::pin_out & l4 , hwlib::pin_out & l5): l1(l1), l2(l2) , l3(l3) , l4(l4) , l5(l5){} /// \brief /// show_color /// \details /// this function has a char parameter. According to this values the function turns the actual color led on. void show_color(char color ); /// \brief /// reset /// \details /// this function turns all the leds off. void reset(); }; #endif
20.276596
112
0.593914
Merryashji
08e1655a6ea40ca41ee8bd4ca653e5c30640d026
1,274
cpp
C++
src/math/tests/test_libaeon_math/test_size2d.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
7
2017-02-19T16:22:16.000Z
2021-03-02T05:47:39.000Z
src/math/tests/test_libaeon_math/test_size2d.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
61
2017-05-29T06:11:17.000Z
2021-03-28T21:51:44.000Z
src/math/tests/test_libaeon_math/test_size2d.cpp
aeon-engine/libaeon
e42b39e621dcd0a0fba05e1c166fc688288fb69b
[ "BSD-2-Clause" ]
2
2017-05-28T17:17:40.000Z
2017-07-14T21:45:16.000Z
// Distributed under the BSD 2-Clause License - Copyright 2012-2021 Robin Degen #include <aeon/math/size2d.h> #include <aeon/math/size2d_stream.h> #include <gtest/gtest.h> using namespace aeon; TEST(test_size2d, test_size2d_default_int) { [[maybe_unused]] math::size2d<int> size; } struct external_size2d { int width{}; int height{}; }; TEST(test_size2d, test_size2d_convert_from_unknown) { const external_size2d s{10, 20}; math::size2d<int> size{s}; EXPECT_EQ(size.width, 10); EXPECT_EQ(size.height, 20); const auto s2 = size.convert_to<external_size2d>(); EXPECT_EQ(s2.width, 10); EXPECT_EQ(s2.height, 20); } TEST(test_size2d, test_size2d_clamp) { const math::size2d min{5, 10}; const math::size2d max{50, 100}; EXPECT_EQ(math::clamp(math::size2d{10, 20}, min, max), (math::size2d{10, 20})); EXPECT_EQ(math::clamp(math::size2d{40, 90}, min, max), (math::size2d{40, 90})); EXPECT_EQ(math::clamp(math::size2d{4, 20}, min, max), (math::size2d{5, 20})); EXPECT_EQ(math::clamp(math::size2d{5, 9}, min, max), (math::size2d{5, 10})); EXPECT_EQ(math::clamp(math::size2d{51, 90}, min, max), (math::size2d{50, 90})); EXPECT_EQ(math::clamp(math::size2d{50, 110}, min, max), (math::size2d{50, 100})); }
28.311111
85
0.66562
aeon-engine
08e4d6f55664305d11c4b22861efc87b3e154840
259
cpp
C++
tests/main.cpp
RotartsiORG/StoneMason
0f6efefad68b29e7e82524e705ce47606ba53665
[ "Apache-2.0" ]
1
2021-10-02T19:31:14.000Z
2021-10-02T19:31:14.000Z
tests/main.cpp
RotartsiORG/StoneMason
0f6efefad68b29e7e82524e705ce47606ba53665
[ "Apache-2.0" ]
1
2020-06-17T01:15:45.000Z
2020-06-17T01:16:08.000Z
tests/main.cpp
RotartsiORG/StoneMason
0f6efefad68b29e7e82524e705ce47606ba53665
[ "Apache-2.0" ]
1
2020-10-17T23:57:27.000Z
2020-10-17T23:57:27.000Z
// // Created by grant on 1/2/20. // #include "gtest/gtest.h" #include "stms/log_test.cpp" #include "stms/async_test.cpp" #include "stms/general.cpp" #if STMS_SSL_TESTS_ENABLED // Toggle SSL tests, disable for travis # include "stms/ssl_test.cpp" #endif
19.923077
67
0.718147
RotartsiORG
08e7bc9d26d1bca865b1ba8f1f8b54a2852db55e
336
hpp
C++
etl/utils/singleton.hpp
julienlopez/ETL
51c6e2c425d1bec29507a4f9a89c6211c9d7488f
[ "MIT" ]
null
null
null
etl/utils/singleton.hpp
julienlopez/ETL
51c6e2c425d1bec29507a4f9a89c6211c9d7488f
[ "MIT" ]
1
2015-03-25T09:42:10.000Z
2015-03-25T09:42:10.000Z
etl/utils/singleton.hpp
julienlopez/ETL
51c6e2c425d1bec29507a4f9a89c6211c9d7488f
[ "MIT" ]
null
null
null
#ifndef __SINGLETON_HPP__ #define __SINGLETON_HPP__ #include "noncopyable.hpp" namespace etl { namespace utils { template<class T> class singleton : public noncopyable { public: static T& instance() { static T i; return i; } protected: singleton() {} }; } //utils } //etl #endif // __SINGLETON_HPP__
12.923077
56
0.660714
julienlopez
08e8850381bddd9d41475a7b1eabc6b9dcaeb4b9
1,524
cpp
C++
ProjetGraph/ProjetGraph/tests/CUnit.cpp
RakSrinaNa/DI3---Projet-CPP
e5742941032f6a30f84868039b81b647fcf41cb5
[ "MIT" ]
null
null
null
ProjetGraph/ProjetGraph/tests/CUnit.cpp
RakSrinaNa/DI3---Projet-CPP
e5742941032f6a30f84868039b81b647fcf41cb5
[ "MIT" ]
null
null
null
ProjetGraph/ProjetGraph/tests/CUnit.cpp
RakSrinaNa/DI3---Projet-CPP
e5742941032f6a30f84868039b81b647fcf41cb5
[ "MIT" ]
null
null
null
#include <iostream> #include "CUnit.h" #include "CExceptionUnit.h" #include "CArcUnit.h" #include "CVertexUnit.h" #include "CGraphUnit.h" #include "CGraphParserUnit.h" #include "CHashMapUnit.h" #include "../CException.h" #include "CGraphToolboxUnit.h" void CUnit::UNITassertError(const char * pcMessage) { perror(pcMessage); perror("\n"); #ifdef _MSC_VER throw CException(0, (char *) "BREAKPOINT UNIT TESTS"); #else raise(SIGINT); #endif exit(EXIT_FAILURE); } void CUnit::UNITlaunchTests() { std::cout << "Starting CException tests..." << std::endl; CExceptionUnit::EXUnitTests(); std::cout << "CException OK" << std::endl << std::endl; std::cout << "Starting CHashMap tests..." << std::endl; CHashMapUnit::HMPUnitTest(); std::cout << "CHashMap OK" << std::endl << std::endl; std::cout << "Starting CArc tests..." << std::endl; CArcUnit::ARCUnitTests(); std::cout << "CArc OK" << std::endl << std::endl; std::cout << "Starting CVertex tests..." << std::endl; CVertexUnit::VERUnitTest(); std::cout << "CVertex OK" << std::endl << std::endl; std::cout << "Starting CGraphParser tests..." << std::endl; CGraphParserUnit::PGRAUnitTests(); std::cout << "CGraphParser OK" << std::endl << std::endl; std::cout << "Starting CGraph tests..." << std::endl; CGraphUnit::GRAUnitTests(); std::cout << "CGraph OK" << std::endl << std::endl; std::cout << "Starting CGraphToolbox tests..." << std::endl; CGraphToolboxUnit::GRTUnitTests(); std::cout << "CGraphToolbox OK" << std::endl << std::endl; }
28.222222
61
0.660105
RakSrinaNa
08f4420ae9b237e53d192e28ad209aaae3a6384b
2,524
cpp
C++
framework/L2DMatrix44.cpp
dragonflylee/Dango
3243a3ade6d8a4391b1d78c8bc4bb210779022cb
[ "MIT" ]
1
2018-01-09T02:43:57.000Z
2018-01-09T02:43:57.000Z
framework/L2DMatrix44.cpp
dragonflylee/Dango
3243a3ade6d8a4391b1d78c8bc4bb210779022cb
[ "MIT" ]
null
null
null
framework/L2DMatrix44.cpp
dragonflylee/Dango
3243a3ade6d8a4391b1d78c8bc4bb210779022cb
[ "MIT" ]
null
null
null
/** * * You can modify and use this source freely * only for the development of application related Live2D. * * (c) Live2D Inc. All rights reserved. */ #include "L2DMatrix44.h" namespace live2d { namespace framework { L2DMatrix44::L2DMatrix44() { identity(); } // 単位行列に初期化 void L2DMatrix44::identity(){ for (int i = 0; i < 16; i++) tr[i] = ((i % 5) == 0) ? 1.0f : 0.0f; } void L2DMatrix44::mul(float* a, float* b, float* dst) { float c[16] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; int n = 4; int i, j, k; // 受け取った2つの行列の掛け算を行う。 for (i = 0; i < n; i++) { for (j = 0; j < n; j++) { for (k = 0; k < n; k++) { //c[i*4+j]+=a[i*4+k]*b[k*4+j]; c[i + j * 4] += a[i + k * 4] * b[k + j * 4]; } } } for (i = 0; i < 16; i++) { dst[i] = c[i]; } } void L2DMatrix44::multTranslate(float x, float y) { float tr1[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, 0, 1 }; mul(tr1, tr, tr); } void L2DMatrix44::translate(float x, float y) { tr[12] = x; tr[13] = y; } void L2DMatrix44::multScale(float scaleX, float scaleY) { float tr1[16] = { scaleX, 0, 0, 0, 0, scaleY, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1 }; mul(tr1, tr, tr); } void L2DMatrix44::scale(float scaleX, float scaleY) { tr[0] = scaleX; tr[5] = scaleY; } float L2DMatrix44::transformX(float src) { return tr[0] * src + tr[12]; } float L2DMatrix44::invertTransformX(float src) { return (src - tr[12]) / tr[0]; } float L2DMatrix44::transformY(float src) { return tr[5] * src + tr[13]; } float L2DMatrix44::invertTransformY(float src) { return (src - tr[13]) / tr[5]; } void L2DMatrix44::setMatrix(float* _tr) { for (int i = 0; i < 16; i++) tr[i] = _tr[i]; } void L2DMatrix44::append(L2DMatrix44* m) { mul(m->getArray(), tr, tr); } } }
22.336283
89
0.389857
dragonflylee
08f7b1a7196f0b681692d1bb2cbe0f9b9bb590ab
1,926
cpp
C++
test/unit_tests/tests/18_FFT_revtests.cpp
bacchus/bacchuslib
35c41b6a7244227c0779c99b3c2f98b9a8349477
[ "MIT" ]
null
null
null
test/unit_tests/tests/18_FFT_revtests.cpp
bacchus/bacchuslib
35c41b6a7244227c0779c99b3c2f98b9a8349477
[ "MIT" ]
null
null
null
test/unit_tests/tests/18_FFT_revtests.cpp
bacchus/bacchuslib
35c41b6a7244227c0779c99b3c2f98b9a8349477
[ "MIT" ]
null
null
null
#include "setting.h" #include "math/fft.h" #include "utils/logger.h" #include "audio/audio_tools.h" using namespace bacchus; const float tol18 = 1e-4f; const int ulpDif = 256*1024; void FftCrossTest(const matxf& x, const matxcx& resy) { matxcx y = DFT(x); int n = y.size(); EXPECT_EQ(resy.size(), n); for (int i = 0; i < n; ++i) { EXPECT_LE(ulp_difference(resy[i].real(),y[i].real(), tol18), i); EXPECT_LE(ulp_difference(resy[i].imag(),y[i].imag(), tol18), i); } matxcx y1 = fft(x); int n1 = y1.size(); EXPECT_EQ(resy.size(), n1); for (int i = 0; i < n1; ++i) { EXPECT_LE(ulp_difference(resy[i].real(),y1[i].real(), tol18), i); EXPECT_LE(ulp_difference(resy[i].imag(),y1[i].imag(), tol18), i); } } void FftCrossTest(const matxf& x) { matxcx resy = DFT(x); matxcx y1 = fft(x); //PRINT(resy); //PRINT(y1); // int bd = x.size() > 1000 ? 948 : 0; // EXPECT_FLOAT_EQ(resy[bd].real(),y1[bd].real()); int n1 = y1.size(); EXPECT_EQ(resy.size(), n1); for (int i = 0; i < n1; ++i) { EXPECT_LE(ulp_difference(resy[i].real(),y1[i].real(), tol18), i); EXPECT_LE(ulp_difference(resy[i].imag(),y1[i].imag(), tol18), i); } } TEST(FFT2, CrossTest) { matxf x = {1,2,3,4}; matxcx resy = {cplx{10,0}, cplx{-2,2}, cplx{-2,0}, cplx{-2,-2}}; FftCrossTest(x,resy); } TEST(FFT2, DftNoRes) { matxf x = {1,2,3,4}; FftCrossTest(x); } TEST(FFT2, Sine) { int fs = 1024*100; int f1 = 100; matxcx x1 = genSine(1,f1,0,fs,1024); matxcx y = fft(x1); //PRINT(y); matxcx res = fftrev(y); int n1 = x1.size(); EXPECT_EQ(res.size(), n1); for (int i = 0; i < n1; ++i) { EXPECT_LE(ulp_difference(res[i].real(),x1[i].real(), tol18), i); EXPECT_LE(ulp_difference(res[i].imag(),x1[i].imag(), tol18), i); } //FftCrossTest(x1); //FftCrossTest(x2); }
25.342105
73
0.558152
bacchus
08fcbe77618e5dfaad7de00fe7b983a15598ca9f
25,842
cc
C++
src/mavsdk_server/src/generated/gimbal/gimbal.grpc.pb.cc
fpersson/MAVSDK
a7161d7634cd04de97f7fbcea10c2da21136892c
[ "BSD-3-Clause" ]
1
2020-03-30T07:53:19.000Z
2020-03-30T07:53:19.000Z
src/mavsdk_server/src/generated/gimbal/gimbal.grpc.pb.cc
fpersson/MAVSDK
a7161d7634cd04de97f7fbcea10c2da21136892c
[ "BSD-3-Clause" ]
1
2021-03-15T18:34:13.000Z
2021-03-15T18:34:13.000Z
src/mavsdk_server/src/generated/gimbal/gimbal.grpc.pb.cc
SEESAI/MAVSDK
5a9289eb09eb6b13f24e9d8d69f5644d2210d6b2
[ "BSD-3-Clause" ]
null
null
null
// Generated by the gRPC C++ plugin. // If you make any local change, they will be lost. // source: gimbal/gimbal.proto #include "gimbal/gimbal.pb.h" #include "gimbal/gimbal.grpc.pb.h" #include <functional> #include <grpcpp/impl/codegen/async_stream.h> #include <grpcpp/impl/codegen/async_unary_call.h> #include <grpcpp/impl/codegen/channel_interface.h> #include <grpcpp/impl/codegen/client_unary_call.h> #include <grpcpp/impl/codegen/client_callback.h> #include <grpcpp/impl/codegen/message_allocator.h> #include <grpcpp/impl/codegen/method_handler.h> #include <grpcpp/impl/codegen/rpc_service_method.h> #include <grpcpp/impl/codegen/server_callback.h> #include <grpcpp/impl/codegen/server_callback_handlers.h> #include <grpcpp/impl/codegen/server_context.h> #include <grpcpp/impl/codegen/service_type.h> #include <grpcpp/impl/codegen/sync_stream.h> namespace mavsdk { namespace rpc { namespace gimbal { static const char* GimbalService_method_names[] = { "/mavsdk.rpc.gimbal.GimbalService/SetPitchAndYaw", "/mavsdk.rpc.gimbal.GimbalService/SetPitchRateAndYawRate", "/mavsdk.rpc.gimbal.GimbalService/SetMode", "/mavsdk.rpc.gimbal.GimbalService/SetRoiLocation", "/mavsdk.rpc.gimbal.GimbalService/TakeControl", "/mavsdk.rpc.gimbal.GimbalService/ReleaseControl", "/mavsdk.rpc.gimbal.GimbalService/SubscribeControl", }; std::unique_ptr< GimbalService::Stub> GimbalService::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options) { (void)options; std::unique_ptr< GimbalService::Stub> stub(new GimbalService::Stub(channel)); return stub; } GimbalService::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) : channel_(channel), rpcmethod_SetPitchAndYaw_(GimbalService_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_SetPitchRateAndYawRate_(GimbalService_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_SetMode_(GimbalService_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_SetRoiLocation_(GimbalService_method_names[3], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_TakeControl_(GimbalService_method_names[4], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_ReleaseControl_(GimbalService_method_names[5], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) , rpcmethod_SubscribeControl_(GimbalService_method_names[6], ::grpc::internal::RpcMethod::SERVER_STREAMING, channel) {} ::grpc::Status GimbalService::Stub::SetPitchAndYaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest& request, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::SetPitchAndYawRequest, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_SetPitchAndYaw_, context, request, response); } void GimbalService::Stub::experimental_async::SetPitchAndYaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest* request, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::SetPitchAndYawRequest, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetPitchAndYaw_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::SetPitchAndYaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest* request, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetPitchAndYaw_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetPitchAndYawResponse>* GimbalService::Stub::PrepareAsyncSetPitchAndYawRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::SetPitchAndYawResponse, ::mavsdk::rpc::gimbal::SetPitchAndYawRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_SetPitchAndYaw_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetPitchAndYawResponse>* GimbalService::Stub::AsyncSetPitchAndYawRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncSetPitchAndYawRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status GimbalService::Stub::SetPitchRateAndYawRate(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest& request, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_SetPitchRateAndYawRate_, context, request, response); } void GimbalService::Stub::experimental_async::SetPitchRateAndYawRate(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest* request, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetPitchRateAndYawRate_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::SetPitchRateAndYawRate(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest* request, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetPitchRateAndYawRate_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse>* GimbalService::Stub::PrepareAsyncSetPitchRateAndYawRateRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_SetPitchRateAndYawRate_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse>* GimbalService::Stub::AsyncSetPitchRateAndYawRateRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncSetPitchRateAndYawRateRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status GimbalService::Stub::SetMode(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest& request, ::mavsdk::rpc::gimbal::SetModeResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::SetModeRequest, ::mavsdk::rpc::gimbal::SetModeResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_SetMode_, context, request, response); } void GimbalService::Stub::experimental_async::SetMode(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest* request, ::mavsdk::rpc::gimbal::SetModeResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::SetModeRequest, ::mavsdk::rpc::gimbal::SetModeResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetMode_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::SetMode(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest* request, ::mavsdk::rpc::gimbal::SetModeResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetMode_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetModeResponse>* GimbalService::Stub::PrepareAsyncSetModeRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::SetModeResponse, ::mavsdk::rpc::gimbal::SetModeRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_SetMode_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetModeResponse>* GimbalService::Stub::AsyncSetModeRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncSetModeRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status GimbalService::Stub::SetRoiLocation(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest& request, ::mavsdk::rpc::gimbal::SetRoiLocationResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::SetRoiLocationRequest, ::mavsdk::rpc::gimbal::SetRoiLocationResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_SetRoiLocation_, context, request, response); } void GimbalService::Stub::experimental_async::SetRoiLocation(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest* request, ::mavsdk::rpc::gimbal::SetRoiLocationResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::SetRoiLocationRequest, ::mavsdk::rpc::gimbal::SetRoiLocationResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetRoiLocation_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::SetRoiLocation(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest* request, ::mavsdk::rpc::gimbal::SetRoiLocationResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_SetRoiLocation_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetRoiLocationResponse>* GimbalService::Stub::PrepareAsyncSetRoiLocationRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::SetRoiLocationResponse, ::mavsdk::rpc::gimbal::SetRoiLocationRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_SetRoiLocation_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::SetRoiLocationResponse>* GimbalService::Stub::AsyncSetRoiLocationRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncSetRoiLocationRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status GimbalService::Stub::TakeControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest& request, ::mavsdk::rpc::gimbal::TakeControlResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::TakeControlRequest, ::mavsdk::rpc::gimbal::TakeControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_TakeControl_, context, request, response); } void GimbalService::Stub::experimental_async::TakeControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest* request, ::mavsdk::rpc::gimbal::TakeControlResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::TakeControlRequest, ::mavsdk::rpc::gimbal::TakeControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_TakeControl_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::TakeControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest* request, ::mavsdk::rpc::gimbal::TakeControlResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_TakeControl_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::TakeControlResponse>* GimbalService::Stub::PrepareAsyncTakeControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::TakeControlResponse, ::mavsdk::rpc::gimbal::TakeControlRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_TakeControl_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::TakeControlResponse>* GimbalService::Stub::AsyncTakeControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncTakeControlRaw(context, request, cq); result->StartCall(); return result; } ::grpc::Status GimbalService::Stub::ReleaseControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest& request, ::mavsdk::rpc::gimbal::ReleaseControlResponse* response) { return ::grpc::internal::BlockingUnaryCall< ::mavsdk::rpc::gimbal::ReleaseControlRequest, ::mavsdk::rpc::gimbal::ReleaseControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), rpcmethod_ReleaseControl_, context, request, response); } void GimbalService::Stub::experimental_async::ReleaseControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest* request, ::mavsdk::rpc::gimbal::ReleaseControlResponse* response, std::function<void(::grpc::Status)> f) { ::grpc::internal::CallbackUnaryCall< ::mavsdk::rpc::gimbal::ReleaseControlRequest, ::mavsdk::rpc::gimbal::ReleaseControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_ReleaseControl_, context, request, response, std::move(f)); } void GimbalService::Stub::experimental_async::ReleaseControl(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest* request, ::mavsdk::rpc::gimbal::ReleaseControlResponse* response, ::grpc::experimental::ClientUnaryReactor* reactor) { ::grpc::internal::ClientCallbackUnaryFactory::Create< ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(stub_->channel_.get(), stub_->rpcmethod_ReleaseControl_, context, request, response, reactor); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::ReleaseControlResponse>* GimbalService::Stub::PrepareAsyncReleaseControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncResponseReaderHelper::Create< ::mavsdk::rpc::gimbal::ReleaseControlResponse, ::mavsdk::rpc::gimbal::ReleaseControlRequest, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>(channel_.get(), cq, rpcmethod_ReleaseControl_, context, request); } ::grpc::ClientAsyncResponseReader< ::mavsdk::rpc::gimbal::ReleaseControlResponse>* GimbalService::Stub::AsyncReleaseControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest& request, ::grpc::CompletionQueue* cq) { auto* result = this->PrepareAsyncReleaseControlRaw(context, request, cq); result->StartCall(); return result; } ::grpc::ClientReader< ::mavsdk::rpc::gimbal::ControlResponse>* GimbalService::Stub::SubscribeControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SubscribeControlRequest& request) { return ::grpc::internal::ClientReaderFactory< ::mavsdk::rpc::gimbal::ControlResponse>::Create(channel_.get(), rpcmethod_SubscribeControl_, context, request); } void GimbalService::Stub::experimental_async::SubscribeControl(::grpc::ClientContext* context, ::mavsdk::rpc::gimbal::SubscribeControlRequest* request, ::grpc::experimental::ClientReadReactor< ::mavsdk::rpc::gimbal::ControlResponse>* reactor) { ::grpc::internal::ClientCallbackReaderFactory< ::mavsdk::rpc::gimbal::ControlResponse>::Create(stub_->channel_.get(), stub_->rpcmethod_SubscribeControl_, context, request, reactor); } ::grpc::ClientAsyncReader< ::mavsdk::rpc::gimbal::ControlResponse>* GimbalService::Stub::AsyncSubscribeControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SubscribeControlRequest& request, ::grpc::CompletionQueue* cq, void* tag) { return ::grpc::internal::ClientAsyncReaderFactory< ::mavsdk::rpc::gimbal::ControlResponse>::Create(channel_.get(), cq, rpcmethod_SubscribeControl_, context, request, true, tag); } ::grpc::ClientAsyncReader< ::mavsdk::rpc::gimbal::ControlResponse>* GimbalService::Stub::PrepareAsyncSubscribeControlRaw(::grpc::ClientContext* context, const ::mavsdk::rpc::gimbal::SubscribeControlRequest& request, ::grpc::CompletionQueue* cq) { return ::grpc::internal::ClientAsyncReaderFactory< ::mavsdk::rpc::gimbal::ControlResponse>::Create(channel_.get(), cq, rpcmethod_SubscribeControl_, context, request, false, nullptr); } GimbalService::Service::Service() { AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::SetPitchAndYawRequest, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest* req, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse* resp) { return service->SetPitchAndYaw(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[1], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest* req, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse* resp) { return service->SetPitchRateAndYawRate(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[2], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::SetModeRequest, ::mavsdk::rpc::gimbal::SetModeResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::SetModeRequest* req, ::mavsdk::rpc::gimbal::SetModeResponse* resp) { return service->SetMode(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[3], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::SetRoiLocationRequest, ::mavsdk::rpc::gimbal::SetRoiLocationResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest* req, ::mavsdk::rpc::gimbal::SetRoiLocationResponse* resp) { return service->SetRoiLocation(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[4], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::TakeControlRequest, ::mavsdk::rpc::gimbal::TakeControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::TakeControlRequest* req, ::mavsdk::rpc::gimbal::TakeControlResponse* resp) { return service->TakeControl(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[5], ::grpc::internal::RpcMethod::NORMAL_RPC, new ::grpc::internal::RpcMethodHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::ReleaseControlRequest, ::mavsdk::rpc::gimbal::ReleaseControlResponse, ::grpc::protobuf::MessageLite, ::grpc::protobuf::MessageLite>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::ReleaseControlRequest* req, ::mavsdk::rpc::gimbal::ReleaseControlResponse* resp) { return service->ReleaseControl(ctx, req, resp); }, this))); AddMethod(new ::grpc::internal::RpcServiceMethod( GimbalService_method_names[6], ::grpc::internal::RpcMethod::SERVER_STREAMING, new ::grpc::internal::ServerStreamingHandler< GimbalService::Service, ::mavsdk::rpc::gimbal::SubscribeControlRequest, ::mavsdk::rpc::gimbal::ControlResponse>( [](GimbalService::Service* service, ::grpc::ServerContext* ctx, const ::mavsdk::rpc::gimbal::SubscribeControlRequest* req, ::grpc::ServerWriter<::mavsdk::rpc::gimbal::ControlResponse>* writer) { return service->SubscribeControl(ctx, req, writer); }, this))); } GimbalService::Service::~Service() { } ::grpc::Status GimbalService::Service::SetPitchAndYaw(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::SetPitchAndYawRequest* request, ::mavsdk::rpc::gimbal::SetPitchAndYawResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::SetPitchRateAndYawRate(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateRequest* request, ::mavsdk::rpc::gimbal::SetPitchRateAndYawRateResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::SetMode(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::SetModeRequest* request, ::mavsdk::rpc::gimbal::SetModeResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::SetRoiLocation(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::SetRoiLocationRequest* request, ::mavsdk::rpc::gimbal::SetRoiLocationResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::TakeControl(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::TakeControlRequest* request, ::mavsdk::rpc::gimbal::TakeControlResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::ReleaseControl(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::ReleaseControlRequest* request, ::mavsdk::rpc::gimbal::ReleaseControlResponse* response) { (void) context; (void) request; (void) response; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } ::grpc::Status GimbalService::Service::SubscribeControl(::grpc::ServerContext* context, const ::mavsdk::rpc::gimbal::SubscribeControlRequest* request, ::grpc::ServerWriter< ::mavsdk::rpc::gimbal::ControlResponse>* writer) { (void) context; (void) request; (void) writer; return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); } } // namespace mavsdk } // namespace rpc } // namespace gimbal
76.910714
317
0.747581
fpersson
1c00ca7ebcb8c0ce9aeeb4784f8e788502f27923
9,983
cc
C++
src/xzero/http/http1/Parser-test.cc
pjsaksa/x0
96b69e5a54b006e3d929b9934c2708f7967371bb
[ "MIT" ]
24
2016-07-10T08:05:11.000Z
2021-11-16T10:53:48.000Z
src/xzero/http/http1/Parser-test.cc
pjsaksa/x0
96b69e5a54b006e3d929b9934c2708f7967371bb
[ "MIT" ]
14
2015-04-12T10:45:26.000Z
2016-06-28T22:27:50.000Z
src/xzero/http/http1/Parser-test.cc
pjsaksa/x0
96b69e5a54b006e3d929b9934c2708f7967371bb
[ "MIT" ]
4
2016-10-05T17:51:38.000Z
2020-04-20T07:45:23.000Z
// This file is part of the "x0" project, http://github.com/christianparpart/x0> // (c) 2009-2018 Christian Parpart <[email protected]> // // Licensed under the MIT License (the "License"); you may not use this // file except in compliance with the License. You may obtain a copy of // the License at: http://opensource.org/licenses/MIT #include <xzero/http/http1/Parser.h> #include <xzero/http/HttpListener.h> #include <xzero/http/HttpStatus.h> #include <xzero/io/FileUtil.h> #include <xzero/RuntimeError.h> #include <xzero/Buffer.h> #include <vector> #include <xzero/testing.h> using namespace xzero; using namespace xzero::http; using namespace xzero::http::http1; class ParserListener : public HttpListener { // {{{ public: ParserListener(); void onMessageBegin(const BufferRef& method, const BufferRef& entity, HttpVersion version) override; void onMessageBegin(HttpVersion version, HttpStatus code, const BufferRef& text) override; void onMessageBegin() override; void onMessageHeader(const BufferRef& name, const BufferRef& value) override; void onMessageHeaderEnd() override; void onMessageContent(const BufferRef& chunk) override; void onMessageContent(FileView&& chunk) override; void onMessageEnd() override; void onError(std::error_code ec) override; public: std::string method; std::string entity; HttpVersion version; HttpStatus statusCode; std::string statusReason; std::vector<std::pair<std::string, std::string>> headers; Buffer body; HttpStatus errorCode; bool messageBegin; bool headerEnd; bool messageEnd; }; ParserListener::ParserListener() : method(), entity(), version(HttpVersion::UNKNOWN), statusCode(HttpStatus::Undefined), statusReason(), headers(), errorCode(HttpStatus::Undefined), messageBegin(false), headerEnd(false), messageEnd(false) { } void ParserListener::onMessageBegin(const BufferRef& method, const BufferRef& entity, HttpVersion version) { this->method = method.str(); this->entity = entity.str(); this->version = version; } void ParserListener::onMessageBegin(HttpVersion version, HttpStatus code, const BufferRef& text) { this->version = version; this->statusCode = code; this->statusReason = text.str(); } void ParserListener::onMessageBegin() { messageBegin = true; } void ParserListener::onMessageHeader(const BufferRef& name, const BufferRef& value) { headers.push_back(std::make_pair(name.str(), value.str())); } void ParserListener::onMessageHeaderEnd() { headerEnd = true; } void ParserListener::onMessageContent(const BufferRef& chunk) { body += chunk; } void ParserListener::onMessageContent(FileView&& chunk) { body += FileUtil::read(chunk); } void ParserListener::onMessageEnd() { messageEnd = true; } void ParserListener::onError(std::error_code ec) { errorCode = static_cast<HttpStatus>(ec.value()); } // }}} TEST(http_http1_Parser, requestLine0) { /* Seems like in HTTP/0.9 it was possible to create * very simple request messages. */ ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET /\r\n"); ASSERT_EQ("GET", listener.method); ASSERT_EQ("/", listener.entity); ASSERT_EQ(HttpVersion::VERSION_0_9, listener.version); ASSERT_TRUE(listener.headerEnd); ASSERT_TRUE(listener.messageEnd); ASSERT_EQ(0, listener.headers.size()); ASSERT_EQ(0, listener.body.size()); } TEST(http_http1_Parser, requestLine1) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET / HTTP/0.9\r\n\r\n"); ASSERT_EQ("GET", listener.method); ASSERT_EQ("/", listener.entity); ASSERT_EQ(HttpVersion::VERSION_0_9, listener.version); ASSERT_EQ(0, listener.headers.size()); ASSERT_EQ(0, listener.body.size()); } TEST(http_http1_Parser, requestLine2) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("HEAD /foo?bar HTTP/1.0\r\n\r\n"); ASSERT_EQ("HEAD", listener.method); ASSERT_EQ("/foo?bar", listener.entity); ASSERT_EQ(HttpVersion::VERSION_1_0, listener.version); ASSERT_EQ(0, listener.headers.size()); ASSERT_EQ(0, listener.body.size()); } TEST(http_http1_Parser, requestLine_invalid1_MissingPathAndProtoVersion) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET\r\n\r\n"); ASSERT_EQ(HttpStatus::BadRequest, listener.errorCode); } TEST(http_http1_Parser, requestLine_invalid3_InvalidVersion) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET / HTTP/0\r\n\r\n"); ASSERT_EQ((int)HttpStatus::BadRequest, (int)listener.errorCode); } TEST(http_http1_Parser, requestLine_invalid3_CharsAfterVersion) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET / HTTP/1.1b\r\n\r\n"); ASSERT_EQ((int)HttpStatus::BadRequest, (int)listener.errorCode); } TEST(http_http1_Parser, requestLine_invalid5_SpaceAfterVersion) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment("GET / HTTP/1.1 \r\n\r\n"); ASSERT_EQ((int)HttpStatus::BadRequest, (int)listener.errorCode); } TEST(http_http1_Parser, requestLine_invalid6_UnsupportedVersion) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); // Actually, we could make it a ParserError, or HttpClientError or so, // But to make googletest lib happy, we should make it even a distinct class. ASSERT_THROW(parser.parseFragment("GET / HTTP/1.2\r\n\r\n"), RuntimeError); } TEST(http_http1_Parser, headers1) { ParserListener listener; Parser parser(Parser::MESSAGE, &listener); parser.parseFragment( "Foo: the foo\r\n" "Content-Length: 6\r\n" "\r\n" "123456"); ASSERT_EQ("Foo", listener.headers[0].first); ASSERT_EQ("the foo", listener.headers[0].second); ASSERT_EQ("123456", listener.body); } TEST(http_http1_Parser, invalidHeader1) { ParserListener listener; Parser parser(Parser::MESSAGE, &listener); size_t n = parser.parseFragment("Foo : the foo\r\n" "\r\n"); ASSERT_EQ(HttpStatus::BadRequest, listener.errorCode); ASSERT_EQ(3, n); ASSERT_EQ(0, listener.headers.size()); } TEST(http_http1_Parser, invalidHeader2) { ParserListener listener; Parser parser(Parser::MESSAGE, &listener); size_t n = parser.parseFragment("Foo\r\n" "\r\n"); ASSERT_EQ(HttpStatus::BadRequest, listener.errorCode); ASSERT_EQ(5, n); ASSERT_EQ(0, listener.headers.size()); } TEST(http_http1_Parser, requestWithHeaders) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment( "GET / HTTP/0.9\r\n" "Foo: the foo\r\n" "X-Bar: the bar\r\n" "\r\n"); ASSERT_EQ("GET", listener.method); ASSERT_EQ("/", listener.entity); ASSERT_EQ(HttpVersion::VERSION_0_9, listener.version); ASSERT_EQ(2, listener.headers.size()); ASSERT_EQ(0, listener.body.size()); ASSERT_EQ("Foo", listener.headers[0].first); ASSERT_EQ("the foo", listener.headers[0].second); ASSERT_EQ("X-Bar", listener.headers[1].first); ASSERT_EQ("the bar", listener.headers[1].second); } TEST(http_http1_Parser, requestWithHeadersAndBody) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment( "GET / HTTP/0.9\r\n" "Foo: the foo\r\n" "X-Bar: the bar\r\n" "Content-Length: 6\r\n" "\r\n" "123456"); ASSERT_EQ("123456", listener.body); } // no chunks except the EOS-chunk TEST(http_http1_Parser, requestWithHeadersAndBodyChunked1) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment( "GET / HTTP/0.9\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "0\r\n" "\r\n"); ASSERT_EQ("", listener.body); } // exactly one data chunk TEST(http_http1_Parser, requestWithHeadersAndBodyChunked2) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment( "GET / HTTP/0.9\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "6\r\n" "123456" "\r\n" "0\r\n" "\r\n"); ASSERT_EQ("123456", listener.body); } // more than one data chunk TEST(http_http1_Parser, requestWithHeadersAndBodyChunked3) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); parser.parseFragment( "GET / HTTP/0.9\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "6\r\n" "123456" "\r\n" "6\r\n" "123456" "\r\n" "0\r\n" "\r\n"); ASSERT_EQ("123456123456", listener.body); } // first chunk is missing CR LR TEST(http_http1_Parser, requestWithHeadersAndBodyChunked_invalid1) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); size_t n = parser.parseFragment( "GET / HTTP/0.9\r\n" "Transfer-Encoding: chunked\r\n" "\r\n" "6\r\n" "123456" //"\r\n" // should bailout here "0\r\n" "\r\n"); ASSERT_EQ(55, n); ASSERT_EQ(HttpStatus::BadRequest, listener.errorCode); } TEST(http_http1_Parser, pipelined1) { ParserListener listener; Parser parser(Parser::REQUEST, &listener); constexpr BufferRef input = "GET /foo HTTP/1.1\r\n\r\n" "HEAD /bar HTTP/0.9\r\n\r\n"; size_t n = parser.parseFragment(input); EXPECT_EQ("GET", listener.method); EXPECT_EQ("/foo", listener.entity); EXPECT_EQ(HttpVersion::VERSION_1_1, listener.version); parser.parseFragment(input.ref(n)); EXPECT_EQ("HEAD", listener.method); EXPECT_EQ("/bar", listener.entity); EXPECT_EQ(HttpVersion::VERSION_0_9, listener.version); }
28.280453
80
0.683863
pjsaksa
1c0f8cdf4689a866f0b5c92700272cdaa0d66e4e
5,951
cpp
C++
OnlineSubsystemB3atZUtils/Source/OnlineSubsystemB3atZUtils/Private/B3atZOnlineBeacon.cpp
philippbb/OnlineSubsytemB3atZPlugin
17ad7c220fddd24bc36860ad9bbc20b3a98bb357
[ "MIT" ]
10
2017-07-22T13:04:45.000Z
2021-12-22T10:02:32.000Z
OnlineSubsystemB3atZUtils/Source/OnlineSubsystemB3atZUtils/Private/B3atZOnlineBeacon.cpp
philippbb/OnlineSubsytemB3atZPlugin
17ad7c220fddd24bc36860ad9bbc20b3a98bb357
[ "MIT" ]
null
null
null
OnlineSubsystemB3atZUtils/Source/OnlineSubsystemB3atZUtils/Private/B3atZOnlineBeacon.cpp
philippbb/OnlineSubsytemB3atZPlugin
17ad7c220fddd24bc36860ad9bbc20b3a98bb357
[ "MIT" ]
3
2017-05-06T20:31:43.000Z
2020-07-01T01:45:37.000Z
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved // Plugin written by Philipp Buerki. Copyright 2017. All Rights reserved.. #include "../OnlineSubsystemB3atZUtils/Public/B3atZOnlineBeacon.h" #include "Engine/NetConnection.h" #include "EngineGlobals.h" #include "Engine/Engine.h" DEFINE_LOG_CATEGORY(LogBeacon); AB3atZOnlineBeacon::AB3atZOnlineBeacon(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer), NetDriver(nullptr), BeaconState(EBeaconState::DenyRequests) { NetDriverName = FName(TEXT("BeaconDriver")); } bool AB3atZOnlineBeacon::InitBase() { UE_LOG(LogTemp, Warning, TEXT("B3atZOnlineBeacon InitBase")); NetDriver = GEngine->CreateNetDriver(GetWorld(), NAME_BeaconNetDriver); if (NetDriver != nullptr) { UE_LOG(LogTemp, Warning, TEXT("B3atZOnlineBeacon InitBase CreatedNetDriver is valid")); HandleNetworkFailureDelegateHandle = GEngine->OnNetworkFailure().AddUObject(this, &AB3atZOnlineBeacon::HandleNetworkFailure); SetNetDriverName(NetDriver->NetDriverName); return true; } return false; } void AB3atZOnlineBeacon::EndPlay(const EEndPlayReason::Type EndPlayReason) { if (NetDriver) { GEngine->DestroyNamedNetDriver(GetWorld(), NetDriverName); NetDriver = nullptr; } Super::EndPlay(EndPlayReason); } bool AB3atZOnlineBeacon::HasNetOwner() const { // Beacons are their own net owners return true; } void AB3atZOnlineBeacon::DestroyBeacon() { UE_LOG(LogBeacon, Verbose, TEXT("Destroying beacon %s, netdriver %s"), *GetName(), NetDriver ? *NetDriver->GetDescription() : TEXT("NULL")); GEngine->OnNetworkFailure().Remove(HandleNetworkFailureDelegateHandle); if (NetDriver) { GEngine->DestroyNamedNetDriver(GetWorld(), NetDriverName); NetDriver = nullptr; } Destroy(); } void AB3atZOnlineBeacon::HandleNetworkFailure(UWorld *World, UNetDriver *InNetDriver, ENetworkFailure::Type FailureType, const FString& ErrorString) { if (InNetDriver && InNetDriver->NetDriverName == NetDriverName) { UE_LOG(LogBeacon, Verbose, TEXT("NetworkFailure %s: %s"), *GetName(), ENetworkFailure::ToString(FailureType)); OnFailure(); } } void AB3atZOnlineBeacon::OnFailure() { GEngine->OnNetworkFailure().Remove(HandleNetworkFailureDelegateHandle); if (NetDriver) { GEngine->DestroyNamedNetDriver(GetWorld(), NetDriverName); NetDriver = nullptr; } } void AB3atZOnlineBeacon::OnActorChannelOpen(FInBunch& Bunch, UNetConnection* Connection) { Connection->OwningActor = this; Super::OnActorChannelOpen(Bunch, Connection); } bool AB3atZOnlineBeacon::IsRelevancyOwnerFor(const AActor* ReplicatedActor, const AActor* ActorOwner, const AActor* ConnectionActor) const { bool bRelevantOwner = (ConnectionActor == ReplicatedActor); return bRelevantOwner; } bool AB3atZOnlineBeacon::IsNetRelevantFor(const AActor* RealViewer, const AActor* ViewTarget, const FVector& SrcLocation) const { // Only replicate to the owner or to connections of the same beacon type (possible that multiple UNetConnections come from the same client) bool bIsOwner = GetNetConnection() == ViewTarget->GetNetConnection(); bool bSameBeaconType = GetClass() == RealViewer->GetClass(); return bOnlyRelevantToOwner ? bIsOwner : bSameBeaconType; } EAcceptConnection::Type AB3atZOnlineBeacon::NotifyAcceptingConnection() { check(NetDriver); if(NetDriver->ServerConnection) { // We are a client and we don't welcome incoming connections. UE_LOG(LogNet, Log, TEXT("NotifyAcceptingConnection: Client refused")); return EAcceptConnection::Reject; } else if(BeaconState == EBeaconState::DenyRequests) { // Server is down UE_LOG(LogNet, Log, TEXT("NotifyAcceptingConnection: Server %s refused"), *GetName()); return EAcceptConnection::Reject; } else //if(BeaconState == EBeaconState::AllowRequests) { // Server is up and running. UE_LOG(LogNet, Log, TEXT("B3atZOnlineBeacon NotifyAcceptingConnection: Server %s accept"), *GetName()); return EAcceptConnection::Accept; } } void AB3atZOnlineBeacon::NotifyAcceptedConnection(UNetConnection* Connection) { check(NetDriver != nullptr); check(NetDriver->ServerConnection == nullptr); UE_LOG(LogNet, Log, TEXT("NotifyAcceptedConnection: Name: %s, TimeStamp: %s, %s"), *GetName(), FPlatformTime::StrTimestamp(), *Connection->Describe()); } bool AB3atZOnlineBeacon::NotifyAcceptingChannel(UChannel* Channel) { check(Channel); check(Channel->Connection); check(Channel->Connection->Driver); UNetDriver* Driver = Channel->Connection->Driver; check(NetDriver == Driver); if (Driver->ServerConnection) { // We are a client and the server has just opened up a new channel. UE_LOG(LogNet, Log, TEXT("NotifyAcceptingChannel %i/%i client %s"), Channel->ChIndex, (int32)Channel->ChType, *GetName()); if (Channel->ChType == CHTYPE_Actor) { // Actor channel. UE_LOG(LogNet, Log, TEXT("Client accepting actor channel")); return 1; } else if (Channel->ChType == CHTYPE_Voice) { // Accept server requests to open a voice channel, allowing for custom voip implementations // which utilize multiple server controlled voice channels. UE_LOG(LogNet, Log, TEXT("Client accepting voice channel")); return 1; } else { // Unwanted channel type. UE_LOG(LogNet, Log, TEXT("Client refusing unwanted channel of type %i"), (uint8)Channel->ChType); return 0; } } else { // We are the server. if (Channel->ChIndex == 0 && Channel->ChType == CHTYPE_Control) { // The client has opened initial channel. UE_LOG(LogNet, Log, TEXT("NotifyAcceptingChannel Control %i server %s: Accepted"), Channel->ChIndex, *GetFullName()); return 1; } else { // Client can't open any other kinds of channels. UE_LOG(LogNet, Log, TEXT("NotifyAcceptingChannel %i %i server %s: Refused"), (uint8)Channel->ChType, Channel->ChIndex, *GetFullName()); return 0; } } } void AB3atZOnlineBeacon::NotifyControlMessage(UNetConnection* Connection, uint8 MessageType, FInBunch& Bunch) { }
31.321053
152
0.750294
philippbb
1c1246b06c41ea08f0c0a3bb12e4b5c2f55d9dea
1,107
cpp
C++
Online Judges/LightOJ/1047 - Neighbor House.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/LightOJ/1047 - Neighbor House.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
Online Judges/LightOJ/1047 - Neighbor House.cpp
akazad13/competitive-programming
5cbb67d43ad8d5817459043bcccac3f68d9bc688
[ "MIT" ]
null
null
null
#include<iostream> #include<bits/stdc++.h> using namespace std; //Macros #define read(a) scanf("%d",&a) #define CLEAR(a,b) memset(a,b,sizeof(a)) #define VI(a) vector<a> #define lld long long int #define ulld unsigned long long int #define PI acos(-1.0) #define Gamma 0.5772156649015328606065120900824024310421 int arr[22][3]; int dp[22][3]; int n; int cal(int i,int j) { if(i==n) return 0; if(i>=n|| j<0 || j>2) return INT_MAX; if(dp[i][j]!=-1) return dp[i][j]; for(int k=0;k<3;k++) { dp[i][k]= arr[i][k]+min(min( cal(i+1,k+1) , cal(i+1,k-1) ), min( cal(i+1,k+2) , cal(i+1,k-2) )); } return dp[i][j]; } int main() { int test; read(test); for(int Case = 1;Case<=test;Case++) { CLEAR(dp,-1); read(n); for(int i=0;i<n;i++) { for(int j=0;j<3;j++) { scanf("%d",&arr[i][j]); } } int ret = cal(0,0); for(int i=0;i<3;i++) ret = min(ret,dp[0][i]); printf("Case %d: %d\n",Case,ret); } return 0; }
17.030769
104
0.483288
akazad13
1c16dc3bb20e37ed22e6079c11a2e75d1e557c8f
1,361
cpp
C++
client/LocalConn.cpp
lzs123/CProxy
08266997317b0ba89ddc93dac46b0faf5fd12592
[ "MIT" ]
7
2022-02-07T08:26:55.000Z
2022-03-23T02:55:44.000Z
client/LocalConn.cpp
lzs123/CProxy
08266997317b0ba89ddc93dac46b0faf5fd12592
[ "MIT" ]
null
null
null
client/LocalConn.cpp
lzs123/CProxy
08266997317b0ba89ddc93dac46b0faf5fd12592
[ "MIT" ]
null
null
null
#include <fcntl.h> #include <string.h> #include "LocalConn.h" #include "Tunnel.h" #include "lib/Util.h" void LocalConn::handleRead() { try{ int bs = splice(fd_, NULL, pipe_fds_[1], NULL, 2048, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (bs < 0) { SPDLOG_CRITICAL("proxy_id: {} local_fd: {} -> pipe_fd: {} splice err: {} ", proxy_id_, fd_, pipe_fds_[1], strerror(errno)); return; } // 当proxyConn调用shutdownFromRemote后,shutdown(local_fd, 1)后会往local_fd中添加EPOLLIN事件,所以可能会重复满足bs=0,需要添加closing_判断。避免多次进入循环 // https://mp.weixin.qq.com/s?__biz=MzUxNDUwOTc0Nw==&mid=2247484253&idx=1&sn=e42ed5e1af8382eb6dffa7550470cdf3 if (bs == 0 && !closing_) { tun_->shutdownFromLocal(proxy_id_, getTranCount()); closing_ = true; return; } bs = splice(pipe_fds_[0], NULL, peer_conn_fd_, NULL, bs, SPLICE_F_MOVE | SPLICE_F_NONBLOCK); if (bs < 0) { SPDLOG_CRITICAL("proxy_id {} local_fd: {} pipe_fd: {} -> proxy_conn_fd: {} splice err: {}", proxy_id_, fd_, pipe_fds_[0], peer_conn_fd_, strerror(errno)); return; } incrTranCount(bs); } catch (const std::exception& e) { SPDLOG_CRITICAL("read local_conn except: {}", e.what()); } } void LocalConn::postHandle() { if (closing_) { return; } channel_->setEvents(EPOLLET | EPOLLIN | EPOLLRDHUP); loop_->updatePoller(channel_); }
35.815789
162
0.659809
lzs123
1c2019fcd1b8894f0a0a76c6cff42181449ee6bc
129,465
cpp
C++
bwchart/bwchart/DlgStats.cpp
udonyang/scr-benchmark
ed81d74a9348b6813750007d45f236aaf5cf4ea4
[ "MIT" ]
null
null
null
bwchart/bwchart/DlgStats.cpp
udonyang/scr-benchmark
ed81d74a9348b6813750007d45f236aaf5cf4ea4
[ "MIT" ]
null
null
null
bwchart/bwchart/DlgStats.cpp
udonyang/scr-benchmark
ed81d74a9348b6813750007d45f236aaf5cf4ea4
[ "MIT" ]
null
null
null
// DlgStats.cpp : implementation file // #include "stdafx.h" #include "bwchart.h" #include "DlgStats.h" #include "regparam.h" #include "bwrepapi.h" #include "DlgHelp.h" #include "DlgMap.h" #include "Dlgbwchart.h" #include "gradient.h" #include "hsvrgb.h" #include "overlaywnd.h" #include "ExportCoachDlg.h" #include "bezier.h" #include <math.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #define MAXPLAYERONVIEW 6 #define HSCROLL_DIVIDER 2 #define TIMERSPEED 8 //----------------------------------------------------------------------------------------------------------------- // constants for chart painting int hleft=30; const int haxisleft = 2; const int vplayer=30; const int hplayer=52; const int hright=8; const int vtop=24; const int vbottom=12; const int evtWidth=4; const int evtHeight=8; const int layerHeight=14; const COLORREF clrCursor = RGB(200,50,50); const COLORREF clrMineral = RGB(50,50,150); const COLORREF clrGrid = RGB(64,64,64); const COLORREF clrLayer1 = RGB(32,32,32); const COLORREF clrLayer2 = RGB(16,16,16); const COLORREF clrLayerTxt1 = RGB(0,0,0); const COLORREF clrLayerTxt2 = RGB(64,64,64); const COLORREF clrAction = RGB(255,206,70); const COLORREF clrBOLine[3] = {RGB(30,30,120),RGB(80,30,30),RGB(30,80,30)}; const COLORREF clrBOName[3] = {RGB(100,150,190), RGB(200,50,90), RGB(50,200,90) }; #define clrPlayer OPTIONSCHART->GetColor(DlgOptionsChart::CLR_PLAYERS) #define clrUnitName OPTIONSCHART->GetColor(DlgOptionsChart::CLR_OTHER) #define clrRatio OPTIONSCHART->GetColor(DlgOptionsChart::CLR_OTHER) #define clrTime OPTIONSCHART->GetColor(DlgOptionsChart::CLR_OTHER) static bool firstPoint=true; static int lastMaxX=0; static int lastHotPointX=0; static const char *lastHotPoint=0; static CString strDrop; static CString strExpand; static CString strLeave; static CString strMinGas; static CString strSupplyUnit; static CString strMinimapPing; // dividers for splines static int gSplineCount[DlgStats::__MAXCHART]= { //APM 200, //RESOURCES, 200, //UNITS 200, //ACTIONS 0, //BUILDINGS 0, //UPGRADES 0, //APMDIST 0, //BUILDORDER 0, //HOTKEYS 0, //MAPCOVERAGE 100, //MIX_APMHOTKEYS 0 }; //----------------------------------------------------------------------------------------------------------------- BEGIN_MESSAGE_MAP(DlgStats, CDialog) //{{AFX_MSG_MAP(DlgStats) ON_WM_PAINT() ON_BN_CLICKED(IDC_GETEVENTS, OnGetevents) ON_WM_SIZE() ON_NOTIFY(LVN_ITEMCHANGED, IDC_LISTEVENTS, OnItemchangedListevents) ON_WM_LBUTTONDOWN() ON_CBN_SELCHANGE(IDC_ZOOM, OnSelchangeZoom) ON_WM_HSCROLL() ON_NOTIFY(NM_DBLCLK, IDC_PLSTATS, OnDblclkPlstats) ON_BN_CLICKED(IDC_GAZ, OnUpdateChart) ON_WM_DESTROY() ON_CBN_SELCHANGE(IDC_CHARTTYPE, OnSelchangeCharttype) ON_BN_CLICKED(IDC_DHELP, OnHelp) ON_BN_CLICKED(IDC_TESTREPLAYS, OnTestreplays) ON_BN_CLICKED(IDC_ADDEVENT, OnAddevent) ON_NOTIFY(NM_RCLICK, IDC_PLSTATS, OnRclickPlstats) ON_BN_CLICKED(IDC_SEEMAP, OnSeemap) ON_BN_CLICKED(IDC_ANIMATE, OnAnimate) ON_WM_TIMER() ON_BN_CLICKED(IDC_PAUSE, OnPause) ON_BN_CLICKED(IDC_SPEEDMINUS, OnSpeedminus) ON_BN_CLICKED(IDC_SPEEDPLUS, OnSpeedplus) ON_NOTIFY(LVN_GETDISPINFO, IDC_LISTEVENTS, OnGetdispinfoListevents) ON_WM_LBUTTONUP() ON_WM_MOUSEMOVE() ON_WM_SETCURSOR() ON_WM_RBUTTONDOWN() ON_NOTIFY(NM_RCLICK, IDC_LISTEVENTS, OnRclickListevents) ON_BN_CLICKED(IDC_FLT_SELECT, OnFilterChange) ON_BN_CLICKED(IDC_NEXT_SUSPECT, OnNextSuspect) ON_BN_CLICKED(IDC_MINERALS, OnUpdateChart) ON_BN_CLICKED(IDC_SUPPLY, OnUpdateChart) ON_BN_CLICKED(IDC_ACTIONS, OnUpdateChart) ON_BN_CLICKED(IDC_UNITS, OnUpdateChart) ON_BN_CLICKED(IDC_USESECONDS, OnUpdateChart) ON_BN_CLICKED(IDC_SPEED, OnUpdateChart) ON_BN_CLICKED(IDC_SINGLECHART, OnUpdateChart) ON_BN_CLICKED(IDC_UNITSONBO, OnUpdateChart) ON_BN_CLICKED(IDC_HOTPOINTS, OnUpdateChart) ON_BN_CLICKED(IDC_UPM, OnUpdateChart) ON_BN_CLICKED(IDC_BPM, OnUpdateChart) ON_BN_CLICKED(IDC_PERCENTAGE, OnUpdateChart) ON_BN_CLICKED(IDC_HKSELECT, OnUpdateChart) ON_BN_CLICKED(IDC_FLT_BUILD, OnFilterChange) ON_BN_CLICKED(IDC_FLT_TRAIN, OnFilterChange) ON_BN_CLICKED(IDC_FLT_SUSPECT, OnFilterChange) ON_BN_CLICKED(IDC_FLT_HACK, OnFilterChange) ON_BN_CLICKED(IDC_FLT_OTHERS, OnFilterChange) ON_BN_CLICKED(IDC_FLT_CHAT, OnFilterChange) ON_BN_CLICKED(IDC_SORTDIST, OnUpdateChart) ON_CBN_SELCHANGE(IDC_APMSTYLE, OnSelchangeApmstyle) //}}AFX_MSG_MAP ON_COMMAND(ID__REMOVEPLAYER,OnRemovePlayer) ON_COMMAND(ID__ENABLEDISABLE,OnEnableDisable) ON_COMMAND(ID__WATCHREPLAY_BW116,OnWatchReplay116) ON_COMMAND(ID__WATCHREPLAY_BW115,OnWatchReplay115) ON_COMMAND(ID__WATCHREPLAY_BW114,OnWatchReplay114) ON_COMMAND(ID__WATCHREPLAY_BW113,OnWatchReplay113) ON_COMMAND(ID__WATCHREPLAY_BW112,OnWatchReplay112) ON_COMMAND(ID__WATCHREPLAY_BW111,OnWatchReplay111) ON_COMMAND(ID__WATCHREPLAY_BW110,OnWatchReplay110) ON_COMMAND(ID__WATCHREPLAY_BW109,OnWatchReplay109) ON_COMMAND(ID__WATCHREPLAYINBW_SC,OnWatchReplaySC) ON_COMMAND(ID__WATCHREPLAYINBW_AUTO,OnWatchReplay) ON_COMMAND(ID_FF_EXPORT_TOTEXTFILE,OnExportToText) ON_COMMAND(ID__EXPORTTO_BWCOACH,OnExportToBWCoach) // ON_COMMAND(ID_FF_EXPORTTO_HTMLFILE,OnExportToHtml) END_MESSAGE_MAP() //----------------------------------------------------------------------------------------------------------------- void DlgStats::_Parameters(bool bLoad) { int defval[__MAXCHART]; int defvalUnits[__MAXCHART]; int defvalApm[__MAXCHART]; memset(defval,0,sizeof(defval)); memset(defvalUnits,0,sizeof(defvalUnits)); memset(defvalApm,0,sizeof(defval)); defvalUnits[MAPCOVERAGE]=1; defvalApm[MAPCOVERAGE]=2; defvalApm[APM]=2; PINT("main",seeMinerals,TRUE); PINT("main",seeGaz,TRUE); PINT("main",seeSupply,FALSE); PINT("main",seeActions,FALSE); PINTARRAY("main",singleChart,__MAXCHART,defval); PINTARRAY("main",seeUnits,__MAXCHART,defvalUnits); PINTARRAY("main",apmStyle,__MAXCHART,defvalApm); PINT("main",useSeconds,FALSE); PINT("main",seeSpeed,FALSE); PINT("main",seeUPM,FALSE); PINT("main",seeBPM,FALSE); PINT("main",chartType,0); PINT("main",seeUnitsOnBO,TRUE); PINT("main",seeHotPoints,TRUE); PINT("main",seePercent,TRUE); PINT("main",animationSpeed,2); PINT("main",hlist,120); PINT("main",wlist,0); PINT("main",viewHKselect,FALSE); PINT("filter",fltSelect,TRUE); PINT("filter",fltTrain,TRUE); PINT("filter",fltBuild,TRUE); PINT("filter",fltSuspect,TRUE); PINT("filter",fltHack,TRUE); PINT("filter",fltOthers,TRUE); PINT("filter",fltChat,TRUE); PINT("main",sortDist,FALSE); } //----------------------------------------------------------------------------------------------------------------- /* static void _GetRemoteItemText(HANDLE hProcess, HWND hlv, LV_ITEM* plvi, int item, int subitem, char *itemText) { // Initialize a local LV_ITEM structure LV_ITEM lvi; lvi.mask = LVIF_TEXT; lvi.iItem = item; lvi.iSubItem = subitem; // NOTE: The text data immediately follows the LV_ITEM structure // in the memory block allocated in the remote process. lvi.pszText = (LPTSTR) (plvi + 1); lvi.cchTextMax = 100; // Write the local LV_ITEM structure to the remote memory block if(!WriteProcessMemory(hProcess, plvi, &lvi, sizeof(lvi), NULL)) { ::MessageBox(0,__TEXT("Cant write into SuperView's memory"), "bwchart", MB_OK | MB_ICONWARNING); return; } // Tell the ListView control to fill the remote LV_ITEM structure ListView_GetItem(hlv, plvi); // Read the remote text string into our buffer if(!ReadProcessMemory(hProcess, plvi + 1, itemText, 256, NULL)) { ::MessageBox(0,__TEXT("Cant read into SuperView's memory"), "bwchart", MB_OK | MB_ICONWARNING); return; } } //----------------------------------------------------------------------------------------------------------------- typedef LPVOID (__stdcall * PFNVIRTALLEX)(HANDLE, LPVOID, SIZE_T, DWORD,DWORD); static HANDLE ghFileMapping=0; static PVOID _AllocSharedMemory(HANDLE hProcess, int size) { OSVERSIONINFO osvi = { sizeof(osvi) }; GetVersionEx( &osvi ); if ( osvi.dwPlatformId == VER_PLATFORM_WIN32_NT ) { // We're on NT, so use VirtualAllocEx to allocate memory in the other // process address space. Alas, we can't just call VirtualAllocEx // since it's not defined in the Windows 95 KERNEL32.DLL. return VirtualAllocEx(hProcess, NULL, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); } else if ( osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ) { // In Windows 9X, create a small memory mapped file. On this // platform, memory mapped files are above 2GB, and thus are // accessible by all processes. ghFileMapping = CreateFileMapping( INVALID_HANDLE_VALUE, 0, PAGE_READWRITE | SEC_COMMIT, 0, size, 0 ); if ( ghFileMapping ) { LPVOID pStubMemory = MapViewOfFile( ghFileMapping, FILE_MAP_WRITE, 0, 0, size ); return pStubMemory; } else { CloseHandle( ghFileMapping ); ghFileMapping=0; } } return 0; } //----------------------------------------------------------------------------------------------------------------- static void _FreeSharedMemory(HANDLE hProcess, PVOID padr) { OSVERSIONINFO osvi = { sizeof(osvi) }; GetVersionEx( &osvi ); if ( osvi.dwPlatformId == VER_PLATFORM_WIN32_NT ) { // We're on NT, so use VirtualFreeEx VirtualFreeEx(hProcess, padr, 0, MEM_RELEASE); } else if ( osvi.dwPlatformId == VER_PLATFORM_WIN32_WINDOWS ) { // In Windows 9X, create a small memory mapped file. On this // platform, memory mapped files are above 2GB, and thus are // accessible by all processes. UnmapViewOfFile(padr); CloseHandle( ghFileMapping ); } } //----------------------------------------------------------------------------------------------------------------- #define CMPUNIT(val,rval) if(_stricmp(itemParam,val)==0) {strcpy(itemParam,rval); return;} #define CMPBUILD(val,rval) if(_stricmp(lastp,val)==0) {strcpy(lastp,rval); return;} // adjust values static void _AdjustAction(char *itemType, char *itemParam) { if(_stricmp(itemType,"Train")==0) { CMPUNIT("46","Scout"); CMPUNIT("47","Arbiter"); CMPUNIT("3C","Corsair"); CMPUNIT("45","Shuttle"); CMPUNIT("53","Reaver"); CMPUNIT("01","Ghost"); CMPUNIT("0C","Battlecruiser"); CMPUNIT("Vulture","Goliath"); CMPUNIT("Goliath","Vulture"); CMPUNIT("0E","Nuke"); return; } else if(_stricmp(itemType,"2A")==0) {strcpy(itemType,"Train"); strcpy(itemParam,"Archon"); return;} else if(_stricmp(itemType,"5A")==0) {strcpy(itemType,"Train"); strcpy(itemParam,"Dark Archon"); return;} else if(_stricmp(itemType,"Build")==0) { // extract building name char *lastp=strrchr(itemParam,','); if(lastp!=0) lastp++; else lastp=itemParam; while(*lastp==' ') lastp++; CMPBUILD("AA","Arbiter Tribunal"); CMPBUILD("AB","Robotics Support Bay"); CMPBUILD("AC","Shield Battery"); CMPBUILD("75","Covert Ops"); CMPBUILD("76","Physics Lab"); CMPBUILD("6C","Nuclear Silo"); CMPBUILD("Acadamy","Academy"); return; } else if(_stricmp(itemType,"Research")==0 || _stricmp(itemType,"Upgrade")==0) { CMPUNIT("27","Gravitic Booster"); CMPUNIT("22","Zealot Speed"); CMPUNIT("15","Recall"); CMPUNIT("0E","Protoss Air Attack"); CMPUNIT("23","Scarab Damage"); CMPUNIT("26","Sensor Array"); CMPUNIT("16","Statis Field"); CMPUNIT("14","Hallucination"); CMPUNIT("0F","Plasma Shield"); CMPUNIT("24","Reaver Capacity"); CMPUNIT("2C","Khaydarin Core"); CMPUNIT("28","Khaydarin Amulet"); CMPUNIT("29","Apial Sensors"); CMPUNIT("25","Gravitic Drive"); CMPUNIT("1B","Mind Control"); CMPUNIT("2A","Gravitic Thrusters"); CMPUNIT("1F","Maelstrom"); CMPUNIT("31","Argus Talisman"); CMPUNIT("19","Disruption Web"); CMPUNIT("2F","Argus Jewel"); CMPUNIT("01","Lockdown"); CMPUNIT("02","EMP Shockwave"); CMPUNIT("09","Cloaking Field"); CMPUNIT("11","Vulture Speed"); CMPUNIT("0A","Personal Cloaking"); CMPUNIT("08","Yamato Gun"); CMPUNIT("17","Colossus Reactor"); CMPUNIT("18","Restoration"); CMPUNIT("1E","Optical Flare"); CMPUNIT("33","Medic Energy"); return; } } //----------------------------------------------------------------------------------------------------------------- bool DlgStats::_GetListViewContent(HWND hlv) { // Get the count of items in the ListView control int nCount = ListView_GetItemCount(hlv); // Open a handle to the remote process's kernel object DWORD dwProcessId; GetWindowThreadProcessId(hlv, &dwProcessId); HANDLE hProcess = OpenProcess( PROCESS_VM_OPERATION | PROCESS_VM_READ | PROCESS_VM_WRITE, FALSE, dwProcessId); if (hProcess == NULL) { MessageBox(__TEXT("Could not communicate with SuperView"), "bwchart", MB_OK | MB_ICONWARNING); return false; } // Allocate memory in the remote process's address space LV_ITEM* plvi = (LV_ITEM*) //VirtualAllocEx(hProcess, NULL, 4096, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); _AllocSharedMemory(hProcess, 4096); if (plvi == NULL) { DWORD dw=GetLastError(); CString msg; msg.Format("Could not allocate virtual memory %lu",dw); MessageBox("Sorry, but BWchart cannot work under Windows 95/98", "bwchart", MB_OK | MB_ICONWARNING); return false; } // Get each ListView item's text data for (int nIndex = 0; nIndex < nCount; nIndex++) { // read elapsed time char itemTime[256]; _GetRemoteItemText(hProcess, hlv, plvi, nIndex, 0, itemTime); int nPos = m_listEvents.InsertItem(nIndex,itemTime, 0); m_listEvents.SetItemData(nPos,(DWORD)_atoi64(itemTime)); // read player name char itemPlayer[256]; _GetRemoteItemText(hProcess, hlv, plvi, nIndex, 1, itemPlayer); m_listEvents.SetItemText(nPos,1,itemPlayer); // read event type char itemType[256]; _GetRemoteItemText(hProcess, hlv, plvi, nIndex, 2, itemType); // read event parameters char itemParam[256]; _GetRemoteItemText(hProcess, hlv, plvi, nIndex, 3, itemParam); // adjust values _AdjustAction(itemType,itemParam); // update list view m_listEvents.SetItemText(nPos,2,itemType); m_listEvents.SetItemText(nPos,3,itemParam); // record event //m_replay.AddEvent(atoi(itemTime),itemPlayer,itemType,itemParam); } // Free the memory in the remote process's address space _FreeSharedMemory(hProcess, plvi); //VirtualFreeEx(hProcess, plvi, 0, MEM_RELEASE); // Cleanup and put our results on the clipboard CloseHandle(hProcess); return true; } //----------------------------------------------------------------------------------------------------------------- BOOL CALLBACK EnumChildProc( HWND hwnd, // handle to child window LPARAM lParam // application-defined value ) { char classname[128]; GetClassName(hwnd,classname,sizeof(classname)); if(_stricmp(classname,"SysListView32")==0) { HWND hlv = ::GetNextWindow(hwnd, GW_HWNDNEXT); if(hlv==0) return FALSE; hlv = ::GetNextWindow(hlv, GW_HWNDNEXT); if(hlv==0) return FALSE; *((HWND*)lParam) = hlv; return FALSE; } return TRUE; } */ //----------------------------------------------------------------------------------------------------------------- bool DlgStats::_GetReplayFileName(CString& path) { static char BASED_CODE szFilter[] = "Replay (*.rep)|*.rep|All Files (*.*)|*.*||"; // find initial path CString initialPath; initialPath = AfxGetApp()->GetProfileString("MAIN","LASTADDREPLAY"); if(initialPath.IsEmpty()) DlgOptions::_GetStarcraftPath(initialPath); // stop animation if any StopAnimation(); // open dialog CFileDialog dlg(TRUE,"rep","",0,szFilter,this); dlg.m_ofn.lpstrInitialDir = initialPath; if(dlg.DoModal()==IDOK) { CWaitCursor wait; path = dlg.GetPathName(); AfxGetApp()->WriteProfileString("MAIN","LASTADDREPLAY",path); return true; } return false; } ///////////////////////////////////////////////////////////////////////////// // DlgStats dialog DlgStats::DlgStats(CWnd* pParent /*=NULL*/) : CDialog(DlgStats::IDD, pParent) { //{{AFX_DATA_INIT(DlgStats) m_zoom = 0; m_seeMinerals = TRUE; m_seeGaz = TRUE; m_seeSupply = FALSE; m_seeActions = FALSE; m_useSeconds = FALSE; m_seeSpeed = FALSE; m_chartType = -1; m_seeUnitsOnBO = FALSE; m_exactTime = _T(""); m_seeBPM = FALSE; m_seeUPM = FALSE; m_seeHotPoints = FALSE; m_seePercent = FALSE; m_viewHKselect = FALSE; m_fltSelect = FALSE; m_fltSuspect = FALSE; m_fltHack = FALSE; m_fltTrain = FALSE; m_fltBuild = FALSE; m_fltOthers = FALSE; m_fltChat = FALSE; m_suspectInfo = _T(""); m_sortDist = FALSE; //}}AFX_DATA_INIT // Note that LoadIcon does not require a subsequent DestroyIcon in Win32 m_timeBegin = 0; m_timeEnd = 0; m_lockListView=false; m_selectedPlayer=0; m_selectedAction=-1; m_maxPlayerOnBoard=0; m_selectedPlayerList=0; m_bIsAnimating=false; m_animationSpeed=2; m_prevAnimationSpeed=0; m_timer=0; m_mixedCount=0; m_MixedPlayerIdx=0; // map title m_rectMapName.SetRectEmpty(); // resize m_resizing=NONE; m_hlist=120; m_wlist=0; // load parameters _Parameters(true); if(m_hlist<60) m_hlist=60; // scroller increments m_lineDev.cx = 5; m_lineDev.cy = 0; m_pageDev.cx = 50; m_pageDev.cy = 0; // create all fonts _CreateFonts(); // create map m_dlgmap = new DlgMap(0,m_pLabelBoldFont,m_pLayerFont,this); // create overlay m_over = new OverlayWnd(this); // init time m_exactTime = _MkTime(0,0,true); } DlgStats::~DlgStats() { // delete overlay m_over->DestroyWindow(); delete m_over; //delete map delete m_dlgmap; // delete fonts _DestroyFonts(); } void DlgStats::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); //{{AFX_DATA_MAP(DlgStats) DDX_Check(pDX, IDC_SINGLECHART, m_singleChart[m_chartType]); DDX_Check(pDX, IDC_UNITS, m_seeUnits[m_chartType]); DDX_CBIndex(pDX, IDC_APMSTYLE, m_apmStyle[m_chartType]); DDX_CBIndex(pDX, IDC_CHARTTYPE, m_chartType); DDX_Control(pDX, IDC_PROGRESS1, m_progress); DDX_Control(pDX, IDC_GAMEDURATION, m_gamed); DDX_Control(pDX, IDC_DBLCLICK, m_dlbclick); DDX_Control(pDX, IDC_PLSTATS, m_plStats); DDX_Control(pDX, IDC_SCROLLBAR2, m_scrollerV); DDX_Control(pDX, IDC_SCROLLBAR1, m_scroller); DDX_Control(pDX, IDC_LISTEVENTS, m_listEvents); DDX_CBIndex(pDX, IDC_ZOOM, m_zoom); DDX_Check(pDX, IDC_MINERALS, m_seeMinerals); DDX_Check(pDX, IDC_GAZ, m_seeGaz); DDX_Check(pDX, IDC_SUPPLY, m_seeSupply); DDX_Check(pDX, IDC_ACTIONS, m_seeActions); DDX_Check(pDX, IDC_USESECONDS, m_useSeconds); DDX_Check(pDX, IDC_SPEED, m_seeSpeed); DDX_Check(pDX, IDC_UNITSONBO, m_seeUnitsOnBO); DDX_Text(pDX, IDC_EXACTTIME, m_exactTime); DDX_Check(pDX, IDC_BPM, m_seeBPM); DDX_Check(pDX, IDC_UPM, m_seeUPM); DDX_Check(pDX, IDC_HOTPOINTS, m_seeHotPoints); DDX_Check(pDX, IDC_PERCENTAGE, m_seePercent); DDX_Check(pDX, IDC_HKSELECT, m_viewHKselect); DDX_Check(pDX, IDC_FLT_SELECT, m_fltSelect); DDX_Check(pDX, IDC_FLT_CHAT, m_fltChat); DDX_Check(pDX, IDC_FLT_SUSPECT, m_fltSuspect); DDX_Check(pDX, IDC_FLT_HACK, m_fltHack); DDX_Check(pDX, IDC_FLT_TRAIN, m_fltTrain); DDX_Check(pDX, IDC_FLT_BUILD, m_fltBuild); DDX_Check(pDX, IDC_FLT_OTHERS, m_fltOthers); DDX_Text(pDX, IDC_SUSPECT_INFO, m_suspectInfo); DDX_Check(pDX, IDC_SORTDIST, m_sortDist); //}}AFX_DATA_MAP } //------------------------------------------------------------------------------------------------------------ void DlgStats::_CreateFonts() { // get system language LANGID lng = GetSystemDefaultLangID(); //if(lng==0x412) // korea //if(lng==0x0804) //chinese // retrieve a standard VARIABLE FONT from system HFONT hFont = (HFONT)GetStockObject( ANSI_VAR_FONT); CFont *pRefFont = CFont::FromHandle(hFont); LOGFONT LFont; // get font description memset(&LFont,0,sizeof(LOGFONT)); pRefFont->GetLogFont(&LFont); // create our label Font LFont.lfHeight = 18; LFont.lfWidth = 0; LFont.lfQuality|=ANTIALIASED_QUALITY; strcpy(LFont.lfFaceName,"Arial"); m_pLabelFont = new CFont(); m_pLabelFont->CreateFontIndirect(&LFont); // create our bold label Font LFont.lfWeight=700; m_pLabelBoldFont = new CFont(); m_pLabelBoldFont->CreateFontIndirect(&LFont); // create our layer Font pRefFont->GetLogFont(&LFont); LFont.lfHeight = 14; LFont.lfWidth = 0; LFont.lfQuality|=ANTIALIASED_QUALITY; strcpy(LFont.lfFaceName,"Arial"); m_pLayerFont = new CFont(); m_pLayerFont->CreateFontIndirect(&LFont); // create our small label Font LFont.lfHeight = 10; LFont.lfWidth = 0; LFont.lfQuality&=~ANTIALIASED_QUALITY; strcpy(LFont.lfFaceName,"Small Fonts"); m_pSmallFont = new CFont(); m_pSmallFont->CreateFontIndirect(&LFont); // create image list m_pImageList = new CImageList(); } //------------------------------------------------------------------------------------------------------------ void DlgStats::_DestroyFonts() { delete m_pLabelBoldFont; delete m_pLabelFont; delete m_pSmallFont; delete m_pLayerFont; delete m_pImageList; } //------------------------------------------------------------------------------------------------------------ // prepare list view void DlgStats::_PrepareListView() { UINT evCol[]={IDS_COL_TIME,IDS_COL_PLAYER,IDS_COL_ACTION,IDS_COL_PARAMETERS,0,IDS_COL_UNITSID}; int evWidth[]={50,115,80,180,20,180}; UINT stCol[]={IDS_COL_PLAYER,IDS_COL_ACTIONS,IDS_COL_APM,IDS_COL_NULL,IDS_COL_VAPM,IDS_COL_MINERAL,IDS_COL_GAS, IDS_COL_SUPPLY,IDS_COL_UNITS,IDS_COL_APMPM,IDS_COL_APMMAX,IDS_COL_APMMIN,IDS_COL_BASE,IDS_COL_MICRO,IDS_COL_MACRO}; int stWidth[]={115,50,40,35,45,50,50,50,50,50,60,60,40,40,45}; // Allow the header controls item to be movable by the user. // and set full row selection m_listEvents.SetExtendedStyle(m_listEvents.GetExtendedStyle()|LVS_EX_HEADERDRAGDROP+LVS_EX_FULLROWSELECT); CString colTitle; for(int i=0;i<sizeof(evCol)/sizeof(evCol[0]);i++) { if(evCol[i]!=0) colTitle.LoadString(evCol[i]); else colTitle=""; m_listEvents.InsertColumn(i, colTitle,LVCFMT_LEFT,evWidth[i],i); } // Set the background color COLORREF clrBack = RGB(255,255,255); m_listEvents.SetBkColor(clrBack); m_listEvents.SetTextBkColor(clrBack); m_listEvents.SetTextColor(RGB(10,10,10)); m_listEvents.SubclassHeaderControl(); // player stats m_plStats.SetExtendedStyle(m_plStats.GetExtendedStyle()|LVS_EX_HEADERDRAGDROP+LVS_EX_FULLROWSELECT); for(int i=0;i<sizeof(stCol)/sizeof(stCol[0]);i++) { if(stCol[i]!=0) colTitle.LoadString(stCol[i]); else colTitle=""; m_plStats.InsertColumn(i, colTitle,LVCFMT_LEFT,stWidth[i],i); } DlgBrowser::LoadColumns(&m_plStats,"plstats"); // Set the background color m_plStats.SetBkColor(clrBack); m_plStats.SetTextBkColor(clrBack); m_plStats.SetTextColor(RGB(10,10,10)); // create, initialize, and hook up image list m_pImageList->Create(16, 16, ILC_COLOR4, 2, 2); m_pImageList->SetBkColor(clrBack); // add icons CWinApp *pApp = AfxGetApp(); m_pImageList->Add(pApp->LoadIcon(IDI_ICON_DISABLE)); m_pImageList->Add(pApp->LoadIcon(IDI_ICON_OK)); m_plStats.SetImageList(m_pImageList, LVSIL_SMALL); } //------------------------------------------------------------------------------------------------------------ void DlgStats::UpdateBkgBitmap() { // re-init all pens for drawing all the charts _InitAllDrawingTools(); // load background bitmap if any Invalidate(); } //------------------------------------------------------------------------------------------------------------ BOOL DlgStats::OnInitDialog() { CDialog::OnInitDialog(); // init chart type CComboBox *charttype = (CComboBox *)GetDlgItem(IDC_CHARTTYPE); CString msg; msg.LoadString(IDS_CT_APM); charttype->AddString(msg); msg.LoadString(IDS_CT_RESOURCES); charttype->AddString(msg); msg.LoadString(IDS_CT_UNITDIST); charttype->AddString(msg); msg.LoadString(IDS_CT_ACTIONDIST); charttype->AddString(msg); msg.LoadString(IDS_CT_BUILDDIST); charttype->AddString(msg); msg.LoadString(IDS_CT_UPGRADES); charttype->AddString(msg); msg.LoadString(IDS_CT_APMDIST); charttype->AddString(msg); msg.LoadString(IDS_CT_BO); charttype->AddString(msg); msg.LoadString(IDS_CT_HOTKEYS); charttype->AddString(msg); msg.LoadString(IDS_CT_MAPCOVERGAGE); charttype->AddString(msg); msg.LoadString(IDS_CT_MIX_APMHOTKEYS); charttype->AddString(msg); charttype->SetCurSel(m_chartType); // prepare list view _PrepareListView(); // resize CRect rect; GetClientRect(&rect); _Resize(rect.Width(),rect.Height()); // update screen OnSelchangeCharttype(); // create map window m_dlgmap->Create(DlgMap::IDD,(CWnd*)this); // load some strings strDrop.LoadString(IDS_DROP); strExpand.LoadString(IDS_EXPAND); strLeave.LoadString(IDS_LEAVE); strMinGas.LoadString(IDS_MINGAS); strSupplyUnit.LoadString(IDS_SUPPLYUNIT); strMinimapPing.LoadString(IDS_MINIMAPPING); #ifndef NDEBUG GetDlgItem(IDC_TESTREPLAYS)->ShowWindow(SW_SHOW); #endif return TRUE; // return TRUE unless you set the focus to a control } //----------------------------------------------------------------------------------------------------------------- // If you add a minimize button to your dialog, you will need the code below // to draw the icon. For MFC applications using the document/view model, // this is automatically done for you by the framework. void DlgStats::OnPaint() { CPaintDC dc(this); // device context for painting if (!IsIconic()) { // fill chart background OPTIONSCHART->PaintBackground(&dc,m_boardRect); // draw tracking rect for vertical resizing CRect resizeRect; _GetResizeRect(resizeRect); resizeRect.DeflateRect(resizeRect.Width()/3,1); CRect resizeRect2(resizeRect); resizeRect2.right = resizeRect2.left+10; dc.Draw3dRect(&resizeRect2,RGB(220,220,220),RGB(180,180,180)); resizeRect2=resizeRect; resizeRect2.left = resizeRect2.right-10; dc.Draw3dRect(&resizeRect2,RGB(220,220,220),RGB(180,180,180)); // draw tracking rect for horizontal resizing _GetHorizResizeRect(resizeRect); resizeRect.DeflateRect(2,resizeRect.Height()/3); resizeRect2=resizeRect; resizeRect2.bottom = resizeRect2.top+10; dc.Draw3dRect(&resizeRect2,RGB(220,220,220),RGB(180,180,180)); resizeRect2=resizeRect; resizeRect2.top = resizeRect2.bottom-10; dc.Draw3dRect(&resizeRect2,RGB(220,220,220),RGB(180,180,180)); // paint charts if(m_replay.IsDone()) _PaintCharts(&dc); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_GetCursorRect(CRect& rect, unsigned long time, int width) { // only repaint around the time cursor rect = m_boardRect; rect.left += m_dataAreaX; float finc = (float)(rect.Width()-hleft-hright)/(float)(m_timeEnd - m_timeBegin); float fx=(float)(rect.left+hleft) + finc * (time-m_timeBegin); rect.right = width+(int)fx; rect.left = -width+(int)fx;; } //----------------------------------------------------------------------------------------------------------------- // bUserControl = true when the cursor is changed by the user // void DlgStats::_SetTimeCursor(unsigned long value, bool bUpdateListView, bool bUserControl) { // repaint current cursor zone CRect rect; _GetCursorRect(rect, m_timeCursor, 2); InvalidateRect(rect,FALSE); // update cursor m_timeCursor = value; _GetCursorRect(rect, m_timeCursor, 2); if(m_zoom>0 && (m_timeCursor<m_timeBegin || m_timeCursor>m_timeEnd)) { // the time window has changed, we must repaint everything _AdjustWindow(); rect = m_boardRect; } // update scroller m_scroller.SetScrollPos(value/HSCROLL_DIVIDER); // if we are animating if(m_bIsAnimating) { // if the animation timer is the one who changed the cursor if(!bUserControl) { // only repaint around the time cursor int width = 16 + m_animationSpeed; _GetCursorRect(rect, m_timeCursor, width); } else { // the user has changed the cursor during the animation // we must repaint everything rect = m_boardRect; } } // update map if(bUserControl) m_dlgmap->ResetTime(m_timeCursor); // repaint view InvalidateRect(rect,FALSE); // update list of events if(bUpdateListView) { // select corresponding line in list view unsigned long idx = _GetEventFromTime(m_timeCursor); m_lockListView=true; m_listEvents.SetItemState(idx,LVIS_SELECTED|LVIS_FOCUSED,LVIS_SELECTED|LVIS_FOCUSED); m_listEvents.EnsureVisible(idx,FALSE); m_lockListView=false; } // update exact time m_exactTime = _MkTime(m_replay.QueryFile()->QueryHeader(),value,true); UpdateData(FALSE); } //----------------------------------------------------------------------------------------------------------------- // display player stats void DlgStats::_DisplayPlayerStats() { m_plStats.DeleteAllItems(); // for each player for(int i=0; i<m_replay.GetPlayerCount(); i++) { // get event list ReplayEvtList *list = m_replay.GetEvtList(i); // insert player stats CString str; int nPos = m_plStats.InsertItem(i,list->PlayerName(), list->IsEnabled()?1:0); str.Format("%d",list->GetEventCount()); m_plStats.SetItemText(nPos,1,str); str.Format("%d",list->GetActionPerMinute()); m_plStats.SetItemText(nPos,2,str); str.Format("%d",list->GetDiscardedActions()); m_plStats.SetItemText(nPos,3,str); str.Format("%d",list->GetValidActionPerMinute()); m_plStats.SetItemText(nPos,4,str); str.Format("%d",list->ResourceMax().Minerals()); m_plStats.SetItemText(nPos,5,str); str.Format("%d",list->ResourceMax().Gaz()); m_plStats.SetItemText(nPos,6,str); str.Format("%d",(int)list->ResourceMax().Supply()); m_plStats.SetItemText(nPos,7,str); str.Format("%d",list->ResourceMax().Units()); m_plStats.SetItemText(nPos,8,str); str.Format("%d",list->GetStandardAPMDev(-1,-1)); m_plStats.SetItemText(nPos,9,str); str.Format("%d",list->ResourceMax().LegalAPM()); m_plStats.SetItemText(nPos,10,str); str.Format("%d",list->GetMiniAPM()); m_plStats.SetItemText(nPos,11,str); str.Format("%d",list->GetStartingLocation()); m_plStats.SetItemText(nPos,12,str); str.Format("%d",list->GetMicroAPM()); m_plStats.SetItemText(nPos,13,str); str.Format("%d",list->GetMacroAPM()); m_plStats.SetItemText(nPos,14,str); m_plStats.SetItemData(nPos,(DWORD)list); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::LoadReplay(const char *reppath, bool bClear) { CWaitCursor wait; // stop animation if any StopAnimation(); // clear list views if(bClear) m_listEvents.DeleteAllItems(); // update map m_dlgmap->UpdateReplay(0); // load replay if(m_replay.Load(reppath,true,&m_listEvents,bClear)!=0) { CString msg; msg.Format(IDS_CORRUPTEDBIS,reppath); MessageBox(msg,0,MB_OK|MB_ICONEXCLAMATION); return; } AfxGetApp()->WriteProfileString("MAIN","LASTREPLAY",reppath); SetDlgItemText(IDC_REPLAYFILE,reppath); // udpate suspect events counts CString chktitle; int suspectCount = m_replay.GetSuspectCount(); chktitle.Format(IDS_SUSPICIOUS,suspectCount); GetDlgItem(IDC_FLT_SUSPECT)->SetWindowText(chktitle); GetDlgItem(IDC_FLT_SUSPECT)->EnableWindow(suspectCount==0?FALSE:TRUE); // udpate hack events counts int hackCount = m_replay.GetHackCount(); chktitle.Format(IDS_HACK,hackCount); GetDlgItem(IDC_FLT_HACK)->SetWindowText(chktitle); GetDlgItem(IDC_FLT_HACK)->EnableWindow(hackCount==0?FALSE:TRUE); // update "next" button GetDlgItem(IDC_NEXT_SUSPECT)->EnableWindow((suspectCount+hackCount)==0?FALSE:TRUE); // display player stats _DisplayPlayerStats(); // init view m_maxPlayerOnBoard = m_replay.GetPlayerCount(); m_timeBegin = 0; m_timeCursor = 0; m_timeEnd = (m_chartType==BUILDORDER) ? m_replay.GetLastBuildOrderTime() : m_replay.GetEndTime(); m_scroller.SetScrollRange(0,m_timeEnd/HSCROLL_DIVIDER); // init all pens for drawing all the charts _InitAllDrawingTools(); // display game duration and game date CTime cdate; CString str; time_t date = m_replay.QueryFile()->QueryHeader()->getCreationDate(); if(localtime(&date)!=0) cdate = CTime(date); else cdate = CTime(1971,1,1,0,0,0); str.Format(IDS_MKDURATION,_MkTime(m_replay.QueryFile()->QueryHeader(),m_replay.GetEndTime(),true), (const char*)cdate.Format("%d %b %y")); SetDlgItemText(IDC_GAMEDURATION,str); // update map m_dlgmap->UpdateReplay(&m_replay); GetDlgItem(IDC_SEEMAP)->EnableWindow(m_replay.GetMapAnim()==0 ? FALSE :TRUE); if(m_replay.GetMapAnim()==0) m_dlgmap->ShowWindow(SW_HIDE); // init action filter _UpdateActionFilter(true); // update apm with current style m_replay.UpdateAPM(m_apmStyle[APM], m_apmStyle[MAPCOVERAGE]); //repaint Invalidate(FALSE); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnGetevents() { // get path CString path; if(!_GetReplayFileName(path)) return; // load replay LoadReplay(path,true); } //----------------------------------------------------------------------------------------------------------------- #define CHANGEPOS(id,x,y)\ {CWnd *wnd = GetDlgItem(id);\ if(wnd && ::IsWindow(wnd->GetSafeHwnd()))\ wnd->SetWindowPos(0,x,y,0,0,SWP_NOZORDER|SWP_NOSIZE);} #define CHANGEPOSSIZE(id,x,y,w,h)\ {CWnd *wnd = GetDlgItem(id);\ if(wnd && ::IsWindow(wnd->GetSafeHwnd()))\ wnd->SetWindowPos(0,x,y,w,h,SWP_NOZORDER);} void DlgStats::_Resize(int cx, int cy) { if(!::IsWindow(m_scroller)) return; // if window was reduced a lot, make sure event list width & height is not too big if(m_wlist==0) m_wlist=min(460,(80*cx/100)); if(m_wlist>(90*cx/100)) m_wlist = 90*cx/100; if(m_hlist>(70*cy/100)) m_hlist = 70*cy/100; int hlist=m_hlist; int wlist=m_wlist; // find position of lowest control on the top CRect rectCtrl; GetDlgItem(IDC_SPEED)->GetWindowRect(&rectCtrl); ScreenToClient(&rectCtrl); int top=rectCtrl.top+rectCtrl.Height()+8; int left=10; int right=16; int wlist2=cx - wlist - right-left-2; m_boardRect.SetRect(left,top,max(16,cx-left-right),max(top+16,cy-32-hlist)); // scrollers if(::IsWindow(m_scroller)) m_scroller.SetWindowPos(0,left,m_boardRect.bottom,m_boardRect.Width()-218,17,SWP_NOZORDER); if(::IsWindow(m_scrollerV)) m_scrollerV.SetWindowPos(0,m_boardRect.right,top,17,m_boardRect.Height(),SWP_NOZORDER); // event list if(::IsWindow(m_listEvents)) m_listEvents.SetWindowPos(0,m_boardRect.left,cy-hlist-8+20,wlist,hlist-40,SWP_NOZORDER); // cursor time CHANGEPOS(IDC_EXACTTIME,m_boardRect.Width()-200,m_boardRect.bottom+2); // filter check boxes CHANGEPOS(IDC_FLT_SELECT,8+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_BUILD,70+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_TRAIN,146+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_OTHERS,222+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_SUSPECT,280+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_HACK,380+m_boardRect.left,cy-hlist-8); CHANGEPOS(IDC_FLT_CHAT,480+m_boardRect.left,cy-hlist-8); CHANGEPOSSIZE(IDC_SUSPECT_INFO,8+m_boardRect.left,cy-22,wlist-70,12); CHANGEPOS(IDC_NEXT_SUSPECT,m_boardRect.left+wlist-58,cy-24); // player list if(::IsWindow(m_plStats)) m_plStats.SetWindowPos(0,m_boardRect.left+wlist+8,cy-hlist-8,wlist2,hlist-20,SWP_NOZORDER); // little help text if(::IsWindow(m_dlbclick)) m_dlbclick.SetWindowPos(0,m_boardRect.left+wlist+8,cy-20,0,0,SWP_NOZORDER|SWP_NOSIZE); // buttons CHANGEPOS(IDC_DHELP,m_boardRect.right-36,cy-22); CHANGEPOSSIZE(IDC_ANIMATE,m_boardRect.Width()-79,m_boardRect.bottom,49,17); CHANGEPOSSIZE(IDC_SEEMAP,m_boardRect.Width()-148,m_boardRect.bottom,69,17); CHANGEPOSSIZE(IDC_SPEEDPLUS,m_boardRect.Width()-30,m_boardRect.bottom,19,17); CHANGEPOSSIZE(IDC_SPEEDMINUS,m_boardRect.Width()-11,m_boardRect.bottom,19,17); CHANGEPOSSIZE(IDC_PAUSE,m_boardRect.Width()+8,m_boardRect.bottom,19,17); Invalidate(TRUE); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnSize(UINT nType, int cx, int cy) { CDialog::OnSize(nType, cx, cy); if(cx!=0 && cy!=0) _Resize(cx, cy); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintOneEvent(CDC *pDC, const CRect* pRect, const ReplayEvt *evt) { COLORREF m_color = evt->GetColor(); COLORREF oldColor = pDC->GetBkColor(); switch(m_shape) { case SQUARE: pDC->FillSolidRect(pRect,m_color); break; case RECTANGLE: pDC->Draw3dRect(pRect,m_color,m_color); break; case FLAG: case FLAGEMPTY: { CRect rect = *pRect; rect.bottom = rect.top+rect.Height()/2; rect.right = rect.left + (3*rect.Width())/4; if(m_shape==FLAG) pDC->FillSolidRect(&rect,m_color); else pDC->Draw3dRect(&rect,m_color,m_color); rect = *pRect; rect.right = rect.left+1; pDC->FillSolidRect(&rect,m_color); } break; case TEALEFT: case TEARIGHT: { CRect rect = *pRect; if(m_shape==TEALEFT) rect.right = rect.left+1; rect.left = rect.right-1; pDC->FillSolidRect(&rect,m_color); rect.right = pRect->right; rect.left = pRect->left; rect.top=pRect->top+pRect->Height()/2; rect.bottom = rect.top+1; pDC->FillSolidRect(&rect,m_color); } break; case TEATOP: case TEABOTTOM: { CRect rect = *pRect; if(m_shape==TEATOP) rect.bottom = rect.top+1; rect.top = rect.bottom-1; pDC->FillSolidRect(&rect,m_color); rect.top = pRect->top; rect.bottom = pRect->bottom; rect.left=pRect->left+pRect->Width()/2; rect.right = rect.left+1; pDC->FillSolidRect(&rect,m_color); } break; case ROUNDRECT: CPen pen(PS_SOLID,1,m_color); CBrush brush(m_color); CPen *oldPen = pDC->SelectObject(&pen); CBrush *oldBrush = pDC->SelectObject(&brush); pDC->RoundRect(pRect,CPoint(4,4)); pDC->SelectObject(oldBrush); pDC->SelectObject(oldPen); break; } pDC->SetBkColor(oldColor); } //----------------------------------------------------------------------------------------------------------------- DrawingTools* DlgStats::_GetDrawingTools(int player) { if(player>=0) return &m_dtools[player+1]; return &m_dtools[0]; } //----------------------------------------------------------------------------------------------------------------- // init all pens for drawing all the charts void DlgStats::_InitAllDrawingTools() { // init drawing tools for multiple frame mode _InitDrawingTools(-1,m_maxPlayerOnBoard,1); // init drawing tools for all players on one frame mode for(int i=0;i<m_maxPlayerOnBoard;i++) _InitDrawingTools(i,m_maxPlayerOnBoard,2); } //----------------------------------------------------------------------------------------------------------------- // init all pens for drawing the charts of one player void DlgStats::_InitDrawingTools(int player, int maxplayer, int /*lineWidth*/) { // clear tools DrawingTools *tools = _GetDrawingTools(player); tools->Clear(); // create pen for minerals for(int i=0; i<DrawingTools::maxcurve;i++) { int lineSize = ReplayResource::GetLineSize(i); tools->m_clr[i] = ReplayResource::GetColor(i,player,maxplayer); tools->m_penMineral[i] = new CPen(PS_SOLID,lineSize,tools->m_clr[i]); tools->m_penMineralS[i] = new CPen(PS_SOLID,1,tools->m_clr[i]); tools->m_penMineralDark[i] = new CPen(PS_SOLID,1,CHsvRgb::Darker(tools->m_clr[i],0.70)); } } //----------------------------------------------------------------------------------------------------------------- // draw a little text to show a hot point void DlgStats::_PaintHotPoint(CDC *pDC, int x, int y, const ReplayEvt *evt, COLORREF clr) { const char *hotpoint=0; const IStarcraftAction *action = evt->GetAction(); int off=8; //if event is a hack if(evt->IsHack()) { // make color lighter COLORREF clrt = RGB(255,0,0); // draw a little triangle there int off=3; CPen clr(PS_SOLID,1,clrt); CPen clr2(PS_SOLID,1,RGB(160,0,0)); CPen *old=(CPen*)pDC->SelectObject(&clr); for(int k=0;k<3;k++) { pDC->MoveTo(x-k,y-off-k); pDC->LineTo(x+k+1,y-off-k); } pDC->SelectObject(&clr2); for(int k=3;k<5;k++) { pDC->MoveTo(x-k,y-off-k); pDC->LineTo(x+k+1,y-off-k); } pDC->SelectObject(old); } // Expand? if(action->GetID()==BWrepGameData::CMD_BUILD) { int buildID = evt->UnitIdx(); if(buildID == BWrepGameData::OBJ_COMMANDCENTER || buildID == BWrepGameData::OBJ_HATCHERY || buildID == BWrepGameData::OBJ_NEXUS) hotpoint = strExpand; if(buildID == BWrepGameData::OBJ_COMMANDCENTER) { // make sure it's not just a "land" const BWrepActionBuild::Params *p = (const BWrepActionBuild::Params *)action->GetParamStruct(); if(p->m_buildingtype!=BWrepGameData::BTYP_BUILD) hotpoint=0; } } // Leave game? else if(action->GetID()==BWrepGameData::CMD_LEAVEGAME) { hotpoint = strLeave; } // Drop? else if(action->GetID()==BWrepGameData::CMD_UNLOAD || action->GetID()==BWrepGameData::CMD_UNLOADALL || (action->GetID()==BWrepGameData::CMD_ATTACK && evt->Type().m_subcmd==BWrepGameData::ATT_UNLOAD)) { hotpoint = strDrop; } // Minimap ping? else if(action->GetID()==BWrepGameData::CMD_MINIMAPPING) { hotpoint = strMinimapPing; } // no hot point? if(hotpoint==0) return; // previous hotpoint too close? if((x-lastHotPointX)<32 && lastHotPoint==hotpoint) return; // make color lighter clr = CHsvRgb::Darker(clr,1.5); // get text size int w = pDC->GetTextExtent(hotpoint).cx; CRect rectTxt(x-w/2-off,y-off,x+w/2-off,y-10-off); // draw text pDC->SetTextColor(clr); int omode = pDC->SetBkMode(TRANSPARENT); pDC->DrawText(hotpoint,&rectTxt,DT_SINGLELINE|DT_CENTER|DT_VCENTER); pDC->SetBkMode(omode); // draw joining line pDC->MoveTo(x-off,y-off); pDC->LineTo(x,y); lastHotPointX = x; lastHotPoint = hotpoint; } //----------------------------------------------------------------------------------------------------------------- // draw a local maximum void DlgStats::_DrawLocalMax(CDC *pDC, int rx, int ry, const COLORREF clr, int& lastMaxX, int maxval) { // if it's not too close to previous Max if(rx>lastMaxX+32) { // draw a little triangle there lastMaxX = rx; for(int k=0;k<5;k++) { pDC->MoveTo(rx-k,ry-3-k); pDC->LineTo(rx+k+1,ry-3-k); } // draw max value CRect rectTxt(rx-16,ry-20,rx+16,ry-10); CString strMax; strMax.Format("%d",maxval); CFont *oldFont=pDC->SelectObject(m_pSmallFont); COLORREF oldClr=pDC->SetTextColor(clr); int omode = pDC->SetBkMode(TRANSPARENT); pDC->DrawText(strMax,rectTxt,DT_CENTER|DT_SINGLELINE); pDC->SetBkMode(omode); pDC->SetTextColor(oldClr); pDC->SelectObject(oldFont); } } //----------------------------------------------------------------------------------------------------------------- static const double BWPI = 3.1415926535897932384626433832795; static double _CosineInterpolate(double y1,double y2,double mu) { double mu2 = (1-cos(mu*BWPI))/2; return(y1*(1-mu2)+y2*mu2); } //----------------------------------------------------------------------------------------------------------------- class CKnotArray { public: //ctor CKnotArray(int knotcount) : m_knotcount(knotcount) { m_knots = new CPoint*[ReplayResource::__CLR_MAX]; for(int i=0;i<ReplayResource::__CLR_MAX;i++) m_knots[i] = new CPoint[knotcount]; memset(m_isUsed,0,sizeof(m_isUsed)); } //dtor ~CKnotArray() { for(int i=0;i<ReplayResource::__CLR_MAX;i++) delete[]m_knots[i]; delete[]m_knots; } // access CPoint *GetKnots(int curveidx) const {return m_knots[curveidx];} int GetKnotCount() const {return m_knotcount;} bool IsUsed(int i) const {return m_isUsed[i];} void SetIsUsed(int i) {m_isUsed[i]=true;} private: CPoint **m_knots; int m_knotcount; bool m_isUsed[ReplayResource::__CLR_MAX]; }; //----------------------------------------------------------------------------------------------------------------- // draw resource lines for one resource slot void DlgStats::_PaintResources2(CDC *pDC, int ybottom, int cx, DrawingTools *tools, ReplayResource *res, unsigned long time, CKnotArray& knot, int knotidx) { static int rx[DrawingTools::maxcurve],ry[DrawingTools::maxcurve]; static int orx[DrawingTools::maxcurve],ory[DrawingTools::maxcurve]; // save all current points for(int j=0; j<ReplayResource::MaxValue(); j++) { orx[j] = rx[j]; ory[j] = ry[j]; } // for each resource type for(int j=0; j<ReplayResource::MaxValue(); j++) { if(j==0 && (!m_seeMinerals || m_chartType!=RESOURCES)) continue; if(j==1 && (!m_seeGaz || m_chartType!=RESOURCES)) continue; if(j==2 && (!m_seeSupply || m_chartType!=RESOURCES)) continue; if(j==3 && (!m_seeUnits[m_chartType] || m_chartType!=RESOURCES)) continue; if(j==4 && (m_chartType!=APM)) continue; if(j==5 && (!m_seeBPM || m_chartType!=APM)) continue; if(j==6 && (!m_seeUPM || m_chartType!=APM)) continue; if(j==7 && (m_chartType!=APM)) continue; // micro if(j==8) continue; if(j==9 && m_chartType!=MAPCOVERAGE) continue; if(j==10 && (!m_seeUnits[m_chartType] || m_chartType!=MAPCOVERAGE)) continue; // we had a previous point, move beginning of line on it CPoint firstpt(rx[j],ry[j]); if(!firstPoint) pDC->MoveTo(rx[j],ry[j]); // compute position rx[j] = cx; ry[j] = ybottom - (int)((float)(res->Value(j))*m_fvinc[j]); // use splines? bool nodraw=false; if(j<4 || j==9 || j==10 || (j==4 && !m_seeSpeed)) {knot.GetKnots(j)[knotidx]=CPoint(cx,ry[j]); knot.SetIsUsed(j); nodraw=true;} // if upm or bpm if(j==5 || j==6) { // paint upm / bpm bar int w = max(4,(int)m_finc); pDC->FillSolidRect(cx-w/2,ry[j],w,ybottom-ry[j],tools->m_clr[j]); } else { // paint segment for resource line if(!firstPoint) pDC->SelectObject(tools->m_penMineral[j]); if(!nodraw) { if(!firstPoint && j!=7) { // if segment is long enough, and not a straight line if(cx-firstpt.x>8 && firstpt.y!=ry[j]) { // interpolate it for(int x=firstpt.x;x<=cx;x++) { double mu = (double)(x-firstpt.x)/(double)(cx-firstpt.x); double y = _CosineInterpolate(firstpt.y,ry[j],mu); pDC->LineTo(x,(int)y); } } else pDC->LineTo(rx[j],ry[j]); } } // is it a max for APM? if(j==4 && OPTIONSCHART->m_maxapm && res->Value(j) == m_list->ResourceMax().LegalAPM() && time>=MINAPMVALIDTIMEFORMAX) _DrawLocalMax(pDC, rx[j], ry[j], tools->m_clr[j], lastMaxX, m_list->ResourceMax().LegalAPM()); // is it a max for MAP coverage? if(j==10 && OPTIONSCHART->m_maxapm && res->Value(j) == m_list->ResourceMax().MovingMapCoverage()) _DrawLocalMax(pDC, rx[j], ry[j], tools->m_clr[j], lastMaxX, m_list->ResourceMax().MovingMapCoverage()); } } // compute position rx[4] = cx; ry[4] = ybottom - (int)((float)(res->Value(4))*m_fvinc[4]); // if macro is on if(m_chartType==APM && m_seeSpeed && !firstPoint) { // paint surface POINT pt[4]; pt[0].x = orx[4]; pt[1].x = rx[4]; pt[2].x = rx[7]; pt[3].x = orx[7]; pt[0].y = ory[4]; pt[1].y = ry[4]; pt[2].y = ry[7]; pt[3].y = ory[7]; CBrush bkgpoly(tools->m_clr[4]); CBrush *oldb = pDC->SelectObject(&bkgpoly); pDC->SelectObject(tools->m_penMineral[4]); pDC->Polygon(pt, 4); pDC->SelectObject(oldb); // draw up and bottom lines in darker color for antialiasing //CPen penred(PS_SOLID,2,RGB(235,0,0)); //CPen pengreen(PS_SOLID,2,RGB(0,0,235)); pDC->SelectObject(tools->m_penMineralDark[4]); //pDC->SelectObject(&penred); pDC->MoveTo(pt[0].x,pt[0].y); pDC->LineTo(pt[1].x,pt[1].y); //pDC->SelectObject(&pengreen); pDC->MoveTo(pt[2].x,pt[2].y); pDC->LineTo(pt[3].x,pt[3].y); } firstPoint=false; } //----------------------------------------------------------------------------------------------------------------- // paint a spline curve void DlgStats::_PaintSpline(CDC *pDC, const CKnotArray& knots, int curveidx) { // compute control points CPoint* firstControlPoints=0; CPoint* secondControlPoints=0; BezierSpline::GetCurveControlPoints(knots.GetKnots(curveidx), knots.GetKnotCount(), firstControlPoints, secondControlPoints); // allocate point array for call to PolyBezier int ptcount = 3*(knots.GetKnotCount()-1)+1; POINT* pts = new POINT[ptcount]; for(int i=0;i<knots.GetKnotCount()-1;i++) { int step = i*3; pts[step]=knots.GetKnots(curveidx)[i]; pts[step+1]=firstControlPoints[i]; pts[step+2]=secondControlPoints[i]; } pts[ptcount-1]=knots.GetKnots(curveidx)[knots.GetKnotCount()-1]; // draw curve pDC->PolyBezier(pts,ptcount); // delete arrays delete[]pts; delete[]firstControlPoints; delete[]secondControlPoints; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintEvents(CDC *pDC, int chartType, const CRect& rect, const ReplayResource& resmax, int player) { // any event to draw? if(m_list->GetEventCount()==0) return; // compute all ratios depending on the max of every resource float rheight = (float)(rect.Height()-vtop-vbottom); m_fvinc[0] = m_fvinc[1] = rheight/(float)(max(resmax.Minerals(),resmax.Gaz())); m_fvinc[2] = m_fvinc[3] = rheight/(float)(max(resmax.Supply(),resmax.Units())); m_fvinc[4] = rheight/(float)resmax.APM(); m_fvinc[5] = rheight/((float)resmax.BPM()*4.0f); m_fvinc[6] = rheight/((float)resmax.UPM()*2.0f); m_fvinc[7] = rheight/(float)resmax.APM(); m_fvinc[8] = rheight/(float)(resmax.MacroAPM()*4); m_fvinc[9] = m_fvinc[10] = rheight/(float)(max(resmax.MapCoverage(),resmax.MovingMapCoverage())); m_finc = (float)(rect.Width()-hleft-hright)/(float)(m_timeEnd - m_timeBegin); // get drawing tools DrawingTools *tools = _GetDrawingTools(player); CPen *oldPen = (CPen*)pDC->SelectObject(tools->m_penMineral[0]); int oldMode = pDC->GetBkMode(); COLORREF oldclr = pDC->GetBkColor(); CFont *oldfont = pDC->SelectObject(m_pSmallFont); // where do we start painting? unsigned long timeBegin = m_timeBegin; //unsigned long timeBegin = m_bIsAnimating ? m_timeCursor : m_timeBegin; //if(m_timeCursor<500) timeBegin = 0; else timeBegin-=500; // reset last max data lastMaxX = 0; lastHotPointX = 0; lastHotPoint = 0; // for all resource slots firstPoint=true; int slotBegin = m_list->Time2Slot(m_timeBegin); int slotEnd = m_list->Time2Slot(m_timeEnd); // m_list->GetSlotCount() int slotCount = slotEnd-slotBegin; int divider = max(1,slotCount/gSplineCount[chartType]); int knotcount = slotCount==0 ? 0 : (slotCount/divider); CKnotArray *knots = knotcount==0 ? 0 : new CKnotArray(knotcount); for(int slot = slotBegin; slot<slotEnd; slot++) { // get resource object ReplayResource *res = m_list->GetResourceFromIdx(slot); unsigned long tick = m_list->Slot2Time(slot); // compute event position on X float fx=(float)(rect.left+hleft) + m_finc * (tick-m_timeBegin); int cx = (int)fx; // draw resource lines int knotslot = min(knotcount-1,(slot-slotBegin)/divider); _PaintResources2(pDC, rect.bottom - vbottom, cx, tools, res, tick, *knots, knotslot); } if(knots!=0) { // paint splines for(int i=0;i<ReplayResource::MaxValue();i++) if(knots->IsUsed(i)) { pDC->SelectObject(tools->m_penMineral[i]); _PaintSpline(pDC,*knots,i); } delete knots; } if(m_chartType==RESOURCES && (m_seeActions || (m_seeMinerals && m_seeHotPoints))) { // for each event in the current window, paint hot points int layer=0; unsigned long eventMax = (unsigned long)m_list->GetEventCount(); CRect rectEvt; firstPoint=true; lastMaxX = 0; lastHotPointX = 0; lastHotPoint = 0; for(unsigned long idx = m_list->GetEventFromTime(timeBegin);;idx++) { // get event description if(idx>=eventMax) break; const ReplayEvt *evt = m_list->GetEvent(idx); if(evt->Time()>m_timeEnd) break; // during animation, we only paint until cursor if(m_bIsAnimating && evt->Time()>m_timeCursor) break; // compute event position on X float fx=(float)(rect.left+hleft) + m_finc * (evt->Time()-m_timeBegin); int cx = (int)fx; // if we paint actions if(m_seeActions) { // compute event rect rectEvt.left=cx-evtWidth/2; rectEvt.right=cx+evtWidth/2; layer = m_replay.GetTypeIdx(evt); rectEvt.bottom=rect.bottom-vbottom-layer*layerHeight-(layerHeight-evtHeight)/2; rectEvt.top=rectEvt.bottom-evtHeight-(layerHeight-evtHeight)/2+1; if(rectEvt.top>rect.top) _PaintOneEvent(pDC,&rectEvt,evt); } // draw hot point (if any) firstPoint=false; if(m_seeMinerals && m_seeHotPoints && !evt->IsDiscarded()) { int y = rect.bottom-vbottom - (int)((float)(evt->Resources().Value(0))*m_fvinc[0]); pDC->SelectObject(tools->m_penMineralS[0]); _PaintHotPoint(pDC, cx, y, evt, tools->m_clr[0]); } } } else if(m_chartType==APM) { // for each event in the current window, paint hot points unsigned long eventMax = (unsigned long)m_list->GetEventCount(); CRect rectEvt; for(unsigned long idx = m_list->GetEventFromTime(timeBegin);;idx++) { // get event description if(idx>=eventMax) break; const ReplayEvt *evt = m_list->GetEvent(idx); if(evt->Time()>m_timeEnd) break; if(evt->ActionID()!=BWrepGameData::CMD_MESSAGE) continue; // during animation, we only paint until cursor if(m_bIsAnimating && evt->Time()>m_timeCursor) break; // compute event position on X float fx=(float)(rect.left+hleft) + m_finc * (evt->Time()-m_timeBegin); int cx = (int)fx; // if we paint actions if(m_seeHotPoints) { // compute event rect rectEvt.left=cx-evtWidth/2; rectEvt.right=cx+evtWidth/2; int layer = 0; rectEvt.bottom=rect.bottom-vbottom-layer*layerHeight-(layerHeight-evtHeight)/2; rectEvt.top=rectEvt.bottom-evtHeight-(layerHeight-evtHeight)/2+1; if(rectEvt.top>rect.top) _PaintOneEvent(pDC,&rectEvt,evt); } } } else if(m_chartType==MAPCOVERAGE) { } // restore every gdi stuff pDC->SelectObject(oldPen); pDC->SetBkMode(oldMode); pDC->SetBkColor(oldclr); pDC->SelectObject(oldfont); } //----------------------------------------------------------------------------------------------------------------- // compute vertical increment for grid and axis float DlgStats::_ComputeGridInc(unsigned long& tminc, unsigned long& maxres, const CRect& rect, const ReplayResource& resmax, int chartType, bool useGivenMax) const { if(!useGivenMax) { // compute max value switch(chartType) { case APM : maxres = resmax.APM(); break; case MAPCOVERAGE : maxres = max(resmax.MapCoverage(),resmax.MovingMapCoverage()); break; default: maxres = max(resmax.Minerals(),resmax.Gaz()); } } // compute vertical pixel per value float fvinc = (float)(rect.Height()-vbottom-vtop)/(float)(maxres); // compute grid increment tminc=((maxres/10)/1000)*1000; if(tminc==0) tminc=tminc=((maxres/10)/100)*100; if(tminc==0) tminc=((maxres/10)/10)*10; if(tminc==0) tminc=5; if(maxres<15) tminc=1; return fvinc; } void DlgStats::_PaintGrid(CDC *pDC, const CRect& rect, const ReplayResource& resmax) { if(!OPTIONSCHART->m_bggrid) return; // create pen for axis CPen *penGrid = new CPen(PS_DOT,1,clrGrid); CPen *oldPen = pDC->SelectObject(penGrid); int oldmode = pDC->SetBkMode(TRANSPARENT); // draw horizontal lines of grid unsigned long maxres = 0; unsigned long tminc; float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax,m_chartType); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { // draw grid float fy=(float)(rect.bottom-vbottom) - fvinc * tr; pDC->MoveTo(rect.left+hleft+1,(int)fy); pDC->LineTo(rect.right-hright,(int)fy); } // restore every gdi stuff pDC->SetBkMode(oldmode); pDC->SelectObject(oldPen); delete penGrid; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintActionsName(CDC *pDC, const CRect& rect) { if(!m_seeActions || m_chartType!=RESOURCES) return; // draw layers CString strNum; CRect rectTxt; CFont *oldFont = pDC->SelectObject(m_pLayerFont); // compute first layer rect CRect rectLayer=rect; rectLayer.top = rectLayer.bottom-layerHeight; rectLayer.OffsetRect(hleft,-vbottom); rectLayer.right-=hleft+hright; COLORREF bkc = pDC->GetBkColor(); // for each layer for(int k=0; k<m_replay.GetTypeCount();k++) { // fill layer rect COLORREF clrLayer = (k%2)==0 ? clrLayer1 : clrLayer2; pDC->FillSolidRect(&rectLayer,clrLayer); // draw layer action name clrLayer = (k%2)==0 ? clrLayerTxt1 : clrLayerTxt2; rectTxt = rectLayer; rectTxt.left+=28; rectTxt.right = rectTxt.left+128; pDC->SetTextColor(clrLayer); pDC->DrawText(m_replay.GetTypeStr(k),rectTxt,DT_LEFT|DT_SINGLELINE); //next layer rectLayer.OffsetRect(0,-layerHeight); if(rectLayer.bottom-layerHeight < rect.top) break; } // restore bkcolor pDC->SetBkColor(bkc); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintAxis(CDC *pDC, const CRect& rect, const ReplayResource& resmax, int mask, unsigned long timeBegin, unsigned long timeEnd) { // create pen for axis CPen *penTime = new CPen(PS_SOLID,1,clrTime); CPen *penAction = new CPen(PS_SOLID,1,clrAction); CPen *oldPen = (CPen*)pDC->SelectObject(penTime); int oldmode = pDC->SetBkMode(TRANSPARENT); // draw X axis values CString strNum; CRect rectTxt; float finc = timeEnd>timeBegin ? (float)(rect.Width()-hleft-hright)/(float)(timeEnd - timeBegin) : 0.0f; unsigned long tminc = 10; unsigned long maxres; while(timeEnd>timeBegin && (int)(tminc*finc)<50) tminc*=2; COLORREF oldClr = pDC->SetTextColor(clrTime); CFont *oldFont=pDC->SelectObject(m_pSmallFont); if(mask&MSK_XLINE && timeEnd>timeBegin) { for(unsigned long tm=timeBegin; tm<timeEnd; tm+=tminc) { float fx=(float)(rect.left+hleft) + finc * (tm-timeBegin); strNum = _MkTime(m_replay.QueryFile()->QueryHeader(),tm, m_useSeconds?true:false); int cx = (int)fx; // draw time rectTxt.SetRect(cx,rect.bottom-vbottom+2,cx+128,rect.bottom); pDC->DrawText(strNum,rectTxt,DT_LEFT|DT_SINGLELINE); // draw line pDC->MoveTo(cx,rect.bottom-vbottom-1); pDC->LineTo(cx,rect.bottom-vbottom+2); } } if((m_seeMinerals || m_seeGaz) && m_chartType==RESOURCES) { // draw left Y axis values (minerals and gas) int xpos = rect.left+hleft; float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType); if(mask&MSK_YLEFTLINE) { for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(xpos-1,cy); pDC->LineTo(xpos+2,cy); // draw time rectTxt.SetRect(rect.left+haxisleft,cy-8,rect.left+hleft-3,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw left Y axis title rectTxt.SetRect(rect.left+haxisleft,rect.top,rect.left+hleft+16,rect.top+16); pDC->DrawText(strMinGas,rectTxt,DT_LEFT|DT_SINGLELINE|DT_VCENTER); } } if((m_seeSupply || m_seeUnits[m_chartType]) && m_chartType==RESOURCES) { // draw right Y axis values (supply & units) if(mask&MSK_YRIGHTLINE) { maxres = resmax.Supply(); float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType,true); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(rect.right-hright-1,cy); pDC->LineTo(rect.right-hright+2,cy); // draw time rectTxt.SetRect(rect.right-hright-4-64,cy-8,rect.right-hright-4,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw right Y axis title rectTxt.SetRect(rect.right-hright-64,rect.top,rect.right-hright-4,rect.top+16); pDC->DrawText(strSupplyUnit,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } } if(m_chartType==APM) { pDC->SelectObject(penAction); pDC->SetTextColor(clrAction); // draw actions/minute Y axis values int xpos = rect.left+hleft; float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(xpos-1,cy); pDC->LineTo(xpos+2,cy); // draw time rectTxt.SetRect(rect.left+haxisleft,cy-8,rect.left+hleft-3,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw actions/minute Y axis title rectTxt.SetRect(rect.left+haxisleft,rect.top,rect.left+hleft-3,rect.top+16); pDC->DrawText("APM",rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); // draw right Y axis values (supply & units) if(mask&MSK_YRIGHTLINE) { fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(rect.right-hright-1,cy); pDC->LineTo(rect.right-hright+2,cy); // draw time rectTxt.SetRect(rect.right-hright-4-64,cy-8,rect.right-hright-4,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw right Y axis title rectTxt.SetRect(rect.right-hright-64,rect.top,rect.right-hright-4,rect.top+16); pDC->DrawText("APM",rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } } else if(m_chartType==MAPCOVERAGE) { pDC->SelectObject(penAction); pDC->SetTextColor(clrAction); // draw coverage Y axis values int xpos = rect.left+hleft; float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(xpos-1,cy); pDC->LineTo(xpos+2,cy); // draw time rectTxt.SetRect(rect.left+haxisleft,cy-8,rect.left+hleft-3,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw building map coverage Y axis title rectTxt.SetRect(rect.left+haxisleft,rect.top,rect.left+hleft-3,rect.top+16); pDC->DrawText("%Map",rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); if(m_seeUnits[m_chartType]) { // draw right Y axis values (unit map coverage) if(mask&MSK_YRIGHTLINE) { maxres = resmax.MovingMapCoverage(); float fvinc = _ComputeGridInc(tminc, maxres, rect, resmax, m_chartType,true); for(unsigned long tr=tminc; tr<(unsigned long)maxres; tr+=tminc) { float fy=(float)(rect.bottom-vbottom) - fvinc * tr; strNum.Format("%lu",tr); int cy = (int)fy; // draw line pDC->MoveTo(rect.right-hright-1,cy); pDC->LineTo(rect.right-hright+2,cy); // draw time rectTxt.SetRect(rect.right-hright-4-64,cy-8,rect.right-hright-4,cy+8); pDC->DrawText(strNum,rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } // draw right Y axis title rectTxt.SetRect(rect.right-hright-64,rect.top,rect.right-hright-4,rect.top+16); pDC->DrawText("%Map",rectTxt,DT_RIGHT|DT_SINGLELINE|DT_VCENTER); } } } // restore every gdi stuff pDC->SetBkMode(oldmode); pDC->SelectObject(oldPen); pDC->SetTextColor(oldClr); pDC->SelectObject(oldFont); delete penTime; delete penAction; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintAxisLines(CDC *pDC, const CRect& rect, int mask) { // create pen for axis CPen *penTime = new CPen(PS_SOLID,1,clrTime); CPen *oldPen = (CPen*)pDC->SelectObject(penTime); // draw X axis time line if(mask&MSK_XLINE) { pDC->MoveTo(rect.left+hleft,rect.bottom-vbottom); pDC->LineTo(rect.right-hright,rect.bottom-vbottom); } // draw left Y axis time line if(mask&MSK_YLEFTLINE) { pDC->MoveTo(rect.left+hleft,rect.bottom-vbottom); pDC->LineTo(rect.left+hleft,rect.top+vtop); } // draw right Y axis time line if(mask&MSK_YRIGHTLINE) { pDC->MoveTo(rect.right-hright,rect.bottom-vbottom); pDC->LineTo(rect.right-hright,rect.top+vtop); } // restore every gdi stuff pDC->SelectObject(oldPen); delete penTime; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintBackgroundLayer(CDC *pDC, const CRect& rect, const ReplayResource& resmax) { // draw horizontal lines of grid _PaintGrid(pDC, rect, resmax); // draw layers _PaintActionsName(pDC, rect); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintForegroundLayer(CDC *pDC, const CRect& rect, const ReplayResource& resmax, int mask) { // draw X & Yaxis time line _PaintAxisLines(pDC, rect, mask); // draw X & Y axis values _PaintAxis(pDC, rect, resmax,MSK_ALL,m_timeBegin,m_timeEnd); // draw cursor _PaintCursor(pDC, rect); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintMapName(CDC *pDC, CRect& rect) { if(m_chartType!=RESOURCES && m_chartType!=APM) return; // select font & color CFont *oldFont = pDC->SelectObject(m_pLabelBoldFont); int oldMode = pDC->SetBkMode(TRANSPARENT); // build title CString title(m_replay.MapName()); if(m_replay.RWAHeader()!=0) { CString audioby; audioby.Format(IDS_AUDIOCOMMENT,m_replay.RWAHeader()->author); title+=audioby; } //get title size with current font CSize sz = pDC->GetTextExtent(title); // draw text CRect rectTxt; rectTxt.SetRect(rect.left+hplayer,rect.top,rect.left+hplayer+sz.cx,rect.top+28); pDC->SetTextColor(OPTIONSCHART->GetColor(DlgOptionsChart::CLR_MAP)); pDC->DrawText(title,rectTxt,DT_LEFT|DT_SINGLELINE|DT_VCENTER); m_rectMapName = rectTxt; // restore pDC->SetBkMode(oldMode); pDC->SelectObject(oldFont); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintSentinel(CDC *pDC, CRect& rectTxt) { if(m_chartType!=RESOURCES && m_chartType!=APM) return; CString gamename = m_replay.QueryFile()->QueryHeader()->getGameName(); if(gamename.Left(11)=="BWSentinel ") { // select font & color CFont *oldFont = pDC->SelectObject(m_pSmallFont); int oldMode = pDC->SetBkMode(TRANSPARENT); // draw text pDC->SetTextColor(clrPlayer); pDC->DrawText("(sentinel on)",rectTxt,DT_LEFT|DT_SINGLELINE|DT_VCENTER); // restore pDC->SetBkMode(oldMode); pDC->SelectObject(oldFont); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintPlayerName(CDC *pDC, const CRect& rectpl, ReplayEvtList *list, int playerIdx, int playerPos, COLORREF clr, int offv) { CRect rect(rectpl); rect.OffsetRect(4,0); // select font & color CFont *oldFont = pDC->SelectObject(m_pLabelBoldFont); COLORREF oldClr = pDC->SetTextColor(clr); COLORREF bkClr = pDC->GetBkColor(); int oldMode = pDC->GetBkMode(); // draw player name CString pname; CRect rectTxt; pname.Format("%s (%s)",list->PlayerName(),list->GetRaceStr()); rectTxt.SetRect(rect.left+hplayer,rect.top+offv,rect.left+hplayer+200,rect.top+offv+28); if(playerPos>=0) rectTxt.OffsetRect(0,playerPos*28); if(m_chartType!=RESOURCES && m_chartType!=APM && m_mixedCount==0) rectTxt.OffsetRect(-hplayer+hleft,0); pDC->SetTextColor(clr); pDC->SetBkMode(TRANSPARENT); pDC->DrawText(pname,rectTxt,DT_LEFT|DT_SINGLELINE|DT_VCENTER); CRect rectRatio=rectTxt; // text size int afterText = pDC->GetTextExtent(pname).cx; // draw colors of resource lines if(playerIdx>=0) { rectTxt.top+=22; rectTxt.right=rectTxt.left+12; rectTxt.bottom=rectTxt.top+3; for(int j=0; j<ReplayResource::MaxValue(); j++) { if(j==0 && (!m_seeMinerals || m_chartType!=RESOURCES)) continue; if(j==1 && (!m_seeGaz || m_chartType!=RESOURCES)) continue; if(j==2 && (!m_seeSupply || m_chartType!=RESOURCES)) continue; if(j==3 && (!m_seeUnits[m_chartType] || m_chartType!=RESOURCES)) continue; if(j==4 && (!m_seeSpeed || m_chartType!=APM)) continue; if(j==5 && (!m_seeBPM || m_chartType!=APM)) continue; if(j==6 && (!m_seeUPM || m_chartType!=APM)) continue; if(j==7 || j==8) continue; pDC->FillSolidRect(&rectTxt,_GetDrawingTools(playerIdx)->m_clr[j]); rectTxt.OffsetRect(rectTxt.Width()+3,0); } } // add player info if(m_chartType>=UNITS && m_chartType<=UPGRADES) { // display distribution total pname.Format(IDS_TOTAL,list->GetDistTotal(m_chartType-UNITS)); } else { // display APM stuff //if(m_maxPlayerOnBoard==2) //{ // compute action ratio //ReplayEvtList *list1 = m_replay.GetEvtList(0); //ReplayEvtList *list2 = m_replay.GetEvtList(1); //float ratio = list==list1 ? (float)list1->GetEventCount()/(float)list2->GetEventCount() : (float)list2->GetEventCount()/(float)list1->GetEventCount(); //pname.Format("[%.2f, %d, %d APM]",ratio,list->GetEventCount(),list->GetActionPerMinute()); //} pname.Format("[%d actions APM=%d]",list->GetEventCount(),list->GetActionPerMinute()); } rectRatio.OffsetRect(afterText+8,0); pDC->SelectObject(m_pLayerFont); pDC->SetTextColor(clrRatio); pDC->SetBkColor(RGB(0,0,0)); pDC->SetBkMode(TRANSPARENT); pDC->DrawText(pname,rectRatio,DT_LEFT|DT_SINGLELINE|DT_VCENTER); // restore every gdi stuff pDC->SetBkMode(oldMode); pDC->SelectObject(oldFont); pDC->SetTextColor(oldClr); pDC->SetBkColor(bkClr); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintCursor(CDC *pDC, const CRect& rect) { // compute position float finc = (float)(rect.Width()-hleft-hright)/(float)(m_timeEnd - m_timeBegin); float fxc=(float)(rect.left+hleft) + finc * (m_timeCursor-m_timeBegin); // prepare pen CPen *penCursor = new CPen(PS_DOT,1,clrCursor); CPen *oldPen = pDC->SelectObject(penCursor); int oldmode = pDC->SetBkMode(TRANSPARENT); // draw cursor pDC->MoveTo((int)fxc,rect.top); pDC->LineTo((int)fxc,rect.bottom); // restore every gdi stuff pDC->SetBkMode(oldmode); pDC->SelectObject(oldPen); delete penCursor; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintBO(CDC *pDC, const CRect& rect, const ReplayObjectSequence& bo, int offset) { // draw building names int levelh = (rect.Height()-32-vplayer)/4; for(int i=0;i<bo.GetCount();i++) { float finc = (float)(rect.Width()-hleft-hright)/(float)(m_timeEnd - m_timeBegin); float fxc=(float)(rect.left+hleft) + finc * bo.GetTime(i); int y = rect.top+vplayer+16 + ((i+1)%4)*levelh + offset; pDC->MoveTo((int)fxc,y); pDC->LineTo((int)fxc,rect.bottom-vbottom); // text size CString pname = bo.GetName(i); int wText = pDC->GetTextExtent(pname).cx; CRect rectText; y-=16; rectText.SetRect((int)fxc-wText/2, y, (int)fxc+wText/2, y+16); rectText.InflateRect(1,1); pDC->DrawText(pname,rectText,DT_CENTER|DT_SINGLELINE|DT_VCENTER); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintBuildOrder(CDC *pDC, const CRect& rect) { // select font & color CFont *oldFont = pDC->SelectObject(m_pLayerFont); COLORREF oldClr = pDC->SetTextColor(clrBOName[0]); int oldMode = pDC->GetBkMode(); CPen *penCursor = new CPen(PS_SOLID,1,clrBOLine[0]); CPen *penCursor2 = new CPen(PS_SOLID,1,clrBOLine[1]); CPen *penCursor3 = new CPen(PS_SOLID,1,clrBOLine[2]); // draw X & Y axis values ReplayResource resmax; _PaintAxis(pDC, rect, resmax, MSK_XLINE,m_timeBegin,m_timeEnd); // draw building names CPen *oldPen = pDC->SelectObject(penCursor); pDC->SetBkMode(TRANSPARENT); _PaintBO(pDC, rect, m_list->GetBuildOrder(),0); // draw upgrades pDC->SetTextColor(clrBOName[2]); pDC->SelectObject(penCursor3); _PaintBO(pDC, rect, m_list->GetBuildOrderUpgrade(),10); // draw research pDC->SetTextColor(clrBOName[2]); pDC->SelectObject(penCursor3); _PaintBO(pDC, rect, m_list->GetBuildOrderResearch(),20); // draw units names if(m_seeUnitsOnBO) { pDC->SetTextColor(clrBOName[1]); pDC->SelectObject(penCursor2); _PaintBO(pDC, rect, m_list->GetBuildOrderUnits(),30); } // paint foreground layer (axis lines + cursor) _PaintForegroundLayer(pDC, rect, resmax, MSK_XLINE); // restore every gdi stuff pDC->SelectObject(oldPen); pDC->SelectObject(oldFont); pDC->SetTextColor(oldClr); pDC->SetBkMode(oldMode); delete penCursor3; delete penCursor2; delete penCursor; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_ComputeHotkeySymbolRect(const ReplayEvtList *list, const HotKeyEvent *hkevt, CRect& datarect, CRect& symRect) { // compute symbol position int levelhk = (datarect.Height()-8-vplayer)/10; float finc = (float)(datarect.Width()-hleft-hright)/(float)(m_timeEnd - m_timeBegin); float fxc=(float)(datarect.left+hleft) + finc * (hkevt->m_time - m_timeBegin); int y = datarect.top+vplayer + hkevt->m_slot*levelhk; int wText = 10; symRect.SetRect((int)fxc-wText/2, y, (int)fxc+wText/2, y+levelhk); symRect.InflateRect(2,2); symRect.DeflateRect(0,(levelhk-wText)/2); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintHotKeyEvent(CDC *pDC, CRect& datarect, int offset) { char text[3]; CRect symRect; // draw hotkey events for(int i=0;i<(int)m_list->GetHKEventCount();i++) { // get event const HotKeyEvent *hkevt = m_list->GetHKEvent(i); if(hkevt->m_time < m_timeBegin || hkevt->m_time > m_timeEnd) continue; // view hotkey selection? if(!m_viewHKselect && hkevt->m_type==HotKeyEvent::SELECT) continue; // compute symbol position _ComputeHotkeySymbolRect(m_list, hkevt, datarect, symRect); // text size sprintf(text,"%d", hkevt->m_slot==9?0:hkevt->m_slot+1); // draw text CRect rectText; pDC->SetTextColor(hkevt->m_type!=HotKeyEvent::ASSIGN ? RGB(100,0,100):RGB(0,0,0)); if(hkevt->m_type==HotKeyEvent::ASSIGN) pDC->FillSolidRect(symRect,RGB(100,0,200)); else if(hkevt->m_type==HotKeyEvent::ADD) pDC->Draw3dRect(symRect,RGB(100,0,200),RGB(100,0,200)); pDC->DrawText(text,symRect,DT_CENTER|DT_SINGLELINE|DT_VCENTER); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintHotKeys(CDC *pDC, const CRect& rectc) { // select font & color CFont *oldFont = pDC->SelectObject(m_pLayerFont); int oldMode = pDC->GetBkMode(); int oldbkClr = pDC->GetBkColor(); // height of a key strip int levelhk = (rectc.Height()-8-vplayer)/10; // offset rect CRect rect(rectc); rect.left += m_dataAreaX; // draw X & Y axis values ReplayResource resmax; _PaintAxis(pDC, rect, resmax, MSK_XLINE,m_timeBegin,m_timeEnd); // draw hotkey numbers pDC->SetBkMode(TRANSPARENT); int oldclr = pDC->SetTextColor(RGB(0,0,0)); COLORREF clrkey=RGB(255,255,0); COLORREF clrkeydark=CHsvRgb::Darker(clrkey,0.50); for(int i=0;i<10;i++) { // compute symbol position int y = rect.top+vplayer + i*levelhk; // text size CString hkslot; hkslot.Format("%d",i==9?0:i+1); // compute key rect CRect rectText; int wkey = min (24,levelhk-4); int hkey = (85*levelhk)/100; int delta = (levelhk-hkey)/2; rectText.SetRect(rect.left+6-m_dataAreaX,y+delta,0,y+hkey+delta); rectText.right = rectText.left + wkey; while(rectText.Width()<4) rectText.InflateRect(1,1); // fill key rect COLORREF clr = m_list->IsHotKeyUsed(i) ? clrkey : clrkeydark; //pDC->FillSolidRect(rectText,clr); Gradient::Fill(pDC,rectText,clr,CHsvRgb::Darker(clr,0.70)); pDC->Draw3dRect(rectText,clr,CHsvRgb::Darker(clr,0.80)); // draw text pDC->DrawText(hkslot,rectText,DT_CENTER|DT_SINGLELINE|DT_VCENTER); } // draw hotkey events _PaintHotKeyEvent(pDC, rect,0); // paint foreground layer (axis lines + cursor) _PaintForegroundLayer(pDC, rect, resmax, MSK_XLINE); // restore rect rect.left -= m_dataAreaX; // restore every gdi stuff pDC->SetBkMode(oldMode); pDC->SetTextColor(oldclr); pDC->SetBkColor(oldbkClr); } //----------------------------------------------------------------------------------------------------------------- static int _gType; static ReplayEvtList* _gList; static int _gCompareElements( const void *arg1, const void *arg2 ) { int i1 = *((int*)arg1); int i2 = *((int*)arg2); return _gList->GetDistCount(_gType,i2)-_gList->GetDistCount(_gType,i1); } void DlgStats::_PaintDistribution(CDC *pDC, const CRect& rect, int type) { //empty distribution? if(m_list->GetDistTotal(type)==0) return; // select font & color CFont *oldFont = pDC->SelectObject(m_pLabelFont); COLORREF oldClr = pDC->SetTextColor(clrUnitName); COLORREF bkClr = pDC->GetBkColor(); // compute number of non null elements in the distribution int elemcount=m_list->GetDistNonNullCount(type); int dvalmax = m_seePercent ? 50 : m_replay.GetDistPeak(type); // skip elements with 0.0% count if(m_seePercent) { for(int i=0; i<m_list->GetDistMax(type); i++) { int dval = (100*m_list->GetDistCount(type,i))/m_list->GetDistTotal(type); if(dval>dvalmax) dvalmax=dval; if(m_list->GetDistCount(type,i)>0 && dval==0) elemcount--; } } // compute bar height CRect barRect = rect; barRect.top+=32; barRect.DeflateRect(hleft,0); int barHeight = elemcount==0 ? 0 : min(40,barRect.Height()/elemcount); // select adequate font pDC->SelectObject((barHeight<18) ? ((barHeight<10) ? m_pSmallFont : m_pLayerFont) : m_pLabelFont); int barStart = 150; //(barHeight<18) ? ((barHeight<10) ? 80 : 110) : 150; // create array of pointer to distribution elements int *elemIdx = new int[m_list->GetDistMax(type)]; int j=0; for(int i=0; i<m_list->GetDistMax(type); i++) { // skip elements with 0 count if(m_list->GetDistCount(type,i)==0) continue; // skip elements with 0.0% count if(m_seePercent && (100*m_list->GetDistCount(type,i))/m_list->GetDistTotal(type)==0) continue; elemIdx[j]=i; j++; } // sort array if(m_sortDist) { _gType=type; _gList=m_list; qsort(elemIdx,j,sizeof(int),_gCompareElements); } // for each element CString val; barRect.bottom = barRect.top + barHeight; int barSpacing = (15*barHeight)/100; //for(int i=0; i<m_list->GetDistMax(type); i++) for(int k=0; k<j; k++) { int i=elemIdx[k]; /* // skip elements with 0 count if(m_list->GetDistCount(type,i)==0) continue; // skip elements with 0.0% count if(m_seePercent && (100*m_list->GetDistCount(type,i))/m_list->GetDistTotal(type)==0) continue; */ // display element name //pDC->SetBkColor(RGB(0,0,0)); pDC->SetBkMode(TRANSPARENT); pDC->SetTextColor(clrUnitName); pDC->DrawText(m_list->GetDistName(type,i),barRect,DT_LEFT|DT_SINGLELINE|DT_VCENTER); // what value int dval = m_seePercent ? (100*m_list->GetDistCount(type,i))/m_list->GetDistTotal(type) : m_list->GetDistCount(type,i); // draw bar int barWidth = dval*(barRect.Width() - (barStart+42))/dvalmax; CRect zbar=barRect; zbar.DeflateRect(barStart,barSpacing,0,barSpacing); zbar.right =zbar.left+barWidth; COLORREF clr = m_list->GetDistColor(type,i); Gradient::Fill(pDC,&zbar,clr,CHsvRgb::Darker(clr,0.6),GRADIENT_FILL_RECT_V); //pDC->FillSolidRect(&zbar,clr); // draw value if(m_seePercent) { /* if(dval==0) { double fval = (100.0*m_list->GetDistCount(type,i))/m_list->GetDistTotal(type); val.Format("%.1f%%",fval); } else */ val.Format("%d%%",dval); } else val.Format("%d",dval); pDC->SetTextColor(clrUnitName); int oldMode=pDC->SetBkMode(TRANSPARENT); zbar.left=zbar.right+4; zbar.right+=42; pDC->DrawText(val,zbar,DT_LEFT|DT_SINGLELINE|DT_VCENTER); pDC->SetBkMode(oldMode); // next element barRect.OffsetRect(0,barHeight); } delete[]elemIdx; // restore every gdi stuff pDC->SelectObject(oldFont); pDC->SetTextColor(oldClr); pDC->SetBkColor(bkClr); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_GetDataRectForPlayer(int plidx, CRect& rect, int pcount) { assert(pcount>0); rect = m_boardRect; rect.bottom = rect.top+rect.Height()/pcount; rect.OffsetRect(0,rect.Height()*plidx); } //----------------------------------------------------------------------------------------------------------------- // paint one chart for one player void DlgStats::_PaintChart(CDC *pDC, int chartType, const CRect& rect, int minMargin) { //what kind of chart do we paint? hleft = max(minMargin,6); if(chartType==BUILDORDER) { // build order _PaintBuildOrder(pDC,rect); } else if(chartType==HOTKEYS) { // build hotkeys _PaintHotKeys(pDC,rect); } else if(chartType!=RESOURCES && chartType!=MAPCOVERAGE && chartType!=APM) { // any distribution _PaintDistribution(pDC,rect,chartType-2); } else { hleft = max(minMargin,30); // paint background layer _PaintBackgroundLayer(pDC, rect, m_list->ResourceMax()); // draw selected events & resources _PaintEvents(pDC, chartType, rect, m_list->ResourceMax()); // paint foreground layer _PaintForegroundLayer(pDC, rect, m_list->ResourceMax()); } // draw player name _PaintPlayerName(pDC, rect, m_list, -1, -1, clrPlayer); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintMultipleCharts(CDC *pDC) { m_rectMapName.SetRectEmpty(); // for each player on board CRect rect; m_shape = SQUARE; for(int i=0,j=0; i<m_replay.GetPlayerCount() && j<m_maxPlayerOnBoard; i++) { // get event list for that player m_list = m_replay.GetEvtList(i); if(!m_list->IsEnabled()) continue; // get rect for the player's charts _GetDataRectForPlayer(j, rect, m_maxPlayerOnBoard); // paint one chart for one player _PaintChart(pDC, m_chartType, rect); // offset shape for next player m_shape=(eSHAPE)((int)m_shape+1); j++; } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintMixedCharts(CDC *pDC, int playerIdx, int *chartType, int count) { m_rectMapName.SetRectEmpty(); // for required chart CRect rect; m_shape = SQUARE; m_mixedCount=count; m_MixedPlayerIdx=playerIdx; for(int i=0; i<count; i++) { // get event list for that player m_list = m_replay.GetEvtList(playerIdx); // get rect for the chart _GetDataRectForPlayer(i, rect, count); // paint one chart int ctype = m_chartType; m_chartType = chartType[i]; _PaintChart(pDC, chartType[i], rect, 35); m_mixedRect[i]=rect; m_mixedChartType[i]=m_chartType; m_chartType=ctype; } } //----------------------------------------------------------------------------------------------------------------- // get index of first enabled player int DlgStats::_GetFirstEnabledPlayer() const { // for each player on board for(int i=0; i<m_replay.GetPlayerCount(); i++) if(m_replay.GetEvtList(i)->IsEnabled()) return i; return 0; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintSingleChart(CDC *pDC) { CRect rect = m_boardRect; hleft = 30; // paint background layer _PaintBackgroundLayer(pDC, rect, m_replay.ResourceMax()); // for each player on board m_shape = SQUARE; for(int i=0,j=0; j<m_maxPlayerOnBoard; i++) { // get event list for that player m_list = m_replay.GetEvtList(i); if(!m_list->IsEnabled()) continue; // draw selected events & resources _PaintEvents(pDC, m_chartType, rect, m_replay.ResourceMax(),i); m_shape=(eSHAPE)((int)m_shape+1); j++; } // paint foreground layer _PaintForegroundLayer(pDC, rect, m_replay.ResourceMax()); // paint map name _PaintMapName(pDC,rect); int offv = vplayer-8; // draw players name for(int i=0,j=0; j<m_maxPlayerOnBoard; i++) { // get event list for that player ReplayEvtList* list = m_replay.GetEvtList(i); if(!list->IsEnabled()) continue; _PaintPlayerName(pDC, rect, list, i,j, clrPlayer,offv); j++; } // paint sentinel logo if needed rect.SetRect(rect.left+hplayer+220,rect.top,rect.left+hplayer+280,rect.top+28); _PaintSentinel(pDC, rect); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintCheckBoxColor(CDC *pDC) { UINT cid[]={IDC_MINERALS,IDC_GAZ,IDC_SUPPLY,IDC_UNITS}; for(int i=0;i<sizeof(cid)/sizeof(cid[0]);i++) { CRect rect; GetDlgItem(cid[i])->GetWindowRect(&rect); ScreenToClient(&rect); rect.OffsetRect(-8,0); rect.DeflateRect(0,2); rect.right = rect.left+6; rect.top--; pDC->FillSolidRect(&rect,_GetDrawingTools(0)->m_clr[i]); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_PaintCharts(CDC *pDC) { m_maxPlayerOnBoard = min(MAXPLAYERONVIEW,m_replay.GetEnabledPlayerCount()); if(m_maxPlayerOnBoard>0) { if(m_chartType==MIX_APMHOTKEYS) { int ctype[]={APM,HOTKEYS}; _PaintMixedCharts(pDC,_GetFirstEnabledPlayer(),ctype,sizeof(ctype)/sizeof(ctype[0])); } else if(!m_singleChart[m_chartType] || (m_chartType!=RESOURCES && m_chartType!=APM && m_chartType!=MAPCOVERAGE)) _PaintMultipleCharts(pDC); else _PaintSingleChart(pDC); _PaintCheckBoxColor(pDC); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_SelectAction(int idx) { // update selected player char szPlayerName[128]; m_listEvents.GetItemText(idx,1,szPlayerName,sizeof(szPlayerName)); for(int i=0; i<m_replay.GetPlayerCount(); i++) if(_stricmp(m_replay.GetEvtList(i)->PlayerName(),szPlayerName)==0) {m_selectedPlayer = i; break;} // update current cursor pos ReplayEvt *evt = _GetEventFromIdx(idx); _SetTimeCursor(evt->Time(),false); // suspect event? GetDlgItem(IDC_SUSPECT_INFO)->SetWindowText(""); if(evt->IsSuspect()) { CString origin; ReplayEvtList *list = (ReplayEvtList *)evt->GetAction()->GetUserData(0); list->GetSuspectEventOrigin(evt->GetAction(),origin,m_useSeconds?true:false); GetDlgItem(IDC_SUSPECT_INFO)->SetWindowText(origin); } // remember selected action index m_selectedAction = idx; } //--------------------------------------------------------------------------------------- void DlgStats::OnItemchangedListevents(NMHDR* pNMHDR, LRESULT* pResult) { NM_LISTVIEW* pNMListView = (NM_LISTVIEW*)pNMHDR; if(pNMListView->uNewState&(LVIS_SELECTED+LVIS_FOCUSED) && !m_lockListView && (pNMListView->iItem!=-1)) { // update selected player & cursor pos _SelectAction(pNMListView->iItem); } *pResult = 0; } //--------------------------------------------------------------------------------------- inline unsigned long DlgStats::_GetActionCount() { return m_replay.GetEnActionCount();//(unsigned long)m_replay.QueryFile()->QueryActions()->GetActionCount(); } //--------------------------------------------------------------------------------------- ReplayEvt * DlgStats::_GetEventFromIdx(unsigned long idx) { assert(idx<_GetActionCount()); const IStarcraftAction *action = m_replay.GetEnAction(idx); //m_replay.QueryFile()->QueryActions()->GetAction(idx); ReplayEvtList *list = (ReplayEvtList *)action->GetUserData(0); ReplayEvt *evt = list->GetEvent(action->GetUserData(1)); return evt; } //--------------------------------------------------------------------------------------- // cursor = value between 0 and full span time // will find the nearest event unsigned long DlgStats::_GetEventFromTime(unsigned long cursor) { unsigned long eventCount = _GetActionCount(); if(eventCount==0) return 0; unsigned long nSlot = 0; unsigned long low = 0; unsigned long high = eventCount - 1; unsigned long beginTimeTS = 0; unsigned long i; unsigned long eventTime; // for all events in the list while(true) { i= (high+low)/2; ASSERT(high>=low); // are we beyond the arrays boundaries? if(i>=eventCount) {nSlot=0;break;} // get event time ReplayEvt *evt = _GetEventFromIdx(i); eventTime = evt->Time(); // compare times LONGLONG delta = eventTime-beginTimeTS; LONGLONG nCmp = (LONGLONG )cursor - delta; // if event time is the same, return index if(nCmp==0) { nSlot = i; goto Exit; } else if(nCmp<0) { if(high==low) {nSlot = low; break;} high = i-1; if(high<low) {nSlot=low; break;} if(high<0) {nSlot=0; break;} } else { if(high==low) {nSlot = low+1; break;} low = i+1; if(low>high) {nSlot=high; break;} if(low>=eventCount-1) {nSlot=eventCount-1; break;} } } ASSERT(nSlot<eventCount); Exit: // make sure event belong to the right player char szPlayerName[128]; int nSlotBegin=nSlot; for(;nSlot<eventCount;) { // get event time ReplayEvt *evt = _GetEventFromIdx(nSlot); assert(evt!=0); if(evt->Time()>cursor) break; m_listEvents.GetItemText(nSlot,1,szPlayerName,sizeof(szPlayerName)); if(strcmp(m_replay.GetEvtList(m_selectedPlayer)->PlayerName(),szPlayerName)!=0) nSlot++; else break; } if(nSlot>=eventCount) nSlot=nSlotBegin; else { ReplayEvt *evt = _GetEventFromIdx(nSlot); if(evt->Time()>cursor) nSlot=nSlotBegin; } return nSlot; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_AdjustWindow() { unsigned long windowWidth = (unsigned long)((double)m_replay.GetEndTime()/pow(2.0f,m_zoom)); if(m_timeCursor<windowWidth/2) { m_timeBegin = 0; m_timeEnd = windowWidth; } else if(m_timeCursor+windowWidth/2>m_replay.GetEndTime()) { m_timeBegin = m_replay.GetEndTime()-windowWidth; m_timeEnd = m_replay.GetEndTime(); } else { m_timeBegin = m_timeCursor-windowWidth/2; m_timeEnd = m_timeCursor+windowWidth/2; } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnSelchangeZoom() { UpdateData(TRUE); if(m_zoom==0) { m_timeBegin = 0; m_timeEnd = m_replay.GetEndTime(); } else { _AdjustWindow(); } Invalidate(FALSE); } //-------------------------------------------------------------------------------- BOOL DlgStats::_OnScroll(UINT nScrollCode, UINT nPos, BOOL bDoScroll) { // calc new x position int x = m_scroller.GetScrollPos(); int xOrig = x; switch (LOBYTE(nScrollCode)) { case SB_TOP: x = 0; break; case SB_BOTTOM: x = INT_MAX; break; case SB_LINEUP: x -= m_lineDev.cx; break; case SB_LINEDOWN: x += m_lineDev.cx; break; case SB_PAGEUP: x -= m_pageDev.cx; break; case SB_PAGEDOWN: x += m_pageDev.cx; break; case SB_THUMBTRACK: x = nPos; break; } // calc new y position int y = m_scrollerV.GetScrollPos(); int yOrig = y; switch (HIBYTE(nScrollCode)) { case SB_TOP: y = 0; break; case SB_BOTTOM: y = INT_MAX; break; case SB_LINEUP: y -= m_lineDev.cy; break; case SB_LINEDOWN: y += m_lineDev.cy; break; case SB_PAGEUP: y -= m_pageDev.cy; break; case SB_PAGEDOWN: y += m_pageDev.cy; break; case SB_THUMBTRACK: y = nPos; break; } BOOL bResult = _OnScrollBy(CSize(x - xOrig, y - yOrig), bDoScroll); /* if (bResult && bDoScroll) { Invalidate(); UpdateWindow(); } */ return bResult; } //------------------------------------------------------------------------------------------ BOOL DlgStats::_OnScrollBy(CSize sizeScroll, BOOL bDoScroll) { int xOrig, x; int yOrig, y; // don't scroll if there is no valid scroll range (ie. no scroll bar) CScrollBar* pBar; DWORD dwStyle = GetStyle(); pBar = &m_scrollerV; if ((pBar != NULL && !pBar->IsWindowEnabled()) || (pBar == NULL && !(dwStyle & WS_VSCROLL))) { // vertical scroll bar not enabled sizeScroll.cy = 0; } pBar = &m_scroller; if ((pBar != NULL && !pBar->IsWindowEnabled()) || (pBar == NULL && !(dwStyle & WS_HSCROLL))) { // horizontal scroll bar not enabled sizeScroll.cx = 0; } // adjust current x position xOrig = x = m_scroller.GetScrollPos(); //int xMax = GetScrollLimit(SB_HORZ); int xMax, xMin ; m_scroller.GetScrollRange(&xMin,&xMax) ; x += sizeScroll.cx; if (x < xMin) x = xMin; else if (x > xMax) x = xMax; // adjust current y position yOrig = y = m_scrollerV.GetScrollPos(); //int yMax = GetScrollLimit(SB_VERT); int yMax, yMin ; m_scrollerV.GetScrollRange(&yMin,&yMax) ; y += sizeScroll.cy; if (y < 0) y = 0; else if (y > yMax) y = yMax; // did anything change? if (x == xOrig && y == yOrig) return FALSE; if (bDoScroll) { // do scroll and update scroll positions if (x != xOrig) { _SetTimeCursor(x*HSCROLL_DIVIDER); } if (y != yOrig) { m_scrollerV.SetScrollPos(y); //??????????? } } return TRUE; } //--------------------------------------------------------------------------------------- void DlgStats::OnHScroll(UINT nSBCode, UINT nPos, CScrollBar* pScrollBar) { _OnScroll(MAKEWORD(nSBCode, -1), nPos, TRUE); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnUpdateChart() { BOOL oldUseSeconds = m_useSeconds; UpdateData(TRUE); InvalidateRect(&m_boardRect,FALSE); if(oldUseSeconds != m_useSeconds) m_listEvents.Invalidate(); } //------------------------------------------------------------------------------------- void DlgStats::_UpdateActionFilter(bool refresh) { // compute filter int filter=0; if(m_fltSelect) filter+=Replay::FLT_SELECT; if(m_fltBuild) filter+=Replay::FLT_BUILD; if(m_fltTrain) filter+=Replay::FLT_TRAIN; if(m_fltSuspect) filter+=Replay::FLT_SUSPECT; if(m_fltHack) filter+=Replay::FLT_HACK; if(m_fltOthers) filter+=Replay::FLT_OTHERS; if(m_fltChat) filter+=Replay::FLT_CHAT; m_replay.UpdateFilter(filter); // update list view if(refresh) { m_listEvents.SetItemCountEx(m_replay.GetEnActionCount(), LVSICF_NOSCROLL|LVSICF_NOINVALIDATEALL); m_listEvents.Invalidate(); } } //------------------------------------------------------------------------------------- void DlgStats::_ToggleIgnorePlayer() { POSITION pos = m_plStats.GetFirstSelectedItemPosition(); if(pos!=0) { // get selected item int nItem = m_plStats.GetNextSelectedItem(pos); ReplayEvtList *list = (ReplayEvtList *)m_plStats.GetItemData(nItem); if(list!=0) { // enable/disable player m_replay.EnablePlayer(list,list->IsEnabled()?false:true); LVITEM item = {LVIF_IMAGE ,nItem,0,0,0,0,0,list->IsEnabled()?1:0,0,0}; m_plStats.SetItem(&item); // update list view int nItem=-1; m_listEvents.SetItemCountEx(m_replay.GetEnActionCount(), LVSICF_NOSCROLL|LVSICF_NOINVALIDATEALL); m_listEvents.Invalidate(); /* POSITION pos = m_listEvents.GetFirstSelectedItemPosition(); if (pos != NULL) nItem = pList->GetNextSelectedItem(pos); //if(nItem>=m_replay.GetEnActionCount()) m_listEvents.SnItem=m_replay.GetEnActionCount()-1; */ //repaint InvalidateRect(m_boardRect,TRUE); // update map m_dlgmap->UpdateReplay(&m_replay); } } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnEnableDisable() { _ToggleIgnorePlayer(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnDblclkPlstats(NMHDR* pNMHDR, LRESULT* pResult) { _ToggleIgnorePlayer(); *pResult = 0; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnDestroy() { // if we are on pause, unpause if(m_prevAnimationSpeed!=0) OnPause(); // save parameters _Parameters(false); DlgBrowser::SaveColumns(&m_plStats,"plstats"); CDialog::OnDestroy(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnSelchangeCharttype() { static bool gbTimeWndHasChanged = false; OnUpdateChart(); // update shared "single chart" checkbox CButton *btn = (CButton *)GetDlgItem(IDC_SINGLECHART); btn->SetCheck(m_singleChart[m_chartType]); btn->EnableWindow((m_chartType==RESOURCES || m_chartType==APM || m_chartType==MAPCOVERAGE)?TRUE:FALSE); // update shared "see units" checkbox btn = (CButton *)GetDlgItem(IDC_UNITS); btn->SetCheck(m_seeUnits[m_chartType]); btn->EnableWindow((m_chartType==RESOURCES || m_chartType==MAPCOVERAGE)?TRUE:FALSE); // update shared "apm style" combo box CComboBox *cbx = (CComboBox *)GetDlgItem(IDC_APMSTYLE); cbx->SetCurSel(m_apmStyle[m_chartType]); cbx->EnableWindow((m_chartType==APM || m_chartType==MAPCOVERAGE)?TRUE:FALSE); m_dataAreaX = 0; m_mixedCount=0; m_MixedPlayerIdx=0; // shall we restore the full timeline? if(gbTimeWndHasChanged) { m_timeBegin = 0; m_timeEnd = m_replay.GetEndTime(); gbTimeWndHasChanged = false; m_zoom=0; UpdateData(FALSE); } switch(m_chartType) { case MAPCOVERAGE: { // disable useless options UINT disable[]={IDC_ANIMATE,IDC_PERCENTAGE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY, IDC_SORTDIST, IDC_SPEED,IDC_BPM,IDC_UPM,IDC_ACTIONS,IDC_HOTPOINTS,IDC_UNITSONBO,IDC_HKSELECT}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); // enable useful options UINT enable[]={IDC_USESECONDS,IDC_ZOOM,IDC_UNITS,IDC_APMSTYLE}; for(int i=0;i<sizeof(enable)/sizeof(enable[0]);i++) GetDlgItem(enable[i])->EnableWindow(TRUE); } break; case MIX_APMHOTKEYS: { m_dataAreaX = 0; // disable useless options UINT disable[]={IDC_PERCENTAGE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY, IDC_SORTDIST,IDC_UNITS, IDC_ACTIONS,IDC_HOTPOINTS,IDC_UNITSONBO,IDC_APMSTYLE}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); // enable useful options UINT enable[]={IDC_USESECONDS,IDC_ZOOM,IDC_HKSELECT,IDC_ANIMATE,IDC_SPEED,IDC_BPM,IDC_UPM,IDC_APMSTYLE}; for(int i=0;i<sizeof(enable)/sizeof(enable[0]);i++) GetDlgItem(enable[i])->EnableWindow(TRUE); } break; case HOTKEYS: { m_dataAreaX = 32; // disable useless options UINT disable[]={IDC_ANIMATE,IDC_PERCENTAGE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY, IDC_SORTDIST, IDC_SPEED,IDC_BPM,IDC_UPM,IDC_UNITS,IDC_ACTIONS,IDC_HOTPOINTS,IDC_UNITSONBO,IDC_APMSTYLE}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); // enable useful options UINT enable[]={IDC_USESECONDS,IDC_ZOOM,IDC_HKSELECT}; for(int i=0;i<sizeof(enable)/sizeof(enable[0]);i++) GetDlgItem(enable[i])->EnableWindow(TRUE); } break; case BUILDORDER: { // build order m_timeBegin = 0; m_timeEnd = m_replay.GetLastBuildOrderTime(); gbTimeWndHasChanged = true; // enable useful options GetDlgItem(IDC_UNITSONBO)->EnableWindow(TRUE); GetDlgItem(IDC_USESECONDS)->EnableWindow(TRUE); // disable useless options UINT disable[]={IDC_ZOOM,IDC_ANIMATE,IDC_PERCENTAGE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY, IDC_SORTDIST, IDC_SPEED,IDC_BPM,IDC_UPM,IDC_UNITS,IDC_ACTIONS,IDC_HOTPOINTS,IDC_HKSELECT,IDC_APMSTYLE}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); } break; case RESOURCES: { // disable useless options UINT disable[]={IDC_SPEED,IDC_BPM,IDC_UPM, IDC_HKSELECT,IDC_APMSTYLE,IDC_SORTDIST,IDC_PERCENTAGE,IDC_UNITSONBO}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); // enable useful options UINT enable[]={IDC_ZOOM,IDC_ANIMATE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY, IDC_UNITS,IDC_USESECONDS,IDC_ACTIONS,IDC_HOTPOINTS}; for(int i=0;i<sizeof(enable)/sizeof(enable[0]);i++) GetDlgItem(enable[i])->EnableWindow(TRUE); } break; case APM: { // disable useless options UINT disable[]={IDC_MINERALS,IDC_GAZ,IDC_SUPPLY,IDC_UNITS,IDC_ACTIONS, IDC_HKSELECT,IDC_SORTDIST,IDC_PERCENTAGE,IDC_UNITSONBO}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); // enable useful options UINT enable[]={IDC_ZOOM,IDC_ANIMATE,IDC_SPEED,IDC_BPM,IDC_UPM,IDC_USESECONDS,IDC_APMSTYLE}; for(int i=0;i<sizeof(enable)/sizeof(enable[0]);i++) GetDlgItem(enable[i])->EnableWindow(TRUE); } break; default: { // any distribution GetDlgItem(IDC_PERCENTAGE)->EnableWindow(TRUE); GetDlgItem(IDC_SORTDIST)->EnableWindow(TRUE); // disable useless options UINT disable[]={IDC_ZOOM,IDC_ANIMATE,IDC_MINERALS,IDC_GAZ,IDC_SUPPLY,IDC_UNITSONBO, IDC_SPEED,IDC_BPM,IDC_UPM,IDC_UNITS,IDC_ACTIONS,IDC_HOTPOINTS,IDC_HKSELECT,IDC_APMSTYLE}; for(int i=0;i<sizeof(disable)/sizeof(disable[0]);i++) GetDlgItem(disable[i])->EnableWindow(FALSE); } break; } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnHelp() { DlgHelp dlg; dlg.DoModal(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_BrowseReplays(const char *dir, int& count, int &idx, bool bCount) { CFileFind finder; char mask[255]; strcpy(mask,dir); if(mask[strlen(mask)-1]!='\\') strcat(mask,"\\"); strcat(mask,"*.*"); // load all replays BOOL bWorking = finder.FindFile(mask); while (bWorking) { // find next package bWorking = finder.FindNextFile(); //dir? if(finder.IsDirectory()) { // . & .. if(finder.IsDots()) continue; // recurse char subdir[255]; strcpy(subdir,dir); if(subdir[strlen(subdir)-1]!='\\') strcat(subdir,"\\"); strcat(subdir,finder.GetFileName()); _BrowseReplays(subdir, count, idx, bCount); continue; } // rep file? CString ext; ext=finder.GetFileName().Right(4); if(ext.CompareNoCase(".rep")!=0) continue; if(bCount) { count++; } else { // load it if(m_replay.Load(finder.GetFilePath(),false,0,true)!=0) { CString msg; msg.Format(IDS_CANTLOAD,(const char*)finder.GetFilePath()); MessageBox(msg); } idx++; // update progress bar m_progress.SetPos((100*idx)/count); } } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnTestreplays() { m_progress.ShowWindow(SW_SHOW); // count available replays int count=0; int idx=0; _BrowseReplays("e:\\program files\\starcraft\\maps\\", count, idx, true); // laod them _BrowseReplays("e:\\program files\\starcraft\\maps\\", count, idx, false); m_replay.Clear(); m_progress.ShowWindow(SW_HIDE); } //----------------------------------------------------------------------------------------------------------------- static bool gbAscendingAction=true; int CALLBACK CompareAction(LPARAM lParam1, LPARAM lParam2, LPARAM lParamSort) { int diff=0; const ReplayEvt *evt1 = (const ReplayEvt *)lParam1; const ReplayEvt *evt2 = (const ReplayEvt *)lParam2; unsigned long rep1 = evt1->Time(); unsigned long rep2 = evt2->Time(); switch(lParamSort) { case 0: diff = rep1 - rep2; break; default: assert(0); break; } return gbAscendingAction ? diff : -diff; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnAddevent() { // get path CString path; if(!_GetReplayFileName(path)) return; // add events from that replay LoadReplay(path,false); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnRclickPlstats(NMHDR* pNMHDR, LRESULT* pResult) { CPoint pt; GetCursorPos(&pt); // select only one player for(int i=0;i<m_plStats.GetItemCount();i++) m_plStats.SetItemState(i,0, LVIS_SELECTED+LVIS_FOCUSED); // find corresponding item m_plStats.ScreenToClient(&pt); UINT uFlags; int nItem = m_plStats.HitTest(pt,&uFlags); if(nItem!=-1 && (uFlags & LVHT_ONITEMLABEL)!=0) { // select item m_selectedPlayerList = (ReplayEvtList *)m_plStats.GetItemData(nItem); m_plStats.SetItemState(nItem,LVIS_SELECTED+LVIS_FOCUSED, LVIS_SELECTED+LVIS_FOCUSED); // load menu CMenu menu; menu.LoadMenu(IDR_POPUPPLAYER); CMenu *pSub = menu.GetSubMenu(0); // display popup menu m_plStats.ClientToScreen(&pt); pSub->TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, pt.x, pt.y, this); } *pResult = 0; } //---------------------------------------------------------------------------------------- void DlgStats::OnRemovePlayer() { if(m_selectedPlayerList!=0) { // remove player events m_replay.RemovePlayer(m_selectedPlayerList,&m_listEvents); m_selectedPlayer=0; // update player stats list _DisplayPlayerStats(); //repaint Invalidate(TRUE); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnSeemap() { m_dlgmap->ShowWindow(SW_SHOW); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::StopAnimation() { if(m_bIsAnimating) OnAnimate(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_UpdateAnimSpeed() { CString str; if(m_bIsAnimating) str.Format("(x%d)",m_animationSpeed); SetDlgItemText(IDC_ANIMSPEED,str); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_ToggleAnimateButtons(bool enable) { CString str; str.LoadString(enable ? IDS_ANIMATE:IDS_STOP); SetDlgItemText(IDC_ANIMATE,str); GetDlgItem(IDC_SPEEDPLUS)->EnableWindow(enable ? FALSE : TRUE); GetDlgItem(IDC_SPEEDMINUS)->EnableWindow(enable ? FALSE : TRUE); GetDlgItem(IDC_PAUSE)->EnableWindow(enable ? FALSE : TRUE); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnAnimate() { if(m_bIsAnimating) { // if we are on pause, unpause if(m_prevAnimationSpeed!=0) OnPause(); //stopping KillTimer(m_timer); m_bIsAnimating=false; _ToggleAnimateButtons(true); GetDlgItem(IDC_ZOOM)->EnableWindow(TRUE); GetDlgItem(IDC_CHARTTYPE)->EnableWindow(TRUE); // tell map m_dlgmap->Animate(false); // repaint Invalidate(); } else if(m_replay.IsDone()) { // starting m_timeBegin = 0; m_timeEnd = m_replay.GetEndTime(); //m_timeCursor = 0; m_zoom=0; UpdateData(FALSE); _ToggleAnimateButtons(false); GetDlgItem(IDC_ZOOM)->EnableWindow(FALSE); GetDlgItem(IDC_CHARTTYPE)->EnableWindow(FALSE); m_bIsAnimating=true; _UpdateAnimSpeed(); InvalidateRect(m_boardRect,TRUE); UpdateWindow(); // show animated map m_dlgmap->Animate(true); m_dlgmap->ShowWindow(SW_SHOW); // start timer m_timer = SetTimer(1,1000/TIMERSPEED,0); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnTimer(UINT nIDEvent) { // compute next position unsigned long newpos = m_timeCursor+m_replay.QueryFile()->QueryHeader()->Sec2Tick(m_animationSpeed)/TIMERSPEED; // if we reach the end, stop animation if(newpos>m_timeEnd) OnAnimate(); // udpate cursor if(m_animationSpeed>0) _SetTimeCursor(newpos, true,false); // update map if(m_dlgmap->IsWindowVisible()) m_dlgmap->UpdateTime(newpos); CDialog::OnTimer(nIDEvent); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnPause() { if(m_prevAnimationSpeed==0) { m_prevAnimationSpeed = m_animationSpeed; m_animationSpeed = 0; } else { m_animationSpeed = m_prevAnimationSpeed; m_prevAnimationSpeed = 0; } } void DlgStats::OnSpeedminus() { if(m_animationSpeed>1) m_animationSpeed/=2; _UpdateAnimSpeed(); } void DlgStats::OnSpeedplus() { if(m_animationSpeed<32) m_animationSpeed*=2; _UpdateAnimSpeed(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnGetdispinfoListevents(NMHDR* pNMHDR, LRESULT* pResult) { LV_DISPINFO* pDispInfo = (LV_DISPINFO*)pNMHDR; LV_ITEM* pItem= &(pDispInfo)->item; int iItemIndx= pItem->iItem; if (pItem->mask & LVIF_TEXT) //valid text buffer? { // get action const IStarcraftAction *action = m_replay.GetEnAction(iItemIndx);//m_replay.QueryFile()->QueryActions()->GetAction(iItemIndx); assert(action!=0); // get corresponding actionlist ReplayEvtList *list = (ReplayEvtList *)action->GetUserData(0); assert(list!=0); // get event description ReplayEvt *evt = list->GetEvent(action->GetUserData(1)); assert(evt!=0); // display value switch(pItem->iSubItem) { case 0: //time strcpy(pItem->pszText,_MkTime(m_replay.QueryFile()->QueryHeader(),evt->Time(),m_useSeconds?true:false)); break; case 1: //player if(evt->IsSuspect() || evt->IsHack()) sprintf(pItem->pszText,"#FF0000%s",list->PlayerName()); else strcpy(pItem->pszText,list->PlayerName()); break; case 2: //action //assert(evt->Time()!=37925); if(OPTIONSCHART->m_coloredevents) sprintf(pItem->pszText,"%s%s",evt->strTypeColor(),evt->strType()); else sprintf(pItem->pszText,"%s",evt->strType()); break; case 3: //parameters strcpy(pItem->pszText,action->GetParameters(list->GetElemList())); break; case 4: //discard & suspect flag strcpy(pItem->pszText,evt->IsDiscarded()?"*":evt->IsSuspect()?"#FF0000?":evt->IsHack()?"#FF0000!":""); break; case 5: // units ID strcpy(pItem->pszText,action->GetUnitsID(list->GetElemList())); break; default: assert(0); break; } assert(pItem->cchTextMax>(int)strlen(pItem->pszText)); } if(pItem->mask & LVIF_IMAGE) //valid image? pItem->iImage=0; *pResult = 0; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_GetResizeRect(CRect& resizeRect) { GetClientRect(&resizeRect); resizeRect.top = resizeRect.bottom - m_hlist - 8 - 6; resizeRect.bottom =resizeRect.top+6; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_GetHorizResizeRect(CRect& resizeRect) { GetClientRect(&resizeRect); resizeRect.top = resizeRect.bottom - m_hlist - 8 - 6; resizeRect.left = m_boardRect.left+ m_wlist; resizeRect.right = m_boardRect.left+m_wlist+8; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnLButtonDown(UINT nFlags, CPoint point) { // get tracking rect for resizing CRect resizeRect; _GetResizeRect(resizeRect); CRect horizResizeRect; _GetHorizResizeRect(horizResizeRect); // clicking on the resize part? if(resizeRect.PtInRect(point)) { m_resizing=VERTICAL_RESIZE; SetCapture(); m_ystart = point.y; } // clicking on the horizontal resize part? else if(horizResizeRect.PtInRect(point)) { m_resizing=HORIZONTAL_RESIZE; SetCapture(); m_xstart = point.x; } // clicking on map name? else if(m_rectMapName.PtInRect(point)) { OnSeemap(); } else { CRect rect = m_boardRect; rect.left+=hleft+m_dataAreaX; rect.right-=hright; // clicking on the graphics? if(rect.PtInRect(point) && m_maxPlayerOnBoard>0 && (m_chartType==APM || m_chartType==RESOURCES || m_chartType==BUILDORDER || m_chartType==MAPCOVERAGE || m_chartType==HOTKEYS || m_chartType>=MIX_APMHOTKEYS)) { // what player? if(!m_singleChart[m_chartType]) m_selectedPlayer = (point.y-m_boardRect.top) / (m_boardRect.Height() / m_maxPlayerOnBoard); // change time cursor float fx = (float)(point.x-rect.left); float finc = (float)(rect.Width())/(float)(m_timeEnd - m_timeBegin); _SetTimeCursor(m_timeBegin + (unsigned long)(fx/finc)); } } CDialog::OnLButtonDown(nFlags, point); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnLButtonUp(UINT nFlags, CPoint point) { if(m_resizing!=NONE) { // release capture ReleaseCapture(); // compute new layout if(m_resizing==VERTICAL_RESIZE) { int newhlist = m_hlist + (m_ystart-point.y); m_hlist = newhlist; } else { int newwlist = m_wlist + (point.x-m_xstart); m_wlist = newwlist; } // resize CRect rect; GetClientRect(&rect); _Resize(rect.Width(),rect.Height()); // end resizing m_resizing=NONE; } CDialog::OnLButtonUp(nFlags, point); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_GetHotKeyDesc(ReplayEvtList *list, int slot, CString& info) { info=""; // browse hotkey events for(int i=0;i<(int)list->GetHKEventCount();i++) { // get event const HotKeyEvent *hkevt = list->GetHKEvent(i); // skip events for other slots if(hkevt->m_slot!=slot) continue; // skip hotkey selection if(hkevt->m_type==HotKeyEvent::SELECT) continue; // new line if(!info.IsEmpty()) info+="\r\n"; // build unit list as string char buffer[64]; strcpy(buffer,_MkTime(m_replay.QueryFile()->QueryHeader(),hkevt->m_time,m_useSeconds?true:false)); info+=buffer+CString(" => "); const HotKey * hk = hkevt->GetHotKey(); for(int uidx=0;uidx<hk->m_unitcount;uidx++) { if(uidx>0) info+=", "; m_replay.QueryFile()->QueryHeader()->MkUnitID2String(buffer, hk->m_hotkeyUnits[uidx], list->GetElemList(), hkevt->m_time); info += buffer; } } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::_CheckForHotKey(ReplayEvtList *list, CPoint& point, CRect& datarect, int delta) { CRect symRect; // check hotkey numbers if(point.x < datarect.left+m_dataAreaX+delta) { // height of a key strip int levelhk = (datarect.Height()-8-vplayer)/10; // check all keys for(int i=0;i<10;i++) { // compute symbol position int y = datarect.top+vplayer + i*levelhk; CRect rectkey(datarect.left+6,y,datarect.left+6+m_dataAreaX+delta,y+levelhk); if(rectkey.PtInRect(point)) { // build description CString info; _GetHotKeyDesc(list, i, info); // update overlay window m_over->SetText(info,this,point); return; } } } // check hotkey events datarect.left+=m_dataAreaX; for(int i=0;i<(int)list->GetHKEventCount();i++) { // get event const HotKeyEvent *hkevt = list->GetHKEvent(i); if(hkevt->m_time < m_timeBegin || hkevt->m_time > m_timeEnd) continue; // view hotkey selection? if(!m_viewHKselect && hkevt->m_type==HotKeyEvent::SELECT) continue; // compute symbol position _ComputeHotkeySymbolRect(list, hkevt, datarect, symRect); // is mouse over this event? const HotKey * hk = hkevt->GetHotKey(); if(symRect.PtInRect(point) && hk!=0) { // build unit list as string CString info; char buffer[64]; for(int uidx=0;uidx<hk->m_unitcount;uidx++) { if(!info.IsEmpty()) info+="\r\n"; m_replay.QueryFile()->QueryHeader()->MkUnitID2String(buffer, hk->m_hotkeyUnits[uidx], list->GetElemList(), hkevt->m_time); info += buffer; } // update overlay window m_over->SetText(info,this,point); return; } } m_over->Show(false); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnMouseMove(UINT nFlags, CPoint point) { if(m_resizing!=NONE) { m_over->Show(false); //int newhlist = m_hlist + (m_ystart-point.y); //CRect resizeRect = m_boardRect; //resizeRect.top =newhlist; //resizeRect.bottom =newhlist+2; //DrawTrackRect( } else if(m_chartType==HOTKEYS) { // for each player on board CRect rect; for(int i=0,j=0; i<m_replay.GetPlayerCount() && j<m_maxPlayerOnBoard; i++) { // get event list for that player ReplayEvtList *list = m_replay.GetEvtList(i); if(!list->IsEnabled()) continue; // get rect for the player's charts _GetDataRectForPlayer(j++, rect, m_maxPlayerOnBoard); // is mouse in that rect? if(rect.PtInRect(point)) { // check if mouse is over a hotkey symbol _CheckForHotKey(list,point, rect); return; } } m_over->Show(false); } else if(m_chartType==MIX_APMHOTKEYS) { if(m_MixedPlayerIdx<m_replay.GetPlayerCount() && m_mixedCount>0) { // get event list for current player ReplayEvtList *list = m_replay.GetEvtList(m_MixedPlayerIdx); // get rect for the player's charts CRect rect; _GetDataRectForPlayer(1, rect, m_mixedCount); // is mouse in that rect? if(rect.PtInRect(point)) { // check if mouse is over a hotkey symbol _CheckForHotKey(list,point, rect, 32); return; } } m_over->Show(false); } CDialog::OnMouseMove(nFlags, point); } //----------------------------------------------------------------------------------------------------------------- BOOL DlgStats::OnSetCursor(CWnd* pWnd, UINT nHitTest, UINT message) { // get tracking rect for vertical resizing CRect resizeRect; _GetResizeRect(resizeRect); // get tracking rect for horizontal resizing CRect horizResizeRect; _GetHorizResizeRect(horizResizeRect); // mouse over the resize part? CPoint point; GetCursorPos(&point); ScreenToClient(&point); if(resizeRect.PtInRect(point)) { // top/bottom resize ::SetCursor(::LoadCursor(0,IDC_SIZENS)); return TRUE; } else if(horizResizeRect.PtInRect(point)) { // left/right resize ::SetCursor(::LoadCursor(0,IDC_SIZEWE)); return TRUE; } else if(m_rectMapName.PtInRect(point)) { // map name ::SetCursor(AfxGetApp()->LoadStandardCursor(MAKEINTRESOURCE(32649))); return TRUE; } return CDialog::OnSetCursor(pWnd, nHitTest, message); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnRButtonDown(UINT nFlags, CPoint point) { if(!m_replay.IsDone()) return; CPoint pt; GetCursorPos(&pt); // load menu CMenu menu; menu.LoadMenu(IDR_WATCHREP); CMenu *pSub = menu.GetSubMenu(0); // display popup menu pSub->TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, pt.x, pt.y, this); CDialog::OnRButtonDown(nFlags, point); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::_StartCurrentReplay(int mode) { CFileFind finder; BOOL bWorking = finder.FindFile(m_replay.GetFileName()); if(bWorking) { // get replay file info finder.FindNextFile(); // get replay info object from replay ReplayInfo *rep = MAINWND->pGetBrowser()->_ProcessReplay(finder.GetRoot(),finder); if(rep) MAINWND->pGetBrowser()->StartReplay(rep, mode); } } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay111() { _StartCurrentReplay(BW_111); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay112() { _StartCurrentReplay(BW_112); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay114() { _StartCurrentReplay(BW_114); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay115() { _StartCurrentReplay(BW_115); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay116() { _StartCurrentReplay(BW_116); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay113() { _StartCurrentReplay(BW_113); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay110() { _StartCurrentReplay(BW_110); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay109() { _StartCurrentReplay(BW_109); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplaySC() { _StartCurrentReplay(BW_SC); } //-------------------------------------------------------------------------------------------------------------- void DlgStats::OnWatchReplay() { _StartCurrentReplay(BW_AUTO); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnRclickListevents(NMHDR* pNMHDR, LRESULT* pResult) { if(m_replay.IsDone()) { // load menu CMenu menu; menu.LoadMenu(IDR_MENU_EVENTS); CMenu *pSub = menu.GetSubMenu(0); // display popup menu CPoint pt; GetCursorPos(&pt); pSub->TrackPopupMenu(TPM_LEFTALIGN |TPM_RIGHTBUTTON, pt.x, pt.y, this); } *pResult = 0; } //------------------------------------------------------------------------------------- static char szFilterTxt[] = "Text File (*.txt)|*.txt|All Files (*.*)|*.*||"; static char szFilterHtml[] = "HTML File (*.html)|*.html|All Files (*.*)|*.*||"; bool DlgStats::_GetFileName(const char *filter, const char *ext, const char *def, CString& file) { CFileDialog dlg(FALSE,ext,def,0,filter,this); CString str = AfxGetApp()->GetProfileString("BWCHART_MAIN","EXPDIR",""); if(!str.IsEmpty()) dlg.m_ofn.lpstrInitialDir = str; if(dlg.DoModal()==IDOK) { file = dlg.GetPathName(); AfxGetApp()->WriteProfileString("BWCHART_MAIN","EXPDIR",file); return true; } return false; } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnExportToText() { assert(m_replay.IsDone()); // get export file CString file; if(!_GetFileName(szFilterTxt, "txt", "bwchart.txt", file)) return; // create file CWaitCursor wait; int err = m_replay.ExportToText(file,m_useSeconds?true:false,'\t'); if(err==-1) {AfxMessageBox(IDS_CANTCREATFILE); return;} } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnExportToBWCoach() { assert(m_replay.IsDone()); ExportCoachDlg dlg(this,&m_replay); dlg.DoModal(); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnExportToHtml() { assert(m_replay.IsDone()); // get export file CString file; if(!_GetFileName(szFilterHtml, "html", "bwchart.html", file)) return; // create file FILE *fp=fopen(file,"wb"); if(fp==0) {AfxMessageBox(IDS_CANTCREATFILE); return;} // list events in list view CWaitCursor wait; for(unsigned long i=0;i<m_replay.GetEnActionCount(); i++) { // get action const IStarcraftAction *action = m_replay.GetEnAction((int)i); } //close file fclose(fp); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnFilterChange() { UpdateData(TRUE); _UpdateActionFilter(true); } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnNextSuspect() { if(!m_replay.IsDone()) return; // find next suspect event int newidx = m_replay.GetNextSuspectEvent(m_selectedAction); if(newidx!=-1) { // select corresponding line in list view m_lockListView=true; m_listEvents.SetItemState(newidx,LVIS_SELECTED|LVIS_FOCUSED,LVIS_SELECTED|LVIS_FOCUSED); m_listEvents.EnsureVisible(newidx,FALSE); m_lockListView=false; // update selected player & cursor pos _SelectAction(newidx); } } //----------------------------------------------------------------------------------------------------------------- void DlgStats::OnSelchangeApmstyle() { UpdateData(TRUE); if(m_replay.IsDone()) { // if apm style was changed if(m_replay.UpdateAPM(m_apmStyle[APM],m_apmStyle[MAPCOVERAGE])) { // repaint chart InvalidateRect(m_boardRect,FALSE); // update player stats _DisplayPlayerStats(); } } } //-----------------------------------------------------------------------------------------------------------------
29.947953
165
0.609408
udonyang
1c28a6c2d84c8db78475da19c2ed7f4c02177055
2,687
cc
C++
cagey-engine/source/cagey/window/Window.cc
theycallmecoach/cagey-engine
7a90826da687a1ea2837d0f614aa260aa1b63262
[ "MIT" ]
null
null
null
cagey-engine/source/cagey/window/Window.cc
theycallmecoach/cagey-engine
7a90826da687a1ea2837d0f614aa260aa1b63262
[ "MIT" ]
null
null
null
cagey-engine/source/cagey/window/Window.cc
theycallmecoach/cagey-engine
7a90826da687a1ea2837d0f614aa260aa1b63262
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////////////// //// //// cagey-engine - Toy 3D Engine //// Copyright (c) 2014 Kyle Girard <[email protected]> //// //// The MIT License (MIT) //// //// Permission is hereby granted, free of charge, to any person obtaining a copy //// of this software and associated documentation files (the "Software"), to deal //// in the Software without restriction, including without limitation the rights //// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell //// copies of the Software, and to permit persons to whom the Software is //// furnished to do so, subject to the following conditions: //// //// The above copyright notice and this permission notice shall be included in //// all copies or substantial portions of the Software. //// //// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //// SOFTWARE. //// ////////////////////////////////////////////////////////////////////////////////// // //#include <cagey/window/Window.hh> //#include <cagey/window/VideoMode.hh> //#include "cagey/window/WindowFactory.hh" //#include "cagey/window/IWindowImpl.hh" //#include <iostream> // //namespace { // cagey::window::Window const * fullScreenWindow = nullptr; //} // //namespace cagey { //namespace window { // //Window::Window(VideoMode const & vidMode, std::string const & winName, StyleSet const & winStyle) // : mImpl{}, // mVideoMode{vidMode}, // mName{winName}, // mStyle{winStyle}, // mVisible{false} { // // if (winStyle.test(Style::Fullscreen)) { // if (fullScreenWindow) { // std::cerr << "Unable to create two fullscreen windows" << std::endl; // mStyle.flip(Style::Fullscreen); // } else { // if (!mVideoMode.isValid()) { // //@TODO invalid video mode...should have better exception // throw 0; // } // fullScreenWindow = this; // } // } // // mImpl = detail::WindowFactory::create(mVideoMode, mName, mStyle); // mVisible = true; //} // //auto Window::getTitle() const -> std::string { // return mName; //} // //auto Window::setTitle(std::string const & newTitle) -> void { // mName = newTitle; // mImpl->setTitle(newTitle); //} // //} // namespace window //} // namespace cagey // // //
34.012658
99
0.629326
theycallmecoach
1c2ab67c1db41c545f994247455c2e688cd42224
321
cpp
C++
src/Omega_h_timer.cpp
overfelt/omega_h
dfc19cc3ea0e183692ca6c548dda39f7892301b5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/Omega_h_timer.cpp
overfelt/omega_h
dfc19cc3ea0e183692ca6c548dda39f7892301b5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
src/Omega_h_timer.cpp
overfelt/omega_h
dfc19cc3ea0e183692ca6c548dda39f7892301b5
[ "BSD-2-Clause-FreeBSD" ]
null
null
null
#include "Omega_h_timer.hpp" namespace Omega_h { Now now() { Now t; t.impl = std::chrono::high_resolution_clock::now(); return t; } Real operator-(Now b, Now a) { return std::chrono::duration_cast<std::chrono::nanoseconds>(b.impl - a.impl) .count() * 1e-9; } } // end namespace Omega_h
17.833333
78
0.619938
overfelt
1c2cf5f3e0ce5d29833ec36397e7c4fea8733201
1,321
cpp
C++
src/plugins/cgal/nodes/topology/convex_hull.cpp
martin-pr/possumwood
0ee3e0fe13ef27cf14795a79fb497e4d700bef63
[ "MIT" ]
232
2017-10-09T11:45:28.000Z
2022-03-28T11:14:46.000Z
src/plugins/cgal/nodes/topology/convex_hull.cpp
martin-pr/possumwood
0ee3e0fe13ef27cf14795a79fb497e4d700bef63
[ "MIT" ]
26
2019-01-20T21:38:25.000Z
2021-10-16T03:57:17.000Z
src/plugins/cgal/nodes/topology/convex_hull.cpp
martin-pr/possumwood
0ee3e0fe13ef27cf14795a79fb497e4d700bef63
[ "MIT" ]
33
2017-10-26T19:20:38.000Z
2022-03-16T11:21:43.000Z
#include <CGAL/convex_hull_3.h> #include <possumwood_sdk/node_implementation.h> #include "datatypes/meshes.h" #include "errors.h" namespace { using possumwood::CGALPolyhedron; using possumwood::Meshes; typedef possumwood::CGALPolyhedron Mesh; dependency_graph::InAttr<Meshes> a_inMesh; dependency_graph::OutAttr<Meshes> a_outMesh; dependency_graph::State compute(dependency_graph::Values& data) { possumwood::ScopedOutputRedirect redirect; // inefficient - an adaptor to replace this would be much better std::vector<possumwood::CGALKernel::Point_3> points; for(auto& mesh : data.get(a_inMesh)) points.insert(points.end(), mesh.polyhedron().points_begin(), mesh.polyhedron().points_end()); possumwood::Mesh mesh("convex_hull"); CGAL::convex_hull_3(points.begin(), points.end(), mesh.edit().polyhedron()); Meshes result; result.addMesh(mesh); data.set(a_outMesh, result); return redirect.state(); } void init(possumwood::Metadata& meta) { meta.addAttribute(a_inMesh, "in_mesh", possumwood::Meshes(), possumwood::AttrFlags::kVertical); meta.addAttribute(a_outMesh, "out_mesh", possumwood::Meshes(), possumwood::AttrFlags::kVertical); meta.addInfluence(a_inMesh, a_outMesh); meta.setCompute(compute); } possumwood::NodeImplementation s_impl("cgal/topology/convex_hull", init); } // namespace
28.106383
98
0.766086
martin-pr
1c2e89d744f4124d22abdfe05d593e26c4d67f5a
6,353
cpp
C++
Child/Releases/r081211/Code/tListInputData/tListInputData.cpp
dvalters/child
9874278f5308ab6c5f0cb93ed879bca9761d24b9
[ "MIT" ]
9
2015-02-23T15:47:20.000Z
2020-05-19T23:42:05.000Z
Child/Releases/r081211/Code/tListInputData/tListInputData.cpp
dvalters/child
9874278f5308ab6c5f0cb93ed879bca9761d24b9
[ "MIT" ]
3
2020-04-21T06:12:53.000Z
2020-08-20T16:56:17.000Z
Child/Releases/r081211/Code/tListInputData/tListInputData.cpp
dvalters/child
9874278f5308ab6c5f0cb93ed879bca9761d24b9
[ "MIT" ]
12
2015-02-18T18:34:57.000Z
2020-07-12T04:04:36.000Z
/**************************************************************************/ /** ** @file tListInputData.cpp ** @brief Functions for class tListInputData. ** ** Modifications: ** - changed .tri file format from points-edges-triangles to ** points-triangles-edges, compatible with earlier format (gt 1/98) ** - GT merged tListIFStreams and tListInputData into a single class ** to avoid multiple definition errors resulting from mixing ** template & non-template classes (1/99) ** - Bug fix in constructor: nnodes was being read from edge and ** triangle files -- thus arrays dimensioned incorrectly! (GT 04/02) ** - Remove dead code. Add findRightTime (AD 07/03) ** - Add Random number generator handling. (AD 08/03) ** - Refactoring with multiple classes (AD 11/03) ** - Add tVegetation handling (AD 11/03) ** ** $Id: tListInputData.cpp,v 1.25 2004/06/16 13:37:35 childcvs Exp $ */ /**************************************************************************/ #include "tListInputData.h" #include <iostream> #include "../Mathutil/mathutil.h" void tListInputDataBase:: ReportIOError(IOErrorType t, const char *filename, const char *suffix, int n) { std::cerr << "\nFile: '" << filename << suffix << "' " << "- Can't read "; switch (t){ case IOTime: std::cerr << "time"; break; case IOSize: std::cerr << "size"; break; case IORecord: std::cerr << "record " << n; break; } std::cerr << "." << std::endl; ReportFatalError( "Input/Output Error." ); } /**************************************************************************\ ** ** tListInputDataBase::openFile ** ** Find the right time in file and position it for reading ** \**************************************************************************/ void tListInputDataBase:: openFile( std::ifstream &infile, const char *basename, const char *ext) { char inname[80]; // full name of an input file // Open each of the four files assert( strlen(basename)+strlen(ext)<sizeof(inname) ); strcpy( inname, basename ); strcat( inname, ext ); infile.open(inname); if( !infile.good() ) { std::cerr << "Error: I can't find the following files:\n" << "\t" << basename << ext << "\n"; ReportFatalError( "Unable to open triangulation input file(s)." ); } } /**************************************************************************\ ** ** tListInputData::findRightTime ** ** Find the right time in file and position it for reading ** \**************************************************************************/ void tListInputDataBase:: findRightTime( std::ifstream &infile, int &nn, double intime, const char *basename, const char *ext, const char *typefile) { char headerLine[kMaxNameLength]; // header line read from input file bool righttime = false; double time; while( !( infile.eof() ) && !righttime ) { /*infile.getline( headerLine, kMaxNameLength ); if( headerLine[0] == kTimeLineMark ) { infile.seekg( -infile.gcount(), ios::cur ); infile >> time; std::cout << "from file, time = " << time << std::endl; std::cout << "Read: " << headerLine << std::endl; if( time == intime ) righttime = 1; }*/ infile >> time; if (infile.fail()) ReportIOError(IOTime, basename, ext); if (0) //DEBUG std::cout << "Read time: " << time << std::endl; if( time < intime ) { infile >> nn; if (infile.fail()) ReportIOError(IOSize, basename, ext); if (0) //DEBUG std::cout << "nn (" << typefile << ")= " << nn << std::endl; int i; for( i=1; i<=nn+1; i++ ) { infile.getline( headerLine, kMaxNameLength ); } } else righttime = true; if (0) //DEBUG std::cout << " NOW are we at eof? " << infile.eof() << std::endl; } if( !( infile.eof() ) ) { infile >> nn; if (infile.fail()) ReportIOError(IOSize, basename, ext); } else { std::cerr << "Couldn't find the specified input time in the " << typefile << " file\n"; ReportFatalError( "Input error" ); } } /**************************************************************************\ ** ** tListInputDataRand::tListInputDataRand() ** ** Read state from file ** \**************************************************************************/ tListInputDataRand:: tListInputDataRand( const tInputFile &inputfile, tRand &rand ) { double intime; // desired time char basename[80]; inputfile.ReadItem( basename, sizeof(basename), "INPUTDATAFILE" ); std::ifstream dataInfile; openFile( dataInfile, basename, SRANDOM); // Find out which time slice we want to extract intime = inputfile.ReadItem( intime, "INPUTTIME" ); if (1) //DEBUG std::cout << "intime = " << intime << std::endl; // Find specified input times in input data files and read # items. int nn; findRightTime( dataInfile, nn, intime, basename, SRANDOM, "random number generator"); if ( rand.numberRecords() != nn ) { std::cerr << "Invalid number of records for the random number generator\n"; ReportFatalError( "Input error" ); } // Read in data from file rand.readFromFile( dataInfile ); } /**************************************************************************\ ** ** tListInputDataVegetation::tListInputDataVegetation() ** ** Read state from file ** \**************************************************************************/ tListInputDataVegetation:: tListInputDataVegetation( const tInputFile &inputfile ) { double intime; // desired time char basename[80]; // Read base name for triangulation files from inputfile inputfile.ReadItem( basename, sizeof(basename), "INPUTDATAFILE" ); std::ifstream dataInfile; openFile( dataInfile, basename, SVEG); // Find out which time slice we want to extract intime = inputfile.ReadItem( intime, "INPUTTIME" ); if (1) //DEBUG std::cout << "intime = " << intime << std::endl; // Find specified input times in input data files and read # items. int nn; findRightTime( dataInfile, nn, intime, basename, SVEG, "vegetation mask"); // Read in data from file vegCov.setSize(nn); for( int i=0; i<nn; ++i ){ dataInfile >> vegCov[i]; if (dataInfile.fail()) ReportIOError(IORecord, basename, SVEG, i); } }
30.990244
79
0.555171
dvalters
1c39384ce95547642533d79874ef7f0dda03a3c5
4,864
cpp
C++
source/Foundation/DataStream.cpp
GrimshawA/Nephilim
1e69df544078b55fdaf58a04db963e20094f27a9
[ "Zlib" ]
19
2015-12-19T11:15:57.000Z
2022-03-09T11:22:11.000Z
source/Foundation/DataStream.cpp
DevilWithin/Nephilim
1e69df544078b55fdaf58a04db963e20094f27a9
[ "Zlib" ]
1
2017-05-17T09:31:10.000Z
2017-05-19T17:01:31.000Z
source/Foundation/DataStream.cpp
GrimshawA/Nephilim
1e69df544078b55fdaf58a04db963e20094f27a9
[ "Zlib" ]
3
2015-12-14T17:40:26.000Z
2021-02-25T00:42:42.000Z
#include <Nephilim/Foundation/DataStream.h> #include <Nephilim/Foundation/IODevice.h> #include <Nephilim/Foundation/String.h> #include <assert.h> #include <stdio.h> NEPHILIM_NS_BEGIN /// Constructs a invalid data stream DataStream::DataStream() : m_device(NULL) { } /// Constructs a data stream from a device DataStream::DataStream(IODevice& device) : m_device(&device) { } /// Set the device of this data stream void DataStream::setDevice(IODevice& device) { m_device = &device; } /// Read <size> bytes from the stream void DataStream::read(void* destination, uint32_t size) { assert(m_device); m_device->read(reinterpret_cast<char*>(destination), size); } /// Write a memory segment to the stream as-is void DataStream::write(void* source, uint32_t size) { assert(m_device); m_device->write(reinterpret_cast<char*>(source), size); } /// Write a uint32_t to the stream void DataStream::write_uint32(uint32_t v) { assert(m_device); m_device->write(reinterpret_cast<const char*>(&v), sizeof(v)); } /// Reads the next byte as a char char DataStream::readChar() { char c = EOF; if(m_device) { m_device->read(&c, sizeof(char)); } return c; } /// Reads count chars and stores them in the pre allocated buffer destination void DataStream::readChars(int count, char* destination) { if(m_device) { for(int i = 0; i < count; ++i) { m_device->read(&destination[i], sizeof(char)); } } } /// Write a 64-bit integer DataStream& DataStream::operator<<(Int64 value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Write a 64-bit signed integer DataStream& DataStream::operator<<(Int32 value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Write a 16-bit signed integer DataStream& DataStream::operator<<(Int16 value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Write a 8-bit signed integer DataStream& DataStream::operator<<(Int8 value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Write a 32-bit unsigned integer DataStream& DataStream::operator<<(Uint32 value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Write a boolean as a unsigned byte DataStream& DataStream::operator<<(bool value) { if(m_device) { Uint8 tempValue = static_cast<Uint8>(value); m_device->write(reinterpret_cast<const char*>(&tempValue), sizeof(tempValue)); } return *this; } /// Write a String DataStream& DataStream::operator<<(const String& value) { if(m_device) { *this << static_cast<Int64>(value.length()); m_device->write(value.c_str(), sizeof(char)*value.length()); } return *this; } /// Write a float DataStream& DataStream::operator<<(float value) { if(m_device) { m_device->write(reinterpret_cast<const char*>(&value), sizeof(value)); } return *this; } /// Read a 64-bit integer DataStream& DataStream::operator>>(Int64& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Int64)); } return *this; } /// Read a 32-bit signed integer DataStream& DataStream::operator>>(Int32& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Int32)); } return *this; } /// Read a 16-bit signed integer DataStream& DataStream::operator>>(Int16& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Int16)); } return *this; } /// Read a 32-bit unsigned integer DataStream& DataStream::operator>>(Uint32& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Uint32)); } return *this; } /// Read a 16-bit unsigned integer DataStream& DataStream::operator>>(Uint16& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Uint16)); } return *this; } /// Read a 8-bit unsigned integer DataStream& DataStream::operator>>(Uint8& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(Uint8)); } return *this; } /// Read a 8-bit boolean DataStream& DataStream::operator>>(bool& value) { if(m_device) { Uint8 tempValue; m_device->read(reinterpret_cast<char*>(&tempValue), sizeof(Uint8)); value = static_cast<bool>(tempValue); } return *this; } /// Read a String DataStream& DataStream::operator>>(String& value) { if(m_device) { Int64 length = 0; *this >> length; char* buffer = new char[length+1]; m_device->read(buffer, length); buffer[length] = '\0'; value = buffer; } return *this; } /// Read a float DataStream& DataStream::operator>>(float& value) { if(m_device) { m_device->read(reinterpret_cast<char*>(&value), sizeof(float)); } return *this; } NEPHILIM_NS_END
19.07451
80
0.694901
GrimshawA
1c3b4e522196f9a659bf825df253016e8ed0edf2
1,881
cpp
C++
src/bpfrequencytracker.cpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
22
2016-08-11T06:16:25.000Z
2022-02-22T00:06:59.000Z
src/bpfrequencytracker.cpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
9
2016-12-08T12:42:38.000Z
2021-12-28T20:12:15.000Z
src/bpfrequencytracker.cpp
LaoZZZZZ/bartender-1.1
ddfb2e52bdf92258dd837ab8ee34306e9fb45b81
[ "MIT" ]
8
2017-06-26T13:15:06.000Z
2021-11-12T18:39:54.000Z
// // bpfrequencytracker.cpp // barcode_project // // Created by luzhao on 4/21/16. // Copyright © 2016 luzhao. All rights reserved. // #include "bpfrequencytracker.hpp" #include <array> #include <cassert> #include <vector> using std::array; using std::vector; namespace barcodeSpace { BPFrequencyTracker::BPFrequencyTracker(size_t num_positions) { _total_position = num_positions; assert(_total_position > 0); _totalFrequency = 0; _condition_frequency_tracker.assign(num_positions, vector<ConditionFrequencyTable>(num_positions,ConditionFrequencyTable())); _self_marginal_frequency.assign(_total_position,array<uint64_t,4>()); for (size_t pos = 0; pos < _total_position; ++pos) { for (auto& t : _condition_frequency_tracker[pos]) { for (auto& c : t) { c.fill(0); } } } for (auto& marg : _self_marginal_frequency) { marg.fill(0); } _dict = kmersDictionary::getAutoInstance(); _bps_buffer.assign(_total_position, 0); } void BPFrequencyTracker::addFrequency(const std::string& seq, size_t freq) { assert(seq.length() == _total_position); for (size_t pos = 0; pos < _total_position; ++pos) { _bps_buffer[pos] = _dict->asc2dna(seq[pos]); _self_marginal_frequency[pos][_bps_buffer[pos]] += 1; } _totalFrequency += freq; // update the conditional frequency table for (size_t pos = 0; pos < _total_position - 1; ++pos) { for (size_t n_pos = pos + 1; n_pos < _total_position; ++n_pos) { _condition_frequency_tracker[pos][n_pos][_bps_buffer[pos]][_bps_buffer[n_pos]] += freq; } } } } // namespace barcodeSpace
34.2
133
0.596491
LaoZZZZZ
1c3f0bc21d3ed41f6fe8b58cb8a63f66eb007ca4
2,627
inl
C++
src/wire/core/transport.inl
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
5
2016-04-07T19:49:39.000Z
2021-08-03T05:24:11.000Z
src/wire/core/transport.inl
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
null
null
null
src/wire/core/transport.inl
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
1
2020-12-27T11:47:31.000Z
2020-12-27T11:47:31.000Z
/* * transport.inl * * Created on: Feb 8, 2016 * Author: zmij */ #ifndef WIRE_CORE_TRANSPORT_INL_ #define WIRE_CORE_TRANSPORT_INL_ #include <wire/core/transport.hpp> #include <wire/util/debug_log.hpp> namespace wire { namespace core { template < typename Session, transport_type Type > transport_listener< Session, Type >::transport_listener( asio_config::io_service_ptr svc, session_factory factory) : io_service_{svc}, acceptor_{*svc}, factory_{factory}, ready_{false}, closed_{true} { } template < typename Session, transport_type Type > transport_listener< Session, Type >::~transport_listener() { try { close(); } catch (...) {} } template < typename Session, transport_type Type > void transport_listener< Session, Type >::open(endpoint const& ep, bool rp) { endpoint_type proto_ep = traits::create_endpoint(io_service_, ep); acceptor_.open(proto_ep.protocol()); acceptor_.set_option( typename acceptor_type::reuse_address{true} ); acceptor_.set_option( typename acceptor_type::keep_alive{ true } ); if (rp) { acceptor_.set_option( reuse_port{true} ); } acceptor_.bind(proto_ep); acceptor_.listen(); closed_ = false; start_accept(); ready_ = true; } template < typename Session, transport_type Type > void transport_listener< Session, Type >::close() { if (!closed_) { closed_ = true; traits::close_acceptor(acceptor_); ready_ = false; } } template < typename Session, transport_type Type > typename transport_listener<Session, Type>::session_ptr transport_listener<Session, Type>::create_session() { return factory_( io_service_ ); } template < typename Session, transport_type Type > endpoint transport_listener<Session, Type>::local_endpoint() const { return traits::get_endpoint_data(acceptor_.local_endpoint()); } template < typename Session, transport_type Type > void transport_listener<Session, Type>::start_accept() { session_ptr session = create_session(); acceptor_.async_accept(session->socket(), ::std::bind(&transport_listener::handle_accept, this, session, ::std::placeholders::_1)); } template < typename Session, transport_type Type > void transport_listener<Session, Type>::handle_accept(session_ptr session, asio_config::error_code const& ec) { if (!ec) { session->start_session(); if (!closed_) start_accept(); } else { DEBUG_LOG(3, "Listener accept error code " << ec.message()); } } } // namespace core } // namespace wire #endif /* WIRE_CORE_TRANSPORT_INL_ */
25.019048
104
0.694328
zmij
1c4131f4e99beaf367375d11ca8b722024d71696
3,249
hpp
C++
include/Common/math.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
2
2020-05-05T13:31:55.000Z
2022-01-16T15:38:00.000Z
include/Common/math.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
null
null
null
include/Common/math.hpp
VisualGMQ/Chaos_Dungeon
95f9b23934ee16573bf9289b9171958f750ffc93
[ "MIT" ]
1
2021-11-27T02:32:24.000Z
2021-11-27T02:32:24.000Z
#ifndef MATH_HPP #define MATH_HPP #include <cfloat> #include <cmath> #include <iostream> #include <vector> #include "glm/glm.hpp" using namespace std; #define FLT_CMP(a, b) (abs(a-b)<=FLT_EPSILON) #define DEG2RAD(x) (x*M_PI/180.0) #define RAD2DEG(x) (x*180.0/M_PI) template <typename T> ostream& operator<<(ostream& o, const vector<T>& v){ cout<<"["; for(int i=0;i<v.size();i++) cout<<v[i]<<" "; cout<<"]"; return o; } struct Size{ float w; float h; Size(); }; class Vec2D{ public: Vec2D(); Vec2D(float x, float y); void Set(float x, float y); void Normalize(); float Len() const; float Cross(const Vec2D v) const; float Dot(const Vec2D v) const; void Rotate(float degree); Vec2D operator=(const Vec2D v); Vec2D operator+(const Vec2D v); Vec2D operator-(const Vec2D v); Vec2D operator*(const Vec2D v); Vec2D operator/(const Vec2D v); Vec2D operator+=(const Vec2D v); Vec2D operator-=(const Vec2D v); Vec2D operator*=(const Vec2D v); Vec2D operator/=(const Vec2D v); bool operator==(const Vec2D v); bool operator!=(const Vec2D v); Vec2D operator+(float v); Vec2D operator-(float v); Vec2D operator*(float v); Vec2D operator/(float v); Vec2D operator+=(float v); Vec2D operator-=(float v); Vec2D operator*=(float v); Vec2D operator/=(float v); float x; float y; void Print() const; }; float Distance(Vec2D v1, Vec2D v2); Vec2D Normalize(Vec2D v); Vec2D Rotate(Vec2D v, float degree); Vec2D operator+(float n, Vec2D v); Vec2D operator-(float n, Vec2D v); Vec2D operator*(float n, Vec2D v); Vec2D operator/(float n, Vec2D v); ostream& operator<<(ostream& o, const Vec2D v); using Vec = Vec2D; struct Range{ Range(); Range(float a, float b); void Set(float a, float b); float GetMax() const; float GetMin() const; float Len() const; float min; float max; void Print() const; }; ostream& operator<<(ostream& o, Range range); Range GetCoveredRange(const Range r1, const Range r2); Range CombineRange(const Range r1, const Range r2); bool PointInRange(const Range r, float p); bool IsRangeCovered(const Range r1, const Range r2); class Rot2D{ public: Rot2D(); Rot2D(float degree); void Set(float degree); Vec2D GetAxisX() const; Vec2D GetAxisY() const; float GetDegree() const; private: float s; float c; }; struct Mat22{ Mat22(); Mat22(Vec2D c1, Vec2D c2); Mat22(float m00, float m01, float m10, float m11); void Identify(); void Zero(); Mat22 Times(const Mat22 m); Mat22 operator+(const Mat22 m); Mat22 operator-(const Mat22 m); Mat22 operator*(const Mat22 m); Vec2D operator*(const Vec2D v); Mat22 operator*(float n); Mat22 operator/(const Mat22 m); Mat22 operator/(float n); Mat22 operator+=(const Mat22 m); Mat22 operator-=(const Mat22 m); Mat22 operator*=(const Mat22 m); Mat22 operator/=(const Mat22 m); float m00; float m01; float m10; float m11; void Print() const; }; ostream& operator<<(ostream& o, Mat22 m); Mat22 operator*(float n, Mat22 m); Mat22 operator/(float n, Mat22 m); Mat22 GenRotMat22(float degree); #endif
23.374101
54
0.644814
VisualGMQ
1c49c154874b273a42fea95b7447dfd1476a38c6
2,902
cpp
C++
src/input.cpp
Bryankaveen/tanks-ce
27670778dbf6329b7fa4e69d12f8a4e5fa1f3ad9
[ "MIT" ]
14
2020-08-11T14:39:52.000Z
2022-02-08T21:17:56.000Z
src/input.cpp
commandblockguy/Tanks-CE
9eb79438a0ecd12cbde23be207257c650b703acb
[ "MIT" ]
1
2020-11-04T08:17:52.000Z
2020-11-05T22:41:46.000Z
src/input.cpp
commandblockguy/Tanks-CE
9eb79438a0ecd12cbde23be207257c650b703acb
[ "MIT" ]
1
2021-12-16T19:24:04.000Z
2021-12-16T19:24:04.000Z
#include "game.h" #include "gui/pause.h" #include "objects/tank.h" #include "util/profiler.h" #include <keypadc.h> #define PLAYER_BARREL_ROTATION DEGREES_TO_ANGLE(5) //1/3 of a second for 90 degree rotation #define PLAYER_TREAD_ROTATION (DEGREES_TO_ANGLE(90) / (TARGET_TICK_RATE / 3)) void handle_movement() { Tank *player = game.player; angle_t target_rot; uint8_t keys = 0; if(kb_IsDown(kb_KeyDown)) keys |= DOWN; if(kb_IsDown(kb_KeyLeft)) keys |= LEFT; if(kb_IsDown(kb_KeyRight)) keys |= RIGHT; if(kb_IsDown(kb_KeyUp)) keys |= UP; switch(keys) { default: player->set_velocity(0); return; case UP: target_rot = DEGREES_TO_ANGLE(270); break; case DOWN: target_rot = DEGREES_TO_ANGLE(90); break; case LEFT: target_rot = DEGREES_TO_ANGLE(180); break; case RIGHT: target_rot = DEGREES_TO_ANGLE(0); break; case UP | RIGHT: target_rot = DEGREES_TO_ANGLE(315); break; case DOWN | RIGHT: target_rot = DEGREES_TO_ANGLE(45); break; case UP | LEFT: target_rot = DEGREES_TO_ANGLE(225); break; case DOWN | LEFT: target_rot = DEGREES_TO_ANGLE(135); } int diff = player->tread_rot - target_rot; if((uint)abs(diff) > DEGREES_TO_ANGLE(90)) { player->tread_rot += DEGREES_TO_ANGLE(180); diff = (int) (player->tread_rot - target_rot); } if(diff < -(int) PLAYER_TREAD_ROTATION) { player->tread_rot += PLAYER_TREAD_ROTATION; } else if(diff > (int) PLAYER_TREAD_ROTATION) { player->tread_rot -= PLAYER_TREAD_ROTATION; } else { player->tread_rot = target_rot; } if((uint)abs(diff) <= DEGREES_TO_ANGLE(45)) { player->set_velocity(TANK_SPEED_NORMAL); } else { player->set_velocity(0); } } uint8_t handle_input() { profiler_start(input); Tank *player = game.player; handle_movement(); if(kb_IsDown(kb_Key2nd)) { player->fire_shell(); } if(kb_IsDown(kb_KeyAlpha)) { player->lay_mine(); } if(kb_IsDown(kb_KeyMode)) { player->barrel_rot -= PLAYER_BARREL_ROTATION; } if(kb_IsDown(kb_KeyGraphVar)) { player->barrel_rot += PLAYER_BARREL_ROTATION; } if(kb_IsDown(kb_KeyAdd)) { switch(pause_menu()) { default: case 0: break; case 1: // todo: restart case 2: return QUIT; } } if(kb_IsDown(kb_KeyDel)) { // TODO: remove return NEXT_LEVEL; } if(kb_IsDown(kb_KeyClear)) { return QUIT; } if(kb_IsDown(kb_KeyYequ)) { profiler_print(); } profiler_end(input); return 0; }
25.910714
77
0.569952
Bryankaveen
1c5287128a8e952846a5208fa07831366f7e1a2e
2,141
cpp
C++
src/logger/logger.cpp
gratonos/cxlog
1e2befb466d600545db3ad79cb0001f2f0056476
[ "MIT" ]
null
null
null
src/logger/logger.cpp
gratonos/cxlog
1e2befb466d600545db3ad79cb0001f2f0056476
[ "MIT" ]
null
null
null
src/logger/logger.cpp
gratonos/cxlog
1e2befb466d600545db3ad79cb0001f2f0056476
[ "MIT" ]
null
null
null
#include <cxlog/logger/logger.h> NAMESPACE_CXLOG_BEGIN void Logger::Log(Level level, const char *file, std::size_t line, const char *func, std::string &&msg) const { const Additional &additional = this->additional; std::vector<Context> contexts; contexts.reserve(additional.statics->size() + additional.dynamics->size()); for (StaticContext &context : *additional.statics) { contexts.emplace_back(Context{context.GetKey(), context.GetValue()}); } for (DynamicContext &context : *additional.dynamics) { contexts.emplace_back(Context{context.GetKey(), context.GetValue()}); } LockGuard lock(this->intrinsic->lock); Record record; record.time = Clock::now(); record.level = level; record.file = file; record.line = line; record.func = func; record.msg = std::move(msg); record.prefix = *additional.prefix; record.contexts = std::move(contexts); record.mark = additional.mark; if (additional.filter(record) && this->intrinsic->config.DoFilter(record)) { this->FormatAndWrite(level, record); } } void Logger::FormatAndWrite(Level level, const Record &record) const { const Intrinsic &intrinsic = *this->intrinsic; std::array<std::string, SlotCount> logs; for (std::size_t i = 0; i < SlotCount; i++) { const Slot &slot = intrinsic.slots[i]; if (slot.NeedToLog(level, record)) { std::string &log = logs[i]; if (log.empty()) { log = slot.Format(record); for (size_t n : intrinsic.equivalents[i]) { logs[n] = log; } } slot.Write(log, record); } } } void Logger::UpdateEquivalents() { Intrinsic &intrinsic = *this->intrinsic; for (std::size_t i = 0; i < SlotCount; i++) { intrinsic.equivalents[i].clear(); for (std::size_t j = i + 1; j < SlotCount; j++) { if (intrinsic.slots[i].GetFormatter() == intrinsic.slots[j].GetFormatter()) { intrinsic.equivalents[i].push_back(j); } } } } NAMESPACE_CXLOG_END
31.485294
89
0.601121
gratonos
1c5856d4b398bc8f8bf0bc558731f2f7feff1882
1,311
cpp
C++
c++/Test/GlobalData/weoExceptionMessageCreator.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/Test/GlobalData/weoExceptionMessageCreator.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
c++/Test/GlobalData/weoExceptionMessageCreator.cpp
taku-xhift/labo
89dc28fdb602c7992c6f31920714225f83a11218
[ "MIT" ]
null
null
null
 //------------------------------------------------------------------- // include //------------------------------------------------------------------- #include "weoExceptionMessageCreator.h" #include <sstream> namespace pm_mode { /******************************************************************** * @brief 一定のフォーマットに法った文字列を作成する * @note ExceptionMessage に使用されることを前提としている * @param[in] message 何か残したい特別なメッセージ * @param[in] fileName 文字列を作成したファイルの名前 * @param[in] line 文字列を作成した行 * @param[in] function 文字列を作成した関数 * @return 情報をまとめた文字列 *******************************************************************/ std::string messageCreator(const std::string& message, bool isException, weString fileName, int line, weString function) throw() { std::stringstream ss; std::string returnValue; if (isException) { returnValue += "Exception is thrown!!!\nmessage: " + message; } else { returnValue += "Have Message!!!\nmessage: " + message; } returnValue.append("\nfile: "); returnValue.append(fileName); ss << line; returnValue += "\nline: "; returnValue += ss.str(); returnValue.append("\nfunction: "); returnValue.append(function); returnValue.append("\n"); return returnValue; } } // namespace pm_mode
26.755102
129
0.515637
taku-xhift
1c5b3de7fce16286f16fb22e379723f676ef5d50
546
hpp
C++
jmax/shader/Shader.hpp
JeanGamain/jmax
1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04
[ "MIT" ]
null
null
null
jmax/shader/Shader.hpp
JeanGamain/jmax
1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04
[ "MIT" ]
null
null
null
jmax/shader/Shader.hpp
JeanGamain/jmax
1d4aee47c7fad25b9c4d9a678b84c5f4aad98c04
[ "MIT" ]
null
null
null
#ifndef SHADER_HPP_ #define SHADER_HPP_ #include "../jmax.hpp" #include <string> #include <vector> namespace jmax { class Shader { public: Shader(std::string const& filePath, GLenum shaderType = 0); virtual ~Shader(); public: static GLuint compileShaderFile(std::string const& shaderFilePath, GLenum shaderType); static GLenum Shader::getShaderType(std::string const& filePath); public: std::string const& filePath; const GLenum type; const GLuint shaderId; bool deleted; }; } // namespace jmax #endif /* !SHADER_HPP_ */
19.5
88
0.725275
JeanGamain
1c5b779943d9abe8389382f1717d224f7c402fef
816
cpp
C++
Linked List/Singly Linked List/Insert/add_at_front.cpp
dipanshuchaubey/competitive-coding
9b41f4693a30fdcf00b82db9aad5ced7d0dc454f
[ "MIT" ]
null
null
null
Linked List/Singly Linked List/Insert/add_at_front.cpp
dipanshuchaubey/competitive-coding
9b41f4693a30fdcf00b82db9aad5ced7d0dc454f
[ "MIT" ]
null
null
null
Linked List/Singly Linked List/Insert/add_at_front.cpp
dipanshuchaubey/competitive-coding
9b41f4693a30fdcf00b82db9aad5ced7d0dc454f
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; class Node { public: Node *next; int data; }; void printList(Node *n) { while (n != NULL) { cout << n->data << "\t"; n = n->next; } } void insertAtFront(Node **start_node, int data) { Node *new_node = new Node(); new_node->data = data; new_node->next = *start_node; *start_node = new_node; } int main() { Node *first = new Node(); Node *second = new Node(); Node *third = new Node(); first->data = 1; first->next = second; second->data = 2; second->next = third; third->data = 3; third->next = NULL; cout << "Default List: \t"; printList(first); insertAtFront(&first, 0); cout << "\nList after inserting at front: \t"; printList(first); return 0; }
14.571429
50
0.551471
dipanshuchaubey
1c5c19ab2d119c2ccec4e995d72e9230b11a2b97
1,807
cpp
C++
src/LG/lg-P1659.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
1
2021-08-13T14:27:39.000Z
2021-08-13T14:27:39.000Z
src/LG/lg-P1659.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
null
null
null
src/LG/lg-P1659.cpp
krishukr/cpp-code
1c94401682227bd86c0d9295134d43582247794e
[ "MIT" ]
null
null
null
#include <cstdio> #include <cstring> #include <iostream> #define int long long const int MAX_N = 2000050; const int MOD = 19930726; std::string d, s; int re[MAX_N], cnt[MAX_N]; int n, nn, k; void init(); void manacher(); int quick_pow(int a, int b); signed main() { std::ios::sync_with_stdio(false); std::cin >> nn >> k >> s; int sum = 0, ans = 1; n = nn; init(); manacher(); for (int i = nn; i > 0; i--) { if (i % 2) { sum += cnt[i]; if (k >= sum) { ans *= quick_pow(i, sum); ans %= MOD; k -= sum; } else { ans *= quick_pow(i, k); ans %= MOD; k -= sum; break; } } else { continue; } } if (k > 0) { std::cout << -1 << '\n'; } else { std::cout << ans << '\n'; } return 0; } void init() { d.resize(2 * n + 10); d[0] = d[1] = 'A'; for (int i = 0; i < n; i++) { d[i * 2 + 2] = s[i]; d[i * 2 + 3] = 'A'; } n = 2 * n + 2; d[n] = 0; } void manacher() { int r = 0, mid = 0; for (int l = 1; l < n; l++) { if (l < r) { re[l] = std::min(re[mid * 2 - l], re[mid] + mid - l); } else { re[l] = 1; } while (d[l + re[l]] == d[l - re[l]]) { re[l]++; } if (re[l] + l > r) { r = re[l] + l; mid = l; } if ((re[l] - 1) % 2) { cnt[re[l] - 1]++; } } } int quick_pow(int a, int b) { a %= MOD; int res = 1; while (b) { if (b & 1) { res = res * a % MOD; } a = a * a % MOD; b >>= 1; } return res; }
17.891089
65
0.342557
krishukr
1c5d2d09af639b8b275c0a1e970826844b4512c4
129
cpp
C++
tensorflow-yolo-ios/dependencies/eigen/doc/special_examples/Tutorial_sparse_example_details.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
27
2017-06-07T19:07:32.000Z
2020-10-15T10:09:12.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/special_examples/Tutorial_sparse_example_details.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
3
2017-08-25T17:39:46.000Z
2017-11-18T03:40:55.000Z
tensorflow-yolo-ios/dependencies/eigen/doc/special_examples/Tutorial_sparse_example_details.cpp
initialz/tensorflow-yolo-face-ios
ba74cf39168d0128e91318e65a1b88ce4d65a167
[ "MIT" ]
10
2017-06-16T18:04:45.000Z
2018-07-05T17:33:01.000Z
version https://git-lfs.github.com/spec/v1 oid sha256:338e6e57d5446ad622a48ab505a62e4ddf72367f1dd3bd9dee9773f0f43ab857 size 1576
32.25
75
0.883721
initialz
1c60fa930f611edaa3a07a5d07828882b70c0b10
974
cpp
C++
demo/src/main.cpp
fundies/Crash2D
40b14d4259d7cedeea27d46f7206b80a07a3327c
[ "MIT" ]
1
2017-05-25T13:49:18.000Z
2017-05-25T13:49:18.000Z
demo/src/main.cpp
fundies/SAT
40b14d4259d7cedeea27d46f7206b80a07a3327c
[ "MIT" ]
6
2016-09-27T22:57:13.000Z
2017-05-11T17:01:26.000Z
demo/src/main.cpp
fundies/SAT
40b14d4259d7cedeea27d46f7206b80a07a3327c
[ "MIT" ]
4
2016-09-29T01:19:44.000Z
2021-04-02T07:45:59.000Z
#include "MTVDemo.hpp" #include "BroadphaseDemo.hpp" int main(int argc, char **argv) { sf::RenderWindow window(sf::VideoMode(800, 600), "Crash2D Demo"); window.setFramerateLimit(60); Demo *demo = new MTVDemo(window); size_t demoId = 0; while (window.isOpen()) { // check all the window's events that were triggered since the last iteration of the loop sf::Event event; while (window.pollEvent(event)) { switch (event.type) { // "close requested" event: we close the window case sf::Event::Closed: window.close(); break; case sf::Event::KeyReleased: if (event.key.code == sf::Keyboard::Space) { delete demo; ++demoId; if (demoId > 1) demoId = 0; switch (demoId) { case 0: demo = new MTVDemo(window); break; case 1: demo = new BroadphaseDemo(window); break; } } break; default: break; } } demo->draw(); window.display(); } }
21.173913
91
0.596509
fundies
1c6d2c7de9a44b122987529f4e6d173c3d381f35
1,127
cpp
C++
src/openloco/townmgr.cpp
Gymnasiast/OpenLoco
1bef36f96bcce0d6095d1b804a8d9f9df9651d07
[ "MIT" ]
null
null
null
src/openloco/townmgr.cpp
Gymnasiast/OpenLoco
1bef36f96bcce0d6095d1b804a8d9f9df9651d07
[ "MIT" ]
null
null
null
src/openloco/townmgr.cpp
Gymnasiast/OpenLoco
1bef36f96bcce0d6095d1b804a8d9f9df9651d07
[ "MIT" ]
null
null
null
#include "townmgr.h" #include "companymgr.h" #include "interop/interop.hpp" #include "openloco.h" using namespace openloco::interop; namespace openloco::townmgr { static loco_global_array<town, 80, 0x005B825C> _towns; std::array<town, max_towns>& towns() { auto arr = (std::array<town, max_towns>*)_towns.get(); return *arr; } town* get(town_id_t id) { if (id >= _towns.size()) { return nullptr; } return &_towns[id]; } // 0x00496B6D void update() { if ((addr<0x00525E28, uint32_t>() & 1) && !is_editor_mode()) { auto ticks = scenario_ticks(); if (ticks % 8 == 0) { town_id_t id = (ticks / 8) % 0x7F; auto town = get(id); if (town != nullptr && !town->empty()) { companymgr::updating_company_id(company_id::neutral); town->update(); } } } } // 0x0049748C void update_monthly() { call(0x0049748C); } }
21.673077
73
0.485359
Gymnasiast
cc6033dfeeb05bcadef587cf2cd59cd5542fc7f6
117,939
cpp
C++
Visual Mercutio/zModelBP/PSS_ProcedureSymbolBP.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
1
2022-01-31T06:24:24.000Z
2022-01-31T06:24:24.000Z
Visual Mercutio/zModelBP/PSS_ProcedureSymbolBP.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-04-11T15:50:42.000Z
2021-06-05T08:23:04.000Z
Visual Mercutio/zModelBP/PSS_ProcedureSymbolBP.cpp
Jeanmilost/Visual-Mercutio
f079730005b6ce93d5e184bb7c0893ccced3e3ab
[ "MIT" ]
2
2021-01-08T00:55:18.000Z
2022-01-31T06:24:18.000Z
/**************************************************************************** * ==> PSS_ProcedureSymbolBP -----------------------------------------------* **************************************************************************** * Description : Provides a procedure symbol for banking process * * Developer : Processsoft * ****************************************************************************/ #include "stdafx.h" #include "PSS_ProcedureSymbolBP.h" // processsoft #include "zBaseLib\PSS_Tokenizer.h" #include "zBaseLib\PSS_Global.h" #include "zBaseLib\PSS_ToolbarObserverMsg.h" #include "zBaseLib\PSS_MsgBox.h" #include "zBaseLib\PSS_DrawFunctions.h" #include "zBaseSym\zBaseSymRes.h" #include "zModel\PSS_ModelGlobal.h" #include "zModel\PSS_UserGroupEntity.h" #include "zModel\PSS_ProcessGraphModelDoc.h" #include "zModel\PSS_SelectUserGroupDlg.h" #include "zModel\PSS_ODSymbolManipulator.h" #define _ZMODELEXPORT #include "zModel\PSS_BasicProperties.h" #undef _ZMODELEXPORT #include "zProperty\PSS_PropertyAttributes.h" #include "zProperty\PSS_PropertyObserverMsg.h" #include "PSS_DeliverableLinkSymbolBP.h" #include "PSS_RuleListPropertiesBP.h" #include "PSS_TaskListPropertiesBP.h" #include "PSS_DecisionListPropertiesBP.h" #include "PSS_CostPropertiesProcedureBP_Beta1.h" #include "PSS_UnitPropertiesBP_Beta1.h" #include "PSS_CombinationPropertiesBP.h" #include "PSS_SimPropertiesProcedureBP.h" #include "PSS_AddRemoveCombinationDeliverableDlg.h" #include "PSS_SelectMasterDeliverableDlg.h" #include "PSS_ProcessGraphModelControllerBP.h" #include "PSS_RiskOptionsDlg.h" // resources #include "zModelBPRes.h" #include "PSS_ModelResIDs.h" #include "zModel\zModelRes.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[] = __FILE__; #define new DEBUG_NEW #endif //--------------------------------------------------------------------------- // Global constants //--------------------------------------------------------------------------- const std::size_t g_MaxRuleListSize = 20; const std::size_t g_MaxTaskListSize = 20; const std::size_t g_MaxDecisionListSize = 20; const std::size_t g_MaxCombinationListSize = 20; const std::size_t g_MaxRulesSize = 20; const std::size_t g_MaxRisksSize = 20; //--------------------------------------------------------------------------- // Static variables //--------------------------------------------------------------------------- static CMenu g_CombinationMenu; static CMenu g_RulesMenu; static CMenu g_RiskMenu; //--------------------------------------------------------------------------- // Serialization //--------------------------------------------------------------------------- IMPLEMENT_SERIAL(PSS_ProcedureSymbolBP, PSS_Symbol, g_DefVersion) //--------------------------------------------------------------------------- // PSS_ProcedureSymbolBP //--------------------------------------------------------------------------- PSS_ProcedureSymbolBP::PSS_ProcedureSymbolBP(const CString& name) : PSS_Symbol(), m_Combinations(this) { ShowAttributeArea(true); PSS_Symbol::SetSymbolName(name); CreateSymbolProperties(); } //--------------------------------------------------------------------------- PSS_ProcedureSymbolBP::PSS_ProcedureSymbolBP(const PSS_ProcedureSymbolBP& other) { *this = other; } //--------------------------------------------------------------------------- PSS_ProcedureSymbolBP::~PSS_ProcedureSymbolBP() {} //--------------------------------------------------------------------------- PSS_ProcedureSymbolBP& PSS_ProcedureSymbolBP::operator = (const PSS_ProcedureSymbolBP& other) { PSS_Symbol::operator = ((const PSS_Symbol&)other); m_Combinations = other.m_Combinations; m_Rules = other.m_Rules; m_Risks = other.m_Risks; return *this; } //--------------------------------------------------------------------------- BOOL PSS_ProcedureSymbolBP::Create(const CString& name) { BOOL result = FALSE; try { m_IsInCreationProcess = true; result = PSS_Symbol::Create(IDR_BP_PROCEDURE, ::AfxFindResourceHandle(MAKEINTRESOURCE(IDR_PACKAGE_SYM), _T("Symbol")), name); if (!CreateSymbolProperties()) result = FALSE; } catch (...) { m_IsInCreationProcess = false; throw; } m_IsInCreationProcess = false; return result; } //--------------------------------------------------------------------------- CODComponent* PSS_ProcedureSymbolBP::Dup() const { return new PSS_ProcedureSymbolBP(*this); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::CopySymbolDefinitionFrom(const CODSymbolComponent& src) { PSS_Symbol::CopySymbolDefinitionFrom(src); const PSS_ProcedureSymbolBP* pProcedure = dynamic_cast<const PSS_ProcedureSymbolBP*>(&src); if (pProcedure) { m_Combinations = pProcedure->m_Combinations; m_Combinations.SetParent(this); m_SimulationProperties = pProcedure->m_SimulationProperties; m_UnitProp = pProcedure->m_UnitProp; m_CostProcedureProp = pProcedure->m_CostProcedureProp; m_Rules = pProcedure->m_Rules; m_Risks = pProcedure->m_Risks; m_CommentRect = pProcedure->m_CommentRect; // fill the unit double validation type array m_UnitDoubleValidationTypeArray.RemoveAll(); GetUnitDoubleValidationTypeStringArray(m_UnitDoubleValidationTypeArray); } } //--------------------------------------------------------------------------- BOOL PSS_ProcedureSymbolBP::SetSymbolName(const CString& value) { return PSS_Symbol::SetSymbolName(value); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::AcceptDropItem(CObject* pObj, const CPoint& point) { // don't allow the drop if the symbol isn't local if (!IsLocal()) return false; // is an user entity? if (pObj && ISA(pObj, PSS_UserGroupEntity)) return true; // is a rule? if (pObj && ISA(pObj, PSS_LogicalRulesEntity)) return true; return PSS_Symbol::AcceptDropItem(pObj, point); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::DropItem(CObject* pObj, const CPoint& point) { PSS_UserGroupEntity* pUserGroupEntity = dynamic_cast<PSS_UserGroupEntity*>(pObj); if (pUserGroupEntity) { PSS_ProcessGraphModelMdl* pModel = dynamic_cast<PSS_ProcessGraphModelMdl*>(GetRootModel()); // is the user group valid? if (pModel && !pModel->MainUserGroupIsValid()) { PSS_MsgBox mBox; mBox.Show(IDS_CANNOTDROP_USERGROUPNOTINLINE, MB_OK); return false; } SetUnitGUID(pUserGroupEntity->GetGUID()); SetUnitName(pUserGroupEntity->GetEntityName()); // change the unit cost SetUnitCost(pUserGroupEntity->GetEntityCost()); // set flag for modification SetModifiedFlag(TRUE); // refresh the attribute area and redraw the symbol RefreshAttributeTextArea(true); return true; } PSS_LogicalRulesEntity* pLogicalRulesEntity = dynamic_cast<PSS_LogicalRulesEntity*>(pObj); if (pLogicalRulesEntity) { PSS_ProcessGraphModelMdl* pModel = dynamic_cast<PSS_ProcessGraphModelMdl*>(GetRootModel()); // is the rule valid? if (pModel && !pModel->MainLogicalRulesIsValid()) { PSS_MsgBox mBox; mBox.Show(IDS_CANNOTDROP_RULENOTINLINE, MB_OK); return false; } std::unique_ptr<PSS_RulesPropertiesBP> pRuleProps(new PSS_RulesPropertiesBP()); pRuleProps->SetRuleName(pLogicalRulesEntity->GetEntityName()); pRuleProps->SetRuleDescription(pLogicalRulesEntity->GetEntityDescription()); pRuleProps->SetRuleGUID(pLogicalRulesEntity->GetGUID()); m_Rules.AddRule(pRuleProps.get()); pRuleProps.release(); // set the procedure symbol as modified SetModifiedFlag(TRUE); // refresh the attribute area and redraw the symbol RefreshAttributeTextArea(true); return true; } return PSS_Symbol::DropItem(pObj, point); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::AcceptExtApp() const { return true; } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::AcceptExtFile() const { return true; } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::CreateSymbolProperties() { if (!PSS_Symbol::CreateSymbolProperties()) return false; PSS_RuleListPropertiesBP propRules; AddProperty(propRules); PSS_TaskListPropertiesBP propTasks; AddProperty(propTasks); PSS_DecisionListPropertiesBP propDecisions; AddProperty(propDecisions); PSS_CostPropertiesProcedureBP_Beta1 propCost; AddProperty(propCost); PSS_UnitPropertiesBP_Beta1 propUnit; AddProperty(propUnit); // create at least one combination property m_Combinations.CreateInitialProperties(); // fill the unit double validation type array m_UnitDoubleValidationTypeArray.RemoveAll(); GetUnitDoubleValidationTypeStringArray(m_UnitDoubleValidationTypeArray); // create at least one risk property m_Risks.CreateInitialProperties(); return true; } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::FillProperties(PSS_Properties::IPropertySet& propSet, bool numericValues, bool groupValues) { // if no file, add a new one if (!GetExtFileCount()) AddNewExtFile(); // if no application, add a new one if (!GetExtAppCount()) AddNewExtApp(); // the "Name", "Description" and "Reference" properties of the "General" group can be found in the base class. // The "External Files" and "External Apps" properties are also available from there if (!PSS_Symbol::FillProperties(propSet, numericValues, groupValues)) return false; // only local symbol may access to properties if (!IsLocal()) return true; PSS_ProcessGraphModelMdl* pProcessGraphModel = dynamic_cast<PSS_ProcessGraphModelMdl*>(GetRootModel()); PSS_ProcessGraphModelDoc* pProcessGraphMdlDoc = pProcessGraphModel ? dynamic_cast<PSS_ProcessGraphModelDoc*>(pProcessGraphModel->GetDocument()) : NULL; // initialize the currency symbol with the user local currency symbol defined in the control panel CString currencySymbol = PSS_Global::GetLocaleCurrency(); // update the currency symbol according to the user selection if (pProcessGraphMdlDoc) currencySymbol = pProcessGraphMdlDoc->GetCurrencySymbol(); bool groupEnabled = true; if (pProcessGraphModel && !pProcessGraphModel->MainUserGroupIsValid()) groupEnabled = false; std::unique_ptr<PSS_Property> pProp; // if the rule menu isn't loaded, load it if (!g_RulesMenu.GetSafeHmenu()) g_RulesMenu.LoadMenu(IDR_RULES_MENU); const int ruleCount = m_Rules.GetRulesCount(); // fill the rule properties if (ruleCount) { CString ruleSectionTitle; ruleSectionTitle.LoadString(IDS_Z_RULES_TITLE); CString ruleDesc; ruleDesc.LoadString(IDS_Z_RULES_DESC); PSS_ProcessGraphModelMdlBP* pOwnerModel = dynamic_cast<PSS_ProcessGraphModelMdlBP*>(GetOwnerModel()); PSS_LogicalRulesEntity* pMainRule = NULL; // get the main rule if (pOwnerModel) { PSS_ProcessGraphModelControllerBP* pModelCtrl = dynamic_cast<PSS_ProcessGraphModelControllerBP*>(pOwnerModel->GetController()); if (pModelCtrl) { PSS_ProcessGraphModelDoc* pDoc = dynamic_cast<PSS_ProcessGraphModelDoc*>(pModelCtrl->GetDocument()); if (pDoc) pMainRule = pDoc->GetMainLogicalRules(); } } // iterate through the rules and add their properties for (int i = 0; i < ruleCount; ++i) { // the rule check can only be performed if the rules are synchronized with the referential if (pProcessGraphModel && pProcessGraphModel->MainLogicalRulesIsValid()) { const CString safeName = GetRuleNameByGUID(pMainRule, m_Rules.GetRuleGUID(i)); if (!safeName.IsEmpty() && safeName != m_Rules.GetRuleName(i)) m_Rules.SetRuleName(i, safeName); } CString ruleName; ruleName.Format(IDS_Z_RULES_NAME, i + 1); // the "Rule x" property of the "Rules" group pProp.reset(new PSS_Property(ruleSectionTitle, ZS_BP_PROP_RULES, ruleName, M_Rule_Name_ID + (i * g_MaxRulesSize), ruleDesc, m_Rules.GetRuleName(i), PSS_Property::IE_T_EditMenu, true, PSS_StringFormat(PSS_StringFormat::IE_FT_General), NULL, &g_RulesMenu)); pProp->EnableDragNDrop(); propSet.Add(pProp.get()); pProp.release(); } } // NOTE BE CAREFUL the previous rules architecture below has now changed, and is designed as controls, because // they became obsolete after the new rules system was implemented since November 2006. But as the two architectures // are too different one from the other, and the both needed to cohabit together, for compatibility reasons with the // previous serialization process, the texts referencing to the previous architecture were modified, and the "Rules" // words were replaced by "Controls" in the text resources, however the code side was not updated, due to a too huge // work to apply the changes. So if a new modification should be applied in the code, please be aware about this point PSS_RuleListPropertiesBP* pRulesProps; // add the rule if ((pRulesProps = static_cast<PSS_RuleListPropertiesBP*>(GetProperty(ZS_BP_PROP_RULELIST))) == NULL) { PSS_RuleListPropertiesBP propRules; AddProperty(propRules); // get it back pRulesProps = static_cast<PSS_RuleListPropertiesBP*>(GetProperty(ZS_BP_PROP_RULELIST)); if (!pRulesProps) return false; } CString propTitle; propTitle.LoadString(IDS_ZS_BP_PROP_RULELST_TITLE); CStringArray* pValueArray = PSS_Global::GetHistoricValueManager().GetFieldHistory(propTitle); CString propName; propName.LoadString(IDS_Z_RULE_LIST_NAME); CString propDesc; propDesc.LoadString(IDS_Z_RULE_LIST_DESC); CString finalPropName; int count = GetRuleCount() + 1; // iterate through all control properties, and define at least one control for (int i = 0; i < g_MaxRuleListSize; ++i) { finalPropName.Format(_T("%s %d"), propName, i + 1); // add control, if count is reached continue to add empty control until reaching the maximum size if (i < count) // the "Control x" property of the "Controls" group pProp.reset(new PSS_Property(propTitle, ZS_BP_PROP_RULELIST, finalPropName, M_Rule_List_ID + (i * g_MaxRuleListSize), propDesc, GetRuleAt(i), PSS_Property::IE_T_EditIntelli, true, PSS_StringFormat(PSS_StringFormat::IE_FT_General), pValueArray)); else // the "Control X" of the "Controls" group, but it is empty and not shown pProp.reset(new PSS_Property(propTitle, ZS_BP_PROP_RULELIST, finalPropName, M_Rule_List_ID + (i * g_MaxRuleListSize), propDesc, _T(""), PSS_Property::IE_T_EditIntelli, false, PSS_StringFormat(PSS_StringFormat::IE_FT_General), pValueArray)); pProp->EnableDragNDrop(); propSet.Add(pProp.get()); pProp.release(); } // load the risk menu if still not exists if (!g_RiskMenu.GetSafeHmenu()) g_RiskMenu.LoadMenu(IDR_RISK_MENU); CString riskTitle; riskTitle.LoadString(IDS_ZS_BP_PROP_RISK_TITLE); // iterate through the risks and add their properties for (int i = 0; i < GetRiskCount(); ++i) { CString finalRiskTitle; finalRiskTitle.Format(_T("%s (%d)"), riskTitle, i + 1); CString riskName; riskName.LoadString(IDS_Z_RISK_NAME_NAME); CString riskDesc; riskDesc.LoadString(IDS_Z_RISK_NAME_DESC); CString finalRiskName; // the "Risk title" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_Name_ID : (M_Risk_Name_ID + (i * g_MaxRisksSize)), riskDesc, GetRiskName(i), PSS_Property::IE_T_EditMenu, true, PSS_StringFormat(PSS_StringFormat::IE_FT_General), NULL, &g_RiskMenu)); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_DESC_NAME); riskDesc.LoadString(IDS_Z_RISK_DESC_DESC); // the "Description" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_Desc_ID : (M_Risk_Desc_ID + (i * g_MaxRisksSize)), riskDesc, GetRiskDesc(i), PSS_Property::IE_T_EditExtended)); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_TYPE_NAME); riskDesc.LoadString(IDS_Z_RISK_TYPE_DESC); CString sNoRiskType = _T(""); sNoRiskType.LoadString(IDS_NO_RISK_TYPE); // the "Type" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_Type_ID : (M_Risk_Type_ID + (i * g_MaxRisksSize)), riskDesc, GetRiskType(i).IsEmpty() ? sNoRiskType : GetRiskType(i), PSS_Property::IE_T_EditExtendedReadOnly)); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_IMPACT_NAME); riskDesc.LoadString(IDS_Z_RISK_IMPACT_DESC); PSS_Application* pApplication = PSS_Application::Instance(); PSS_MainForm* pMainForm = NULL; CString riskImpact; // get the risk impact string if (pApplication) { pMainForm = pApplication->GetMainForm(); if (pMainForm) { PSS_RiskImpactContainer* pContainer = pMainForm->GetRiskImpactContainer(); if (pContainer) riskImpact = pContainer->GetElementAt(GetRiskImpact(i)); } } // the "Impact" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_Impact_ID : (M_Risk_Impact_ID + (i * g_MaxRisksSize)), riskDesc, riskImpact, PSS_Property::IE_T_EditExtendedReadOnly)); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_PROBABILITY_NAME); riskDesc.LoadString(IDS_Z_RISK_PROBABILITY_DESC); CString riskProbability; if (pMainForm) { PSS_RiskProbabilityContainer* pContainer = pMainForm->GetRiskProbabilityContainer(); if (pContainer) riskProbability = pContainer->GetElementAt(GetRiskProbability(i)); } // the "Probability" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_Probability_ID : (M_Risk_Probability_ID + (i * g_MaxRisksSize)), riskDesc, riskProbability, PSS_Property::IE_T_EditExtendedReadOnly)); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_SEVERITY_NAME); riskDesc.LoadString(IDS_Z_RISK_SEVERITY_DESC); // the "Severity" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_Severity_ID : (M_Risk_Severity_ID + (i * g_MaxRisksSize)), riskDesc, double(GetRiskSeverity(i)), PSS_Property::IE_T_EditNumberReadOnly)); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_UE_NAME); riskDesc.LoadString(IDS_Z_RISK_UE_DESC); // the "Unit. est." property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_UE_ID : (M_Risk_UE_ID + (i * g_MaxRisksSize)), riskDesc, GetRiskUE(i), PSS_Property::IE_T_EditNumber, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol))); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_POA_NAME); riskDesc.LoadString(IDS_Z_RISK_POA_DESC); // the "POA" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_POA_ID : (M_Risk_POA_ID + (i * g_MaxRisksSize)), riskDesc, GetRiskPOA(i), PSS_Property::IE_T_EditNumber, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol))); propSet.Add(pProp.get()); pProp.release(); riskName.LoadString(IDS_Z_RISK_ACTION_NAME); riskDesc.LoadString(IDS_Z_RISK_ACTION_DESC); // the "Action" property of the "Risk (x)" group pProp.reset(new PSS_Property(finalRiskTitle, groupValues ? ZS_BP_PROP_RISK : (ZS_BP_PROP_RISK + i), riskName, groupValues ? M_Risk_Action_ID : (M_Risk_Action_ID + (i * g_MaxRisksSize)), riskDesc, GetRiskAction(i) ? PSS_Global::GetYesFromArrayYesNo() : PSS_Global::GetNoFromArrayYesNo(), PSS_Property::IE_T_ComboStringReadOnly, TRUE, PSS_StringFormat(PSS_StringFormat::IE_FT_General), PSS_Global::GetArrayYesNo())); propSet.Add(pProp.get()); pProp.release(); } // add tasks PSS_TaskListPropertiesBP* pTasksProps = static_cast<PSS_TaskListPropertiesBP*>(GetProperty(ZS_BP_PROP_TASKLIST)); if (!pTasksProps) return false; count = GetTaskCount() + 1; propTitle.LoadString(IDS_ZS_BP_PROP_PROCEDURE_TSKLST_TITLE); pValueArray = PSS_Global::GetHistoricValueManager().GetFieldHistory(propTitle); propName.LoadString(IDS_Z_TASK_LIST_NAME); propDesc.LoadString(IDS_Z_TASK_LIST_DESC); // iterate through all task properties, and define at least one task for (int i = 0; i < g_MaxTaskListSize; ++i) { finalPropName.Format(_T("%s %d"), propName, i + 1); // add task, if count is reached continue to add empty task until reaching the maximum size if (i < count) // the "Task x" property of the "Tasks" group pProp.reset(new PSS_Property(propTitle, ZS_BP_PROP_TASKLIST, finalPropName, M_Task_List_ID + (i * g_MaxTaskListSize), propDesc, GetTaskAt(i), PSS_Property::IE_T_EditIntelli, true, PSS_StringFormat(PSS_StringFormat::IE_FT_General), pValueArray)); else // the "Task x" property of the "Tasks" group, but empty and not shown pProp.reset(new PSS_Property(propTitle, ZS_BP_PROP_TASKLIST, finalPropName, M_Task_List_ID + (i * g_MaxTaskListSize), propDesc, _T(""), PSS_Property::IE_T_EditIntelli, false, PSS_StringFormat(PSS_StringFormat::IE_FT_General), pValueArray)); pProp->EnableDragNDrop(); propSet.Add(pProp.get()); pProp.release(); } // get the decisions PSS_DecisionListPropertiesBP* pDecisionsProps = static_cast<PSS_DecisionListPropertiesBP*>(GetProperty(ZS_BP_PROP_DECISIONLIST)); if (!pDecisionsProps) return false; count = GetDecisionCount() + 1; propTitle.LoadString(IDS_ZS_BP_PROP_PROCEDURE_DECLST_TITLE); pValueArray = PSS_Global::GetHistoricValueManager().GetFieldHistory(propTitle); propName.LoadString(IDS_Z_DECISION_LIST_NAME); propDesc.LoadString(IDS_Z_DECISION_LIST_DESC); // iterate through all decision properties, and define at least one decision for (int i = 0; i < g_MaxDecisionListSize; ++i) { finalPropName.Format(_T("%s %d"), propName, i + 1); // add decision, if count is reached continue to add empty decision until reaching the maximum size if (i < count) // the "Decision x" property of the "Decisions" group pProp.reset(new PSS_Property(propTitle, ZS_BP_PROP_DECISIONLIST, finalPropName, M_Decision_List_ID + (i * g_MaxDecisionListSize), propDesc, GetDecisionAt(i), PSS_Property::IE_T_EditIntelli, true, PSS_StringFormat(PSS_StringFormat::IE_FT_General), pValueArray)); else // the "Decision x" property of the "Decisions" group, but it is empty and not shown pProp.reset(new PSS_Property(propTitle, ZS_BP_PROP_DECISIONLIST, finalPropName, M_Decision_List_ID + (i * g_MaxDecisionListSize), propDesc, _T(""), PSS_Property::IE_T_EditIntelli, false, PSS_StringFormat(PSS_StringFormat::IE_FT_General), pValueArray)); pProp->EnableDragNDrop(); propSet.Add(pProp.get()); pProp.release(); } int hourPerDay = -1; int dayPerWeek = -1; int dayPerMonth = -1; int dayPerYear = -1; // get the standard time if (pProcessGraphMdlDoc) { hourPerDay = pProcessGraphMdlDoc->GetHourPerDay(); dayPerWeek = pProcessGraphMdlDoc->GetDayPerWeek(); dayPerMonth = pProcessGraphMdlDoc->GetDayPerMonth(); dayPerYear = pProcessGraphMdlDoc->GetDayPerYear(); } bool error; // do add the procedure and processing unit properties? if (pProcessGraphModel && pProcessGraphModel->GetIntegrateCostSimulation()) { // the "Multiplier" property of the "Procedure" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_MULTIPLIER_NAME, M_Cost_Proc_Multiplier_ID, IDS_Z_COST_MULTIPLIER_DESC, GetMultiplier(), PSS_Property::IE_T_EditNumber, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Accounting, true, -1))); propSet.Add(pProp.get()); pProp.release(); // the "Standard time" property of the "Procedure" group if (numericValues) pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_PROCESSING_TIME_NAME, M_Cost_Proc_Processing_Time_ID, IDS_Z_COST_PROCESSING_TIME_DESC, GetProcessingTime(), PSS_Property::IE_T_EditNumber)); else pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_PROCESSING_TIME_NAME, M_Cost_Proc_Processing_Time_ID, IDS_Z_COST_PROCESSING_TIME_DESC, PSS_Duration(GetProcessingTime(), hourPerDay, dayPerWeek, dayPerMonth, dayPerYear), PSS_Property::IE_T_EditDuration, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Duration7))); propSet.Add(pProp.get()); pProp.release(); // the "Unitary cost" property of the "Procedure" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_UNITARY_COST_NAME, M_Cost_Proc_Unitary_Cost_ID, IDS_Z_COST_UNITARY_COST_DESC, GetUnitaryCost(), PSS_Property::IE_T_EditNumber, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol))); propSet.Add(pProp.get()); pProp.release(); // the "Average duration (weighted)" property of the "Procedure" group if (numericValues) pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_PROCESSING_DURATION_NAME, M_Cost_Proc_Processing_Duration_ID, IDS_Z_COST_PROCESSING_DURATION_DESC, GetProcessingDuration(), PSS_Property::IE_T_EditNumber)); else pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_PROCESSING_DURATION_NAME, M_Cost_Proc_Processing_Duration_ID, IDS_Z_COST_PROCESSING_DURATION_DESC, PSS_Duration(GetProcessingDuration(), hourPerDay, dayPerWeek, dayPerMonth, dayPerYear), PSS_Property::IE_T_EditDurationReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Duration7))); propSet.Add(pProp.get()); pProp.release(); // the "Average duration (max)" property of the "Procedure" group if (numericValues) pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_PROCESSING_DURATIONMAX_NAME, M_Cost_Proc_Processing_Duration_Max_ID, IDS_Z_COST_PROCESSING_DURATIONMAX_DESC, GetProcessingDurationMax(), PSS_Property::IE_T_EditNumber)); else pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_PROCEDURE_TITLE, ZS_BP_PROP_PROCEDURE_COST, IDS_Z_COST_PROCESSING_DURATIONMAX_NAME, M_Cost_Proc_Processing_Duration_Max_ID, IDS_Z_COST_PROCESSING_DURATIONMAX_DESC, PSS_Duration(GetProcessingDurationMax(), hourPerDay, dayPerWeek, dayPerMonth, dayPerYear), PSS_Property::IE_T_EditDurationReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Duration7))); propSet.Add(pProp.get()); pProp.release(); // get the unit cost const float unitCost = RetrieveUnitCost(GetUnitGUID(), error); // the "Cost" property of the "Processing unit" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_UNIT_TITLE, ZS_BP_PROP_UNIT, IDS_Z_UNIT_COST_NAME, M_Unit_Cost_ID, IDS_Z_UNIT_COST_DESC, unitCost, PSS_Property::IE_T_EditNumberReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol))); propSet.Add(pProp.get()); pProp.release(); // the "Double validation" property of the "Processing unit" group if (numericValues) pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_UNIT_TITLE, ZS_BP_PROP_UNIT, IDS_Z_UNIT_DOUBLE_VALIDATION_NAME, M_Unit_Double_Validation_ID, IDS_Z_UNIT_DOUBLE_VALIDATION_DESC, double(GetUnitDoubleValidationType()), PSS_Property::IE_T_EditNumber, false, PSS_StringFormat(PSS_StringFormat::IE_FT_General))); else pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_UNIT_TITLE, ZS_BP_PROP_UNIT, IDS_Z_UNIT_DOUBLE_VALIDATION_NAME, M_Unit_Double_Validation_ID, IDS_Z_UNIT_DOUBLE_VALIDATION_DESC, GetUnitDoubleValidationTypeString(GetUnitDoubleValidationType()), PSS_Property::IE_T_ComboStringReadOnly, false, PSS_StringFormat(PSS_StringFormat::IE_FT_General), &m_UnitDoubleValidationTypeArray)); propSet.Add(pProp.get()); pProp.release(); } // the "Guid" property of the "Processing unit" group. This property isn't enabled, just used for write the unit GUID. // NOTE "GUID" and "Name" properties should appear in Conceptor pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_UNIT_TITLE, ZS_BP_PROP_UNIT, IDS_Z_UNIT_GUID_NAME, M_Unit_GUID_ID, IDS_Z_UNIT_GUID_DESC, GetUnitGUID(), PSS_Property::IE_T_EditExtendedReadOnly, false)); propSet.Add(pProp.get()); pProp.release(); // get the unit name const CString unitName = RetrieveUnitName(GetUnitGUID(), error); // the "Unit" property of the "Processing unit" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_UNIT_TITLE, ZS_BP_PROP_UNIT, IDS_Z_UNIT_NAME_NAME, M_Unit_Name_ID, IDS_Z_UNIT_NAME_DESC, unitName, groupEnabled ? PSS_Property::IE_T_EditExtendedReadOnly : PSS_Property::IE_T_EditStringReadOnly)); propSet.Add(pProp.get()); pProp.release(); // if the combination menu is not loaded, load it if (!g_CombinationMenu.GetSafeHmenu()) g_CombinationMenu.LoadMenu(IDR_COMBINATION_MENU); // the combination properties should appear only in Messenger if (pProcessGraphModel && pProcessGraphModel->GetIntegrateCostSimulation()) { CString finalPropTitle; count = GetCombinationCount(); propTitle.LoadString(IDS_ZS_BP_PROP_COMBINATION_TITLE); // necessary to check if the initial combination is correct CheckInitialCombination(); // iterate through all combination properties for (int i = 0; i < count; ++i) { finalPropTitle.Format(_T("%s (%d)"), propTitle, i + 1); propName.LoadString(IDS_Z_COMBINATION_NAME_NAME); propDesc.LoadString(IDS_Z_COMBINATION_NAME_DESC); // the "Combination title" property of the "Combination x" group pProp.reset(new PSS_Property(finalPropTitle, groupValues ? ZS_BP_PROP_COMBINATION : (ZS_BP_PROP_COMBINATION + i), propName, groupValues ? M_Combination_Name_ID : (M_Combination_Name_ID + (i * g_MaxCombinationListSize)), propDesc, GetCombinationName(i), PSS_Property::IE_T_EditMenu, true, PSS_StringFormat(PSS_StringFormat::IE_FT_General), NULL, &g_CombinationMenu)); propSet.Add(pProp.get()); pProp.release(); propName.LoadString(IDS_Z_COMBINATION_DELIVERABLES_NAME); propDesc.LoadString(IDS_Z_COMBINATION_DELIVERABLES_DESC); // the "Deliverables" property of the "Combination x" group pProp.reset(new PSS_Property(finalPropTitle, groupValues ? ZS_BP_PROP_COMBINATION : (ZS_BP_PROP_COMBINATION + i), propName, groupValues ? M_Combination_Deliverables_ID : (M_Combination_Deliverables_ID + (i * g_MaxCombinationListSize)), propDesc, GetCombinationDeliverables(i), PSS_Property::IE_T_EditExtendedReadOnly)); propSet.Add(pProp.get()); pProp.release(); propName.LoadString(IDS_Z_COMBINATION_ACTIVATION_PERC_NAME); propDesc.LoadString(IDS_Z_COMBINATION_ACTIVATION_PERC_DESC); // get the percentage const float maxPercent = GetMaxActivationPerc(GetCombinationMaster(i)); // the "Percentage" property of the "Combination x" group pProp.reset(new PSS_Property(finalPropTitle, groupValues ? ZS_BP_PROP_COMBINATION : (ZS_BP_PROP_COMBINATION + i), propName, groupValues ? M_Combination_Activation_Perc_ID : (M_Combination_Activation_Perc_ID + (i * g_MaxCombinationListSize)), propDesc, maxPercent, PSS_Property::IE_T_EditNumberReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Percentage))); propSet.Add(pProp.get()); pProp.release(); propName.LoadString(IDS_Z_COMBINATION_MASTER_NAME); propDesc.LoadString(IDS_Z_COMBINATION_MASTER_DESC); // the "Master" property of the "Combination x" group pProp.reset(new PSS_Property(finalPropTitle, groupValues ? ZS_BP_PROP_COMBINATION : (ZS_BP_PROP_COMBINATION + i), propName, groupValues ? M_Combination_Master_ID : (M_Combination_Master_ID + (i * g_MaxCombinationListSize)), propDesc, GetCombinationMaster(i), PSS_Property::IE_T_EditExtendedReadOnly)); propSet.Add(pProp.get()); pProp.release(); } } if (pProcessGraphModel && pProcessGraphModel->GetIntegrateCostSimulation()) { // get the procedure activation value const double value = double(CalculateProcedureActivation()); // the "Activation" property of the "Calculations and forecasts" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_ACTIVATION_NAME, M_Sim_Procedure_Activation_ID, IDS_Z_SIM_PROCEDURE_ACTIVATION_DESC, value, PSS_Property::IE_T_EditNumberReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Accounting, true, 0))); propSet.Add(pProp.get()); pProp.release(); // the "HMO cost" property of the "Calculations and forecasts" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_COST_NAME, M_Sim_Procedure_Cost_ID, IDS_Z_SIM_PROCEDURE_COST_DESC, double(GetProcedureCost()), PSS_Property::IE_T_EditNumberReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol))); propSet.Add(pProp.get()); pProp.release(); // the "Charge" property of the "Calculations and forecasts" group if (numericValues) pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_WORKLOAD_FORECAST_NAME, M_Sim_Procedure_Workload_Forecast_ID, IDS_Z_SIM_PROCEDURE_WORKLOAD_FORECAST_DESC, double(GetProcedureWorkloadForecast()), PSS_Property::IE_T_EditNumber)); else pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_WORKLOAD_FORECAST_NAME, M_Sim_Procedure_Workload_Forecast_ID, IDS_Z_SIM_PROCEDURE_WORKLOAD_FORECAST_DESC, PSS_Duration(double(GetProcedureWorkloadForecast()), hourPerDay, dayPerWeek, dayPerMonth, dayPerYear), PSS_Property::IE_T_EditDurationReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Duration7))); propSet.Add(pProp.get()); pProp.release(); // the "Cost" property of the "Calculations and forecasts" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_COST_FORECAST_NAME, M_Sim_Procedure_Cost_Forecast_ID, IDS_Z_SIM_PROCEDURE_COST_FORECAST_DESC, double(GetProcedureCostForecast()), PSS_Property::IE_T_EditNumberReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol))); propSet.Add(pProp.get()); pProp.release(); // the "Charge / activation" property of the "Calculations and forecasts" group if (numericValues) pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_WORKLOAD_P_ACTIV_NAME, M_Sim_Procedure_Workload_Per_Activ_ID, IDS_Z_SIM_PROCEDURE_WORKLOAD_P_ACTIV_DESC, double(GetProcedureWorkloadPerActivity()), PSS_Property::IE_T_EditNumber)); else pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_WORKLOAD_P_ACTIV_NAME, M_Sim_Procedure_Workload_Per_Activ_ID, IDS_Z_SIM_PROCEDURE_WORKLOAD_P_ACTIV_DESC, PSS_Duration(double(GetProcedureWorkloadPerActivity()), hourPerDay, dayPerWeek, dayPerMonth, dayPerYear), PSS_Property::IE_T_EditDurationReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Duration7))); propSet.Add(pProp.get()); pProp.release(); // the "Cost / activation" property of the "Calculations and forecasts" group pProp.reset(new PSS_Property(IDS_ZS_BP_PROP_SIM_PROCEDURE, ZS_BP_PROP_SIM_PROCEDURE, IDS_Z_SIM_PROCEDURE_COST_P_ACTIV_NAME, M_Sim_Procedure_Cost_Per_Activ_ID, IDS_Z_SIM_PROCEDURE_COST_P_ACTIV_DESC, GetProcedureCostPerActivity(), PSS_Property::IE_T_EditNumberReadOnly, true, PSS_StringFormat(PSS_StringFormat::IE_FT_Currency, true, 2, currencySymbol))); propSet.Add(pProp.get()); pProp.release(); } return true; } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::SaveProperties(PSS_Properties::IPropertySet& propSet) { if (!PSS_Symbol::SaveProperties(propSet)) return false; // only local symbol may access to properties if (!IsLocal()) return true; // save the rules PSS_RuleListPropertiesBP* pRulesProps = static_cast<PSS_RuleListPropertiesBP*>(GetProperty(ZS_BP_PROP_RULELIST)); if (!pRulesProps) return false; PSS_Properties::IPropertyIterator it(&propSet); // empty the task list SetRuleList(_T("")); // iterate through the data list and fill the property set for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_RULELIST) switch (pProp->GetValueType()) { case PSS_Property::IE_VT_String: // if not empty, add this new task if (!pProp->GetValueString().IsEmpty()) AddRule(pProp->GetValueString()); break; } for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) { const int categoryID = pProp->GetCategoryID(); if (categoryID >= ZS_BP_PROP_RISK && categoryID <= ZS_BP_PROP_RISK + GetRiskCount()) { const int itemID = pProp->GetItemID(); const int i = categoryID - ZS_BP_PROP_RISK; if (itemID == M_Risk_Name_ID + (i * g_MaxRisksSize)) SetRiskName(i, pProp->GetValueString()); if (itemID == M_Risk_Desc_ID + (i * g_MaxRisksSize)) SetRiskDesc(i, pProp->GetValueString()); if (itemID == M_Risk_UE_ID + (i * g_MaxRisksSize)) SetRiskUE(i, pProp->GetValueFloat()); if (itemID == M_Risk_POA_ID + (i * g_MaxRisksSize)) SetRiskPOA(i, pProp->GetValueFloat()); if (itemID == M_Risk_Action_ID + (i * g_MaxRisksSize)) SetRiskAction(i, (pProp->GetValueString() == PSS_Global::GetYesFromArrayYesNo() ? 1 : 0)); } } // save the tasks PSS_TaskListPropertiesBP* pTasksProps = static_cast<PSS_TaskListPropertiesBP*>(GetProperty(ZS_BP_PROP_TASKLIST)); if (!pTasksProps) return false; // empty the task list SetTaskList(_T("")); // iterate through the data list and fill the property set for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_TASKLIST) switch (pProp->GetValueType()) { case PSS_Property::IE_VT_String: // if not empty, add this new task if (!pProp->GetValueString().IsEmpty()) AddTask(pProp->GetValueString()); break; } // save the decisions. Because the AddTask() function is called, it's not necessary to call SetProperty() PSS_DecisionListPropertiesBP* pDecisionsProps = static_cast<PSS_DecisionListPropertiesBP*>(GetProperty(ZS_BP_PROP_DECISIONLIST)); if (!pDecisionsProps) return false; // empty the decision list SetDecisionList(_T("")); // iterate through the data list and fill the property set for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_DECISIONLIST) switch (pProp->GetValueType()) { case PSS_Property::IE_VT_String: // if not empty, add this new decision if (!pProp->GetValueString().IsEmpty()) AddDecision(pProp->GetValueString()); break; } // iterate through the data list and fill the property set. Because the AddDecision() function is called, // it's not necessary to call SetProperty() for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_PROCEDURE_COST) { const int itemID = pProp->GetItemID(); switch (pProp->GetValueType()) { case PSS_Property::IE_VT_String: m_CostProcedureProp.SetValue(itemID, pProp->GetValueString()); break; case PSS_Property::IE_VT_Double: m_CostProcedureProp.SetValue(itemID, float( pProp->GetValueDouble())); break; case PSS_Property::IE_VT_Float: m_CostProcedureProp.SetValue(itemID, pProp->GetValueFloat()); break; case PSS_Property::IE_VT_Date: m_CostProcedureProp.SetValue(itemID, float(DATE(pProp->GetValueDate()))); break; case PSS_Property::IE_VT_TimeSpan: m_CostProcedureProp.SetValue(itemID, double( pProp->GetValueTimeSpan())); break; case PSS_Property::IE_VT_Duration: m_CostProcedureProp.SetValue(itemID, double( pProp->GetValueDuration())); break; } } // iterate through the data list and fill the property set for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_UNIT) if (pProp->GetItemID() == M_Unit_Double_Validation_ID) m_UnitProp.SetValue(pProp->GetItemID(), ConvertUnitDoubleValidationString2Type(pProp->GetValueString())); else { const int itemID = pProp->GetItemID(); switch (pProp->GetValueType()) { case PSS_Property::IE_VT_Double: m_UnitProp.SetValue(itemID, float(pProp->GetValueDouble())); break; case PSS_Property::IE_VT_Float: m_UnitProp.SetValue(itemID, pProp->GetValueFloat()); break; case PSS_Property::IE_VT_String: m_UnitProp.SetValue(itemID, pProp->GetValueString()); break; } } // iterate through the data list and fill the property set of combination for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) { const int categoryID = pProp->GetCategoryID(); if (categoryID >= ZS_BP_PROP_COMBINATION && categoryID <= ZS_BP_PROP_COMBINATION + GetCombinationCount()) { const int i = categoryID - ZS_BP_PROP_COMBINATION; PSS_CombinationPropertiesBP* pCombProps = GetCombinationProperty(i); if (!pCombProps) return false; const int itemID = pProp->GetItemID(); switch (pProp->GetValueType()) { case PSS_Property::IE_VT_String: pCombProps->SetValue(itemID - (i * g_MaxCombinationListSize), pProp->GetValueString()); break; case PSS_Property::IE_VT_Double: pCombProps->SetValue(itemID - (i * g_MaxCombinationListSize), float( pProp->GetValueDouble())); break; case PSS_Property::IE_VT_Float: pCombProps->SetValue(itemID - (i * g_MaxCombinationListSize), pProp->GetValueFloat()); break; case PSS_Property::IE_VT_Date: pCombProps->SetValue(itemID - (i * g_MaxCombinationListSize), float(DATE(pProp->GetValueDate()))); break; case PSS_Property::IE_VT_TimeSpan: case PSS_Property::IE_VT_Duration: THROW("Unsupported value"); } } } // iterate through the data list and fill the property set for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_SIM_PROCEDURE) { const int itemID = pProp->GetItemID(); switch (pProp->GetValueType()) { case PSS_Property::IE_VT_String: m_SimulationProperties.SetValue(itemID, pProp->GetValueString()); break; case PSS_Property::IE_VT_Double: m_SimulationProperties.SetValue(itemID, pProp->GetValueDouble()); break; case PSS_Property::IE_VT_Float: m_SimulationProperties.SetValue(itemID, pProp->GetValueFloat()); break; case PSS_Property::IE_VT_Date: m_SimulationProperties.SetValue(itemID, float(DATE(pProp->GetValueDate()))); break; case PSS_Property::IE_VT_TimeSpan: m_SimulationProperties.SetValue(itemID, double( pProp->GetValueTimeSpan())); break; case PSS_Property::IE_VT_Duration: m_SimulationProperties.SetValue(itemID, double( pProp->GetValueDuration())); break; } } RefreshAttributeTextArea(true); return true; } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::SaveProperty(PSS_Property& prop) { if (!PSS_Symbol::SaveProperty(prop)) return false; // only local symbol may access to properties if (!IsLocal()) return true; const int categoryID = prop.GetCategoryID(); if (categoryID >= ZS_BP_PROP_RISK && categoryID <= ZS_BP_PROP_RISK + GetRiskCount()) { const int itemID = prop.GetItemID(); const int i = categoryID - ZS_BP_PROP_RISK; if (itemID == M_Risk_Name_ID + (i * g_MaxRisksSize)) SetRiskName(i, prop.GetValueString()); if (itemID == M_Risk_Desc_ID + (i * g_MaxRisksSize)) SetRiskDesc(i, prop.GetValueString()); if (itemID == M_Risk_UE_ID + (i * g_MaxRisksSize)) SetRiskUE(i, prop.GetValueFloat()); if (itemID == M_Risk_POA_ID + (i * g_MaxRisksSize)) SetRiskPOA(i, prop.GetValueFloat()); if (itemID == M_Risk_Action_ID + (i * g_MaxRisksSize)) SetRiskAction(i, (prop.GetValueString() == PSS_Global::GetYesFromArrayYesNo() ? 1 : 0)); } // check if the user tried to rename a rule, if yes revert to previous name if (categoryID == ZS_BP_PROP_RULES) { const int index = (prop.GetItemID() - M_Rule_Name_ID) / g_MaxRulesSize; if (m_Rules.GetRuleName(index) != prop.GetValueString()) prop.SetValueString(m_Rules.GetRuleName(index)); } if (categoryID >= ZS_BP_PROP_COMBINATION && categoryID <= ZS_BP_PROP_COMBINATION + GetCombinationCount()) { const int i = categoryID - ZS_BP_PROP_COMBINATION; switch (prop.GetItemID() - (i * g_MaxCombinationListSize)) { case M_Combination_Name_ID: SetCombinationName (prop.GetCategoryID() - ZS_BP_PROP_COMBINATION, prop.GetValueString()); break; case M_Combination_Deliverables_ID: SetCombinationDeliverables (prop.GetCategoryID() - ZS_BP_PROP_COMBINATION, prop.GetValueString()); break; case M_Combination_Activation_Perc_ID: SetCombinationActivationPerc(prop.GetCategoryID() - ZS_BP_PROP_COMBINATION, prop.GetValueFloat()); break; case M_Combination_Master_ID: SetCombinationMaster (prop.GetCategoryID() - ZS_BP_PROP_COMBINATION, prop.GetValueString()); break; } } if (categoryID == ZS_BP_PROP_RULELIST) // if not empty, add this new rule if (!prop.GetValueString().IsEmpty()) AddRule(prop.GetValueString()); if (categoryID == ZS_BP_PROP_TASKLIST) // if not empty, add this new task if (!prop.GetValueString().IsEmpty()) AddTask(prop.GetValueString()); if (categoryID == ZS_BP_PROP_DECISIONLIST) // if not empty, add this new task if (!prop.GetValueString().IsEmpty()) AddDecision(prop.GetValueString()); // set the symbol as modified. Do nothing else, the values will be saved by the save properties method SetModifiedFlag(); return true; } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::CheckPropertyValue(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props) { return PSS_Symbol::CheckPropertyValue(prop, value, props); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::ProcessExtendedInput(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) { const int categoryID = prop.GetCategoryID(); if (categoryID >= ZS_BP_PROP_RISK && categoryID <= ZS_BP_PROP_RISK + GetRiskCount()) { const int i = categoryID - ZS_BP_PROP_RISK; PSS_ProcessGraphModelMdl* pModel = dynamic_cast<PSS_ProcessGraphModelMdl*>(GetRootModel()); CString currencySymbol = PSS_Global::GetLocaleCurrency(); // get the model currency symbol if (pModel) { PSS_ProcessGraphModelDoc* pDoc = dynamic_cast<PSS_ProcessGraphModelDoc*>(pModel->GetDocument()); if (pDoc) currencySymbol = pDoc->GetCurrencySymbol(); } CString noRiskType; noRiskType.LoadString(IDS_NO_RISK_TYPE); PSS_RiskOptionsDlg riskOptions(GetRiskName(i), GetRiskDesc(i), GetRiskType(i).IsEmpty() ? noRiskType : GetRiskType(i), GetRiskImpact(i), GetRiskProbability(i), GetRiskUE(i), GetRiskPOA(i), GetRiskAction(i), currencySymbol); if (riskOptions.DoModal() == IDOK) { SetRiskName (i, riskOptions.GetRiskTitle()); SetRiskDesc (i, riskOptions.GetRiskDescription()); SetRiskType (i, riskOptions.GetRiskType()); SetRiskImpact (i, riskOptions.GetRiskImpact()); SetRiskProbability(i, riskOptions.GetRiskProbability()); SetRiskSeverity (i, riskOptions.GetRiskSeverity()); SetRiskUE (i, riskOptions.GetRiskUE()); SetRiskPOA (i, riskOptions.GetRiskPOA()); SetRiskAction (i, riskOptions.GetRiskAction()); SetModifiedFlag(TRUE); refresh = true; return true; } } if (categoryID == ZS_BP_PROP_UNIT && prop.GetItemID() == M_Unit_Name_ID) { PSS_ProcessGraphModelMdl* pModel = dynamic_cast<PSS_ProcessGraphModelMdl*>(GetOwnerModel()); if (pModel) { PSS_SelectUserGroupDlg dlg(IDS_SELECTAGROUP_T, pModel->GetMainUserGroup(), true, false); if (dlg.DoModal() == IDOK) { PSS_UserEntity* pUserEntity = dlg.GetSelectedUserEntity(); if (pUserEntity) { value = pUserEntity->GetEntityName(); // change the disabled property unit GUID PSS_Properties::IPropertyIterator it(&props); for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_UNIT && pProp->GetItemID() == M_Unit_GUID_ID) { pProp->SetValueString(pUserEntity->GetGUID()); break; } return true; } } } } else if (categoryID >= ZS_BP_PROP_COMBINATION && categoryID <= ZS_BP_PROP_COMBINATION + GetCombinationCount()) { const int i = categoryID - ZS_BP_PROP_COMBINATION; switch (prop.GetItemID() - (i * g_MaxCombinationListSize)) { case M_Combination_Deliverables_ID: { // get the deliverables CString enteringDeliverables; GetEnteringUpDeliverable(enteringDeliverables); CString availableDeliverables = GetAvailableDeliverables(enteringDeliverables); // show the dialog PSS_AddRemoveCombinationDeliverableDlg dlg(availableDeliverables, value); if (dlg.DoModal() == IDOK) { value = dlg.GetDeliverables(); return true; } break; } case M_Combination_Master_ID: { PSS_SelectMasterDeliverableDlg dlg(GetCombinationDeliverables(i), value); if (dlg.DoModal() == IDOK) { value = dlg.GetMaster(); return true; } break; } } } return PSS_Symbol::ProcessExtendedInput(prop, value, props, refresh); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::ProcessMenuCommand(int menuCmdID, PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) { const int categoryID = prop.GetCategoryID(); if (categoryID >= ZS_BP_PROP_RISK && categoryID <= ZS_BP_PROP_RISK + GetRiskCount()) { switch (menuCmdID) { case ID_ADD_NEWRISK: OnAddNewRisk (prop, value, props, refresh); break; case ID_DEL_CURRENTRISK: OnDelCurrentRisk(prop, value, props, refresh); break; default: break; } return true; } if (categoryID >= ZS_BP_PROP_COMBINATION && categoryID <= ZS_BP_PROP_COMBINATION + GetCombinationCount()) { switch (menuCmdID) { case ID_ADD_NEWCOMBINATION: OnAddNewCombination (prop, value, props, refresh); break; case ID_DEL_CURRENTCOMBINATION: OnDelCurrentCombination (prop, value, props, refresh); break; case ID_ADD_DELIVERABLE_COMBINATION: OnAddDeliverableCombination(prop, value, props, refresh); break; case ID_DEL_DELIVERABLE_COMBINATION: OnDelDeliverableCombination(prop, value, props, refresh); break; default: break; } return true; } if (categoryID == ZS_BP_PROP_RULES) switch (menuCmdID) { case ID_DEL_CURRENTRULE: { const int index = (prop.GetItemID() - M_Rule_Name_ID) / g_MaxRulesSize; m_Rules.DeleteRule(index); refresh = true; break; } default: break; } return PSS_Symbol::ProcessMenuCommand(menuCmdID, prop, value, props, refresh); } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetAttributeString(PSS_PropertyAttributes* pAttributes) const { return PSS_Symbol::GetAttributeString(pAttributes); } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetEnteringUpDeliverable(CString& deliverables) { int counter = 0; CODEdgeArray edges; // keep only deliverable symbols if (GetEnteringUpDeliverable(edges) > 0) { // initialize the token with ; as separator PSS_Tokenizer token; const int edgeCount = edges.GetSize(); for (int i = 0; i < edgeCount; ++i) { IODEdge* pIEdge = edges.GetAt(i); PSS_DeliverableLinkSymbolBP* pComp = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge); if (pComp) { token.AddToken(pComp->GetSymbolName()); ++counter; } } // assign the resulting string deliverables = token.GetString(); } return counter; } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetEnteringUpDeliverable(CODEdgeArray& edges) { // get all procedure entering up edges GetEdgesEntering_Up(edges); CODComponentSet* pSet = GetReferenceSymbols(); CODComponentSet internalSet; // get all edges from referenced procedures and local symbol if a referenced symbol is defined if (!IsLocal()) { if (!pSet) pSet = &internalSet; CODComponent* pLocalSymbol = GetLocalSymbol(); if (pLocalSymbol) pSet->Add(pLocalSymbol); } if (pSet) { const int setCount = pSet->GetSize(); for (int i = 0; i < setCount; ++i) { PSS_ProcedureSymbolBP* pComp = dynamic_cast<PSS_ProcedureSymbolBP*>(pSet->GetAt(i)); if (pComp) { CODEdgeArray additionalEdges; pComp->GetEdgesEntering_Up(additionalEdges); const int edgeCount = additionalEdges.GetSize(); // copy additional edges to the main edges for (int j = 0; j < edgeCount; ++j) // get the link edges.AddEdge(additionalEdges.GetAt(j)); } } } // keep only deliverable symbols return int(PSS_ODSymbolManipulator::KeepOnlyLinksISA(edges, RUNTIME_CLASS(PSS_DeliverableLinkSymbolBP))); } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetLeavingDownDeliverable(CString& deliverables) { int counter = 0; CODEdgeArray edges; if (GetLeavingDownDeliverable(edges) > 0) { // initialize the token with ; as separator PSS_Tokenizer token; const int edgeCount = edges.GetSize(); for (int i = 0; i < edgeCount; ++i) { IODEdge* pIEdge = edges.GetAt(i); PSS_DeliverableLinkSymbolBP* pComp = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge); if (pComp) { token.AddToken(pComp->GetSymbolName()); ++counter; } } // assign the resulting string deliverables = token.GetString(); } return counter; } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetLeavingDownDeliverable(CODEdgeArray& edges) { // get all leaving down edges GetEdgesLeaving_Down(edges); CODComponentSet* pSet = GetReferenceSymbols(); CODComponentSet internalSet; // get all edges from referenced procedures and local symbol if a referenced symbol is defined if (!IsLocal()) { if (!pSet) pSet = &internalSet; CODComponent* pLocalSymbol = GetLocalSymbol(); if (pLocalSymbol) pSet->Add(pLocalSymbol); } if (pSet) { const int setCount = pSet->GetSize(); for (int i = 0; i < setCount; ++i) { PSS_ProcedureSymbolBP* pComp = dynamic_cast<PSS_ProcedureSymbolBP*>(pSet->GetAt(i)); if (pComp) { CODEdgeArray additionalEdges; pComp->GetEdgesLeaving_Down(additionalEdges); const int edgeCount = additionalEdges.GetSize(); // copy additional edges to the main edges for (int j = 0; j < edgeCount; ++j) // get the link edges.AddEdge(additionalEdges.GetAt(j)); } } } // keep only deliverable symbols return int(PSS_ODSymbolManipulator::KeepOnlyLinksISA(edges, RUNTIME_CLASS(PSS_DeliverableLinkSymbolBP))); } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetLeavingLeftDeliverable(CString& deliverables) { int counter = 0; CODEdgeArray edges; if (GetLeavingLeftDeliverable(edges) > 0) { // initialize the token with ; as separator PSS_Tokenizer token; const int edgeCount = edges.GetSize(); for (int i = 0; i < edgeCount; ++i) { IODEdge* pIEdge = edges.GetAt(i); PSS_DeliverableLinkSymbolBP* pComp = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge); if (pComp) { token.AddToken(pComp->GetSymbolName()); ++counter; } } // assign the resulting string deliverables = token.GetString(); } return counter; } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetLeavingLeftDeliverable(CODEdgeArray& edges) { // get all leaving left edges GetEdgesLeaving_Left(edges); CODComponentSet* pSet = GetReferenceSymbols(); CODComponentSet internalSet; // get all edges from referenced procedures and local symbol if a referenced symbol is defined if (!IsLocal()) { if (!pSet) pSet = &internalSet; CODComponent* pLocalSymbol = GetLocalSymbol(); if (pLocalSymbol) pSet->Add(pLocalSymbol); } if (pSet) { const int setCount = pSet->GetSize(); for (int i = 0; i < setCount; ++i) { PSS_ProcedureSymbolBP* pComp = dynamic_cast<PSS_ProcedureSymbolBP*>(pSet->GetAt(i)); if (pComp) { CODEdgeArray additionalEdges; pComp->GetEdgesLeaving_Left(additionalEdges); const int edgeCount = additionalEdges.GetSize(); // copy additional edges to the main edges for (int j = 0; j < edgeCount; ++j) // get the link edges.AddEdge(additionalEdges.GetAt(j)); } } } // keep only deliverable symbols return (int)PSS_ODSymbolManipulator::KeepOnlyLinksISA(edges, RUNTIME_CLASS(PSS_DeliverableLinkSymbolBP)); } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetLeavingRightDeliverable(CString& deliverables) { int counter = 0; CODEdgeArray edges; if (GetLeavingRightDeliverable(edges) > 0) { // initialize the token with ; as separator PSS_Tokenizer token; const int edgeCount = edges.GetSize(); for (int i = 0; i < edgeCount; ++i) { IODEdge* pIEdge = edges.GetAt(i); PSS_DeliverableLinkSymbolBP* pComp = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge); if (pComp) { token.AddToken(pComp->GetSymbolName()); ++counter; } } // assign the resulting string deliverables = token.GetString(); } return counter; } //--------------------------------------------------------------------------- int PSS_ProcedureSymbolBP::GetLeavingRightDeliverable(CODEdgeArray& edges) { // get all leaving right edges GetEdgesLeaving_Right(edges); // get all edges from referenced procedures and local symbol if a referenced symbol is defined CODComponentSet* pSet = GetReferenceSymbols(); CODComponentSet internalSet; if (!IsLocal()) { if (!pSet) pSet = &internalSet; CODComponent* pLocalSymbol = GetLocalSymbol(); if (pLocalSymbol) pSet->Add(pLocalSymbol); } if (pSet) { const int setCount = pSet->GetSize(); for (int i = 0; i < setCount; ++i) { PSS_ProcedureSymbolBP* pComp = dynamic_cast<PSS_ProcedureSymbolBP*>(pSet->GetAt(i)); if (pComp) { CODEdgeArray additionalEdges; pComp->GetEdgesLeaving_Right(additionalEdges); const int edgeCount = additionalEdges.GetSize(); // copy additional edges to the main edges for (int j = 0; j < edgeCount; ++j) // get the link edges.AddEdge(additionalEdges.GetAt(j)); } } } // keep only deliverable symbols return (int)PSS_ODSymbolManipulator::KeepOnlyLinksISA(edges, RUNTIME_CLASS(PSS_DeliverableLinkSymbolBP)); } //--------------------------------------------------------------------------- PSS_AnnualNumberPropertiesBP PSS_ProcedureSymbolBP::CalculateProcedureActivation() { // get all entering deliverables CODEdgeArray edges; // get all entering up edges if (!GetEnteringUpDeliverable(edges)) return 0; PSS_AnnualNumberPropertiesBP ProcedureActivation(0); // for each deliverables, calculate the max procedure activation for (int i = 0; i < edges.GetSize(); ++i) { IODEdge* pIEdge = edges.GetAt(i); PSS_DeliverableLinkSymbolBP* pDeliverable = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge); if (!pDeliverable) continue; // check if it's a local symbol if (!pDeliverable->IsLocal()) { // get the local symbol pDeliverable = dynamic_cast<PSS_DeliverableLinkSymbolBP*>(pDeliverable->GetLocalSymbol()); if (!pDeliverable) return false; } const int count = GetCombinationCount(); // iterate through combination and check if this deliverable is defined as a master. If yes, // add it to the procedure activation for (int j = 0; j < count; ++j) { TRACE1("Master = %s\n", GetCombinationMaster(j)); TRACE1("Livrable = %s\n", pDeliverable->GetSymbolName()); // found a master? if (!GetCombinationMaster(j).IsEmpty() && GetCombinationMaster(j) == pDeliverable->GetSymbolName()) ProcedureActivation += pDeliverable->GetQuantity(); } } return ProcedureActivation; } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetRuleList() const { PSS_RuleListPropertiesBP* pProps = static_cast<PSS_RuleListPropertiesBP*>(GetProperty(ZS_BP_PROP_RULELIST)); if (!pProps) return _T(""); return pProps->GetRuleList(); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::SetRuleList(const CString& value) { PSS_RuleListPropertiesBP* pProps = static_cast<PSS_RuleListPropertiesBP*>(GetProperty(ZS_BP_PROP_RULELIST)); if (pProps) { PSS_RuleListPropertiesBP props(*pProps); props.SetRuleList(value); SetProperty(&props); } } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::RuleExist(const CString& value) { // initialize the token with the rule list and with the default ; as separator PSS_Tokenizer token(GetRuleList()); return token.TokenExist(value); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::AddRule(const CString& value) { // initialize the token with the rule list and with the default ; as separator PSS_Tokenizer token(GetRuleList()); // if the new rule was added successfully, update the rule list if (token.AddUniqueToken(value)) { // add the value to the history CString key; key.LoadString(IDS_ZS_BP_PROP_RULELST_TITLE); PSS_Global::GetHistoricValueManager().AddHistoryValue(key, value); // set the new rule string SetRuleList(token.GetString()); } } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::RemoveRule(const CString& value) { // initialize the token with the rule list and with the default ; as separator PSS_Tokenizer token(GetRuleList()); // if the rule was removed successfully, update the rule list if (token.RemoveToken(value)) SetRuleList(token.GetString()); } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetRuleAt(std::size_t index) { // initialize the token with the rule list and with the default ; as separator PSS_Tokenizer token(GetRuleList()); CString value; // get the token at index if (token.GetTokenAt(index, value)) return value; return _T(""); } //--------------------------------------------------------------------------- std::size_t PSS_ProcedureSymbolBP::GetRuleCount() const { // initialize the token with the rule list and with the default ; as separator PSS_Tokenizer token(GetRuleList()); return token.GetTokenCount(); } //--------------------------------------------------------------------------- BOOL PSS_ProcedureSymbolBP::ContainsRule(const CString& ruleName) const { const int ruleCount = m_Rules.GetRulesCount(); for (int i = 0; i < ruleCount; ++i) if (m_Rules.GetRuleName(i) == ruleName) return TRUE; return FALSE; } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::CheckRulesSync(CStringArray& rulesList) { CODModel* pModel = GetRootModel(); if (pModel) return; if (m_Rules.GetRulesCount() > 0) { PSS_ProcessGraphModelMdlBP* pOwnerModel = dynamic_cast<PSS_ProcessGraphModelMdlBP*>(GetOwnerModel()); PSS_LogicalRulesEntity* pMainRule = NULL; if (pOwnerModel) pMainRule = pOwnerModel->GetMainLogicalRules(); if (!pMainRule) return; const int ruleCount = m_Rules.GetRulesCount(); for (int i = 0; i < ruleCount; ++i) { const CString safeName = GetRuleNameByGUID(pMainRule, m_Rules.GetRuleGUID(i)); if (safeName.IsEmpty()) rulesList.Add(m_Rules.GetRuleName(i)); } } } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetTaskList() const { PSS_TaskListPropertiesBP* pProps = static_cast<PSS_TaskListPropertiesBP*>(GetProperty(ZS_BP_PROP_TASKLIST)); if (!pProps) return _T(""); return pProps->GetTaskList(); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::SetTaskList(const CString& value) { PSS_TaskListPropertiesBP* pProps = static_cast<PSS_TaskListPropertiesBP*>(GetProperty(ZS_BP_PROP_TASKLIST)); if (pProps) { PSS_TaskListPropertiesBP props(*pProps); props.SetTaskList(value); SetProperty(&props); } } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::TaskExist(const CString& value) { // initialize the token with the task list and with the default ; as separator PSS_Tokenizer token(GetTaskList()); return token.TokenExist(value); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::AddTask(const CString& value) { // initialize the token with the task list and with the default ; as separator PSS_Tokenizer token(GetTaskList()); // if the new task was added successfully, update the task list if (token.AddUniqueToken(value)) { // add the value to the history CString key; key.LoadString(IDS_ZS_BP_PROP_PROCEDURE_TSKLST_TITLE); PSS_Global::GetHistoricValueManager().AddHistoryValue(key, value); // set the new task string SetTaskList(token.GetString()); } } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::RemoveTask(const CString& value) { // initialize the token with the task list and with the default ; as separator PSS_Tokenizer token(GetTaskList()); // if the new task was removed successfully, update the task list if (token.RemoveToken(value)) SetTaskList(token.GetString()); } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetTaskAt(std::size_t index) { // Initialize the token with the task list and with the default ; as separator PSS_Tokenizer token(GetTaskList()); CString value; // get the token at index if (token.GetTokenAt(index, value)) return value; return _T(""); } //--------------------------------------------------------------------------- std::size_t PSS_ProcedureSymbolBP::GetTaskCount() const { // initialize the token with the task list and with the default ; as separator PSS_Tokenizer token(GetTaskList()); return token.GetTokenCount(); } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetDecisionList() const { PSS_DecisionListPropertiesBP* pProps = static_cast<PSS_DecisionListPropertiesBP*>(GetProperty(ZS_BP_PROP_DECISIONLIST)); if (!pProps) return _T(""); return pProps->GetDecisionList(); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::SetDecisionList(const CString& value) { PSS_DecisionListPropertiesBP* pProps = static_cast<PSS_DecisionListPropertiesBP*>(GetProperty(ZS_BP_PROP_DECISIONLIST)); if (pProps) { PSS_DecisionListPropertiesBP props(*pProps); props.SetDecisionList(value); SetProperty(&props); } } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::DecisionExist(const CString& value) { // initialize the token with the decision list and with the default ; as separator PSS_Tokenizer token(GetDecisionList()); return token.TokenExist(value); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::AddDecision(const CString& value) { // initialize the token with the decision list and with the default ; as separator PSS_Tokenizer token(GetDecisionList()); // if the new decision was added successfully, update the decision list if (token.AddUniqueToken(value)) { // add the value to the history CString key; key.LoadString(IDS_ZS_BP_PROP_PROCEDURE_DECLST_TITLE); PSS_Global::GetHistoricValueManager().AddHistoryValue(key, value); // set the new decision string SetDecisionList(token.GetString()); } } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::RemoveDecision(const CString& value) { // initialize the token with the decision list and with the default ; as separator PSS_Tokenizer token(GetDecisionList()); // if the new decision was removed successfully, update the decision list if (token.RemoveToken(value)) SetDecisionList(token.GetString()); } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetDecisionAt(std::size_t index) { // initialize the token with the decision list and with the default ; as separator PSS_Tokenizer token(GetDecisionList()); CString value; // get the decision at index if (token.GetTokenAt(index, value)) return value; return _T(""); } //--------------------------------------------------------------------------- std::size_t PSS_ProcedureSymbolBP::GetDecisionCount() const { // initialize the token with the decision list and with the default ; as separator PSS_Tokenizer token(GetDecisionList()); return token.GetTokenCount(); } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetRiskType(std::size_t index) const { PSS_Application* pApp = PSS_Application::Instance(); if (!pApp) return _T(""); PSS_MainForm* pMainForm = pApp->GetMainForm(); if (!pMainForm) return _T(""); PSS_RiskTypeContainer* pContainer = pMainForm->GetRiskTypeContainer(); if (!pContainer) return _T(""); const int count = pContainer->GetElementCount(); const CString riskType = m_Risks.GetRiskType(index); for (int i = 0; i < count; ++i) if (riskType == pContainer->GetElementAt(i)) return m_Risks.GetRiskType(index); return _T(""); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::Serialize(CArchive& ar) { PSS_Symbol::Serialize(ar); // only if the object is serialized from or to a document if (ar.m_pDocument) { // serialize the combinations m_Combinations.Serialize(ar); m_SimulationProperties.Serialize(ar); PSS_BaseDocument* pDocument = dynamic_cast<PSS_BaseDocument*>(ar.m_pDocument); // serialize the risks if (pDocument && pDocument->GetDocumentStamp().GetInternalVersion() >= 27) m_Risks.Serialize(ar); // serialize the rules if (ar.IsStoring()) m_Rules.Serialize(ar); else if (pDocument && pDocument->GetDocumentStamp().GetInternalVersion() >= 26) m_Rules.Serialize(ar); if (ar.IsStoring() || (pDocument && pDocument->GetDocumentStamp().GetInternalVersion() >= 19)) { m_UnitProp.Serialize(ar); m_CostProcedureProp.Serialize(ar); } else { TRACE("PSS_ProcedureSymbolBP::Serialize - Start read\n"); // transfer the properties to new format PSS_CostPropertiesProcedureBP_Beta1* pCostProps = static_cast<PSS_CostPropertiesProcedureBP_Beta1*>(GetProperty(ZS_BP_PROP_PROCEDURE_COST)); if (pCostProps) { SetMultiplier(pCostProps->GetMultiplier()); SetProcessingTime(pCostProps->GetProcessingTime()); SetUnitaryCost(pCostProps->GetUnitaryCost()); } PSS_UnitPropertiesBP_Beta1* pUnitProps = static_cast<PSS_UnitPropertiesBP_Beta1*>(GetProperty(ZS_BP_PROP_UNIT)); if (pUnitProps) { SetUnitName(pUnitProps->GetUnitName()); SetUnitCost(pUnitProps->GetUnitCost()); } // set the master if only one deliverable was found for the combination const int count = GetCombinationCount(); for (int i = 0; i < count; ++i) { const CString deliverables = GetCombinationDeliverables(i); // if no separator, only one deliverable, so set this deliverable as the master one if (deliverables.Find(';') == -1) SetCombinationMaster(i, deliverables); } TRACE("PSS_ProcedureSymbolBP::Serialize - End read\n"); } } } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnSymbolNameChanged(CODComponent& comp, const CString& oldName) { PSS_LinkSymbol* pSymbol = dynamic_cast<PSS_LinkSymbol*>(&comp); if (pSymbol) ReplaceDeliverable(oldName, pSymbol->GetSymbolName()); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::OnPostPropertyChanged(PSS_Property& prop, PSS_Properties::IPropertySet& props, bool& refresh) { // only local symbol may access to properties if (!IsLocal()) return false; bool result = false; if (prop.GetCategoryID() >= ZS_BP_PROP_COMBINATION && prop.GetCategoryID() <= ZS_BP_PROP_COMBINATION + GetCombinationCount()) { const int i = prop.GetCategoryID() - ZS_BP_PROP_COMBINATION; switch (prop.GetItemID() - (i * g_MaxCombinationListSize)) { case M_Combination_Deliverables_ID: { const float maxPercent = GetMaxActivationPerc(GetCombinationMaster(prop.GetCategoryID() - ZS_BP_PROP_COMBINATION)); PSS_Properties::IPropertyIterator it(&props); bool found = false; // set the value to the property for (PSS_Property* pProp = it.GetFirst(); pProp && !found; pProp = it.GetNext()) { if (!pProp || ((pProp->GetCategoryID() - ZS_BP_PROP_COMBINATION) != i)) continue; if (pProp->GetItemID() - (i * g_MaxCombinationListSize) == M_Combination_Activation_Perc_ID) { pProp->SetValueFloat(maxPercent); found = true; } } // change the return value if found if (found) result = true; break; } default: break; } } else if (prop.GetCategoryID() == ZS_BP_PROP_UNIT && prop.GetItemID() == M_Unit_Name_ID) { PSS_Properties::IPropertyIterator it(&props); CString guid; // iterate through the properties and change the unit cost to the property value for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_UNIT && pProp->GetItemID() == M_Unit_GUID_ID) { guid = pProp->GetValueString(); break; } if (!guid.IsEmpty()) for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_UNIT && pProp->GetItemID() == M_Unit_Cost_ID) { bool error; float unitCost = RetrieveUnitCost(guid, error); if (!error) { pProp->SetValueFloat(unitCost); result = true; } break; } } else if (prop.GetCategoryID() == ZS_BP_PROP_RULELIST) { // change the return value to reload the properties. Need to reload since the rule list has an empty rule. // If the user fills it, need to enable a new empty one. And if the user remove one rule, need also to // disable one from the property list PSS_Properties::IPropertyIterator it(&props); std::size_t counterEnableEmpty = 0; // iterate through the properties and change their enabled flag. To change it, need to check if it is a new // property that need to be enabled or not, then need to ensure that only an empty property is enable for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_RULELIST) { // if the string is not empty, set its enabled flag to true if (!pProp->GetValueString().IsEmpty()) pProp->SetEnabled(true); // if the string is empty, check if its enabled flag is set and add it to the counter. // Enable or disable it according to if the counter is equal or not to 1 if (pProp->GetValueString().IsEmpty()) { if (pProp->GetEnabled()) ++counterEnableEmpty; else // if not at least one empty element if (counterEnableEmpty < 1) { pProp->SetEnabled(true); ++counterEnableEmpty; } // if the counter is greater than 1, need to disable the empty element if (counterEnableEmpty > 1) { --counterEnableEmpty; pProp->SetEnabled(false); } } } result = true; } else if (prop.GetCategoryID() == ZS_BP_PROP_TASKLIST) { // change the return value to reload the properties. Need to reload since the rule list has an empty task. // If the user fills it, need to enable a new empty one. And if the user remove one task, need also to // disable one from the property list PSS_Properties::IPropertyIterator it(&props); std::size_t counterEnableEmpty = 0; // iterate through the properties and change their enabled flag. To change it, need to check if it is a new // property that need to be enabled or not, then need to ensure that only an empty property is enable for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_TASKLIST) { // if the string is not empty, set the enabled flag to true if (!pProp->GetValueString().IsEmpty()) pProp->SetEnabled(true); // if the string is empty, check if its enabled flag is set and add it to the counter. // Enable or disable it according to if the counter is equal or not to 1 if (pProp->GetValueString().IsEmpty()) { if (pProp->GetEnabled()) ++counterEnableEmpty; else // if not at least one empty element if (counterEnableEmpty < 1) { pProp->SetEnabled(true); ++counterEnableEmpty; } // if the counter is greater than 1, need to disable the empty element if (counterEnableEmpty > 1) { --counterEnableEmpty; pProp->SetEnabled(false); } } } result = true; } else if (prop.GetCategoryID() == ZS_BP_PROP_DECISIONLIST) { // change the return value to reload the properties. Need to reload since the decision list has an empty decision. // If the user fills it, need to enable a new empty one. And if the user remove one decision, need also to // disable one from the property list PSS_Properties::IPropertyIterator it(&props); std::size_t counterEnableEmpty = 0; // iterate through the properties and change their enabled flag. To change it, need to check if it is a new // property that need to be enabled or not, then need to ensure that only an empty property is enable for (PSS_Property* pProp = it.GetFirst(); pProp; pProp = it.GetNext()) if (pProp->GetCategoryID() == ZS_BP_PROP_DECISIONLIST) { // if the string is not empty, set its enabled flag to true if (!pProp->GetValueString().IsEmpty()) pProp->SetEnabled(true); // if the string is empty, check if its enabled flag is set and add it to the counter. // Enable or disable it according to if the counter is equal or not to 1 if (pProp->GetValueString().IsEmpty()) { if (pProp->GetEnabled() == true) ++counterEnableEmpty; else // if not at least one empty element if (counterEnableEmpty < 1) { pProp->SetEnabled(true); ++counterEnableEmpty; } // if the counter is greater than 1, need to disable the empty element if (counterEnableEmpty > 1) { --counterEnableEmpty; pProp->SetEnabled(false); } } } result = true; } if (!result) return PSS_Symbol::OnPostPropertyChanged(prop, props, refresh); return result; } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::OnDropInternalPropertyItem(PSS_Property& srcProperty, PSS_Property& dstProperty, bool top2Down, PSS_Properties::IPropertySet& props) { bool result = ::SwapInternalPropertyItem(srcProperty, dstProperty, top2Down, props, ZS_BP_PROP_TASKLIST); if (result) return true; result = ::SwapInternalPropertyItem(srcProperty, dstProperty, top2Down, props, ZS_BP_PROP_RULELIST); if (result) return true; result = ::SwapInternalPropertyItem(srcProperty, dstProperty, top2Down, props, ZS_BP_PROP_RULES); if (result) { const int srcIndex = (srcProperty.GetItemID() - M_Rule_Name_ID) / g_MaxRulesSize; const int dstIndex = (dstProperty.GetItemID() - M_Rule_Name_ID) / g_MaxRulesSize; const CString srcRuleName = m_Rules.GetRuleName(srcIndex); const CString srcRuleDesc = m_Rules.GetRuleDescription(srcIndex); const CString srcRuleGUID = m_Rules.GetRuleGUID(srcIndex); const CString dstRuleName = m_Rules.GetRuleName(dstIndex); const CString dstRuleDesc = m_Rules.GetRuleDescription(dstIndex); const CString dstRuleGUID = m_Rules.GetRuleGUID(dstIndex); m_Rules.SetRuleName(srcIndex, dstRuleName); m_Rules.SetRuleDescription(srcIndex, dstRuleDesc); m_Rules.SetRuleGUID(srcIndex, dstRuleGUID); m_Rules.SetRuleName(dstIndex, srcRuleName); m_Rules.SetRuleDescription(dstIndex, srcRuleDesc); m_Rules.SetRuleGUID(dstIndex, srcRuleGUID); return true; } // otherwise, do it for decisions return ::SwapInternalPropertyItem(srcProperty, dstProperty, top2Down, props, ZS_BP_PROP_DECISIONLIST); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::OnFillDefaultAttributes(PSS_PropertyAttributes* pAttributes) { if (!pAttributes) return false; PSS_PropertyAttributes& attributes = PSS_ModelGlobal::GetGlobalPropertyAttributes(GetObjectTypeID()); // if global attributes were defined, copy them if (attributes.GetAttributeCount() > 0) *pAttributes = attributes; else { // add the reference number pAttributes->AddAttribute(ZS_BP_PROP_BASIC, M_Symbol_Number_ID); // add the unit name pAttributes->AddAttribute(ZS_BP_PROP_UNIT, M_Unit_Name_ID); // no item labels pAttributes->SetShowTitleText(false); } return PSS_Symbol::OnFillDefaultAttributes(pAttributes); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::OnChangeAttributes(PSS_PropertyAttributes* pAttributes) { return PSS_Symbol::OnChangeAttributes(pAttributes); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnConnect(CODConnection* pConnection) { PSS_Symbol::OnConnect(pConnection); CheckInitialCombination(); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnDisconnect(CODConnection* pConnection) { PSS_Symbol::OnDisconnect(pConnection); CheckInitialCombination(); } //--------------------------------------------------------------------------- BOOL PSS_ProcedureSymbolBP::OnConnectionMove(CODConnection* pConnection) { return PSS_Symbol::OnConnectionMove(pConnection); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnLinkDisconnect(CODLinkComponent* pLink) { PSS_LinkSymbol* pLinkSymbol = dynamic_cast<PSS_LinkSymbol*>(pLink); if (pLinkSymbol) DeleteDeliverableFromAllCombinations(pLinkSymbol->GetSymbolName()); } //--------------------------------------------------------------------------- BOOL PSS_ProcedureSymbolBP::OnDoubleClick() { return FALSE; } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnUpdate(PSS_Subject* pSubject, PSS_ObserverMsg* pMsg) { PSS_Symbol::OnUpdate(pSubject, pMsg); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnDraw(CDC* pDC) { PSS_Symbol::OnDraw(pDC); } //--------------------------------------------------------------------------- bool PSS_ProcedureSymbolBP::OnToolTip(CString& toolTipText, const CPoint& point, PSS_ToolTip::IEToolTipMode mode) { toolTipText.Format(IDS_FS_BPPROCEDURE_TOOLTIP, (const char*)GetSymbolName(), (const char*)GetSymbolComment(), (const char*)GetSymbolReferenceNumberStr()); if (mode == PSS_Symbol::IE_TT_Design) { // todo -cFeature -oJean: need to implement the result of the control checking } return true; } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::AdjustElementPosition() { PSS_Symbol::AdjustElementPosition(); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::CheckInitialCombination() { // check if only one combination. If it's the case, set all deliverables to the combination if (GetCombinationCount() == 1) { // get all deliverables CString enteringDeliverables; GetEnteringUpDeliverable(enteringDeliverables); // set it SetCombinationDeliverables(0, enteringDeliverables); // if no entering deliverables, remove the master if (enteringDeliverables.IsEmpty()) SetCombinationMaster(0, enteringDeliverables); else { // if there is only one deliverable, it's the master PSS_Tokenizer token(enteringDeliverables); if (token.GetTokenCount() == 1) { CString value; // get the token at index if (token.GetTokenAt(0, value)) SetCombinationMaster(0, value); } } SetCombinationActivationPerc(0, GetMaxActivationPerc(GetCombinationMaster(0))); } } //--------------------------------------------------------------------------- float PSS_ProcedureSymbolBP::GetMaxActivationPerc(const CString& master) { if (master.IsEmpty()) return 0.0f; double sum = 0; double masterQuantity = 0; CODEdgeArray edges; // get all procedures entering up edges if (GetEnteringUpDeliverable(edges) > 0) { const int edgeCount = edges.GetSize(); for (int i = 0; i < edgeCount; ++i) { IODEdge* pIEdge = edges.GetAt(i); PSS_DeliverableLinkSymbolBP* pComp = static_cast<PSS_DeliverableLinkSymbolBP*>(pIEdge); // check if it's a local symbol if (!pComp->IsLocal()) // get the local symbol pComp = dynamic_cast<PSS_DeliverableLinkSymbolBP*>(pComp->GetLocalSymbol()); if (pComp) { // check if the component is the master if (pComp->GetSymbolName() == master) masterQuantity = (double)pComp->GetQuantity(); // iterate through combinations and check if the component is the combination master, // add its quantity to the sum const int combinationCount = GetCombinationCount(); for (int i = 0; i < combinationCount; ++i) if (pComp->GetSymbolName() == GetCombinationMaster(i)) sum += (double)pComp->GetQuantity(); } } } if (!sum) return 0.0f; return float(masterQuantity / sum); } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnAddNewCombination(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) { // add a new combination if (AddNewCombination() >= 0) { // set the refresh flag to true refresh = true; SetModifiedFlag(TRUE); } } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnDelCurrentCombination(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) { const int count = GetCombinationCount(); if (count <= 1) { // cannot delete all combinations PSS_MsgBox mBox; mBox.Show(IDS_CANNOTDELETE_ALLCOMBINATIONS, MB_OK); return; } // otherwise, delete the currently selected combination const int index = prop.GetCategoryID() - ZS_BP_PROP_COMBINATION; if (DeleteCombination(index)) { // set the refresh flag to true refresh = true; SetModifiedFlag(TRUE); } } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnAddDeliverableCombination(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) {} //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnDelDeliverableCombination(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) {} //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnAddNewRisk(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) { // sdd a new risk if (AddNewRisk() >= 0) { // set the refresh flag to true refresh = true; SetModifiedFlag(TRUE); } } //--------------------------------------------------------------------------- void PSS_ProcedureSymbolBP::OnDelCurrentRisk(PSS_Property& prop, CString& value, PSS_Properties::IPropertySet& props, bool& refresh) { const int count = GetRiskCount(); if (count <= 1) { // cannot delete all risks PSS_MsgBox mBox; mBox.Show(IDS_CANNOTDELETE_ALLRISKS, MB_OK); return; } // otherwise, delete the currently selected risk const int index = prop.GetCategoryID() - ZS_BP_PROP_RISK; if (DeleteRisk(index)) { // set the refresh flag to true refresh = true; SetModifiedFlag(TRUE); } } //--------------------------------------------------------------------------- CString PSS_ProcedureSymbolBP::GetRuleNameByGUID(PSS_LogicalRulesEntity* pRule, const CString& ruleGUID) { if (!pRule) return _T(""); if (pRule->GetGUID() == ruleGUID) return pRule->GetEntityName(); if (pRule->ContainEntity()) { const int count = pRule->GetEntityCount(); for (int i = 0; i < count; ++i) { PSS_LogicalRulesEntity* pEntity = dynamic_cast<PSS_LogicalRulesEntity*>(pRule->GetEntityAt(i)); if (!pEntity) continue; const CString name = GetRuleNameByGUID(pEntity, ruleGUID); if (!name.IsEmpty()) return name; } } return _T(""); } //---------------------------------------------------------------------------
40.514943
158
0.526679
Jeanmilost
cc678fb574dfe265aadd588c689b0d1efdba0f13
231
hpp
C++
Spiel/src/Graveyard/rendering/RenderBuffer.hpp
Ipotrick/CPP-2D-Game-Engine
9cd87c369d813904d76668fe6153c7c4e8686023
[ "MIT" ]
null
null
null
Spiel/src/Graveyard/rendering/RenderBuffer.hpp
Ipotrick/CPP-2D-Game-Engine
9cd87c369d813904d76668fe6153c7c4e8686023
[ "MIT" ]
null
null
null
Spiel/src/Graveyard/rendering/RenderBuffer.hpp
Ipotrick/CPP-2D-Game-Engine
9cd87c369d813904d76668fe6153c7c4e8686023
[ "MIT" ]
null
null
null
#pragma once #include "Layer.hpp" #include "Camera.hpp" struct RenderBuffer { std::vector<std::unique_ptr<RenderScript>> scriptDestructQueue; bool resetTextureCache{ false }; Camera camera; std::vector<RenderLayer> layers; };
21
64
0.761905
Ipotrick
cc731400e0ed1b202dead5e6b892b09477c244ca
2,843
hpp
C++
behavior_system/IBehavior.hpp
draghan/behavior_tree
e890c29f009e11e8120a861aa5515797a52d656a
[ "MIT" ]
7
2018-08-27T20:31:21.000Z
2021-11-22T05:57:18.000Z
behavior_system/IBehavior.hpp
draghan/behavior_tree
e890c29f009e11e8120a861aa5515797a52d656a
[ "MIT" ]
null
null
null
behavior_system/IBehavior.hpp
draghan/behavior_tree
e890c29f009e11e8120a861aa5515797a52d656a
[ "MIT" ]
null
null
null
/* This file is distributed under MIT License. Copyright (c) 2018 draghan Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ // // Created by draghan on 2017-10-14. // #pragma once #include <string> #include <vector> #ifndef __arm__ #include <ostream> #endif enum class BehaviorState: uint8_t { undefined, success, failure, running }; class IBehavior { public: using ptr = IBehavior *; using id_t = uint32_t; const static id_t undefined_id; #ifndef __arm__ // Decided to disable printing to the streams on ARM processors // in order to keep some bytes of compiled result file. // With stream library included, result files were unacceptable // oversized for Cortex M. void print_family(std::string indent, bool last, std::ostream &stream); void introduce_yourself(std::ostream &stream); #endif id_t get_id() const; void set_id(id_t id); bool add_child(ptr child); size_t get_number_of_children() const; ptr get_child(size_t index) const; ptr get_last_child() const; ptr get_parent() const; explicit IBehavior(ptr parent, uint32_t id = 0); IBehavior(const IBehavior&) = delete; void operator=(const IBehavior&) = delete; virtual ~IBehavior() = default; BehaviorState evaluate(); BehaviorState get_status() const; bool operator==(const IBehavior &); virtual std::string get_glyph() const; virtual bool can_have_children() const = 0; protected: std::vector<ptr> children; ptr parent; id_t id; BehaviorState status; id_t last_evaluated_child; ptr get_child_for_eval(id_t id); id_t get_last_evaluated_child_id(); virtual BehaviorState internal_evaluate(id_t id_child_for_evaluation) = 0; BehaviorState internal_evaluate(); };
26.820755
82
0.719311
draghan
cc733829dd43fe861230df5866fe3587e4342e0a
1,670
hh
C++
src/cpu/vpred/fcmvp.hh
surya00060/ece-565-course-project
cb96f9be0aa21b6e1a5e10fa62bbb119f3c3a1cd
[ "BSD-3-Clause" ]
null
null
null
src/cpu/vpred/fcmvp.hh
surya00060/ece-565-course-project
cb96f9be0aa21b6e1a5e10fa62bbb119f3c3a1cd
[ "BSD-3-Clause" ]
null
null
null
src/cpu/vpred/fcmvp.hh
surya00060/ece-565-course-project
cb96f9be0aa21b6e1a5e10fa62bbb119f3c3a1cd
[ "BSD-3-Clause" ]
1
2020-12-15T20:53:56.000Z
2020-12-15T20:53:56.000Z
#ifndef __CPU_VPRED_LVP_PRED_HH__ #define __CPU_VPRED_LVP_PRED_HH__ #include "cpu/vpred/vpred_unit.hh" #include <vector> #include "base/statistics.hh" #include "base/sat_counter.hh" #include "base/types.hh" #include "cpu/inst_seq.hh" #include "cpu/static_inst.hh" #include "params/FCMVP.hh" #include "sim/sim_object.hh" class FCMVP : public VPredUnit { public: FCMVP(const FCMVPParams *params); bool lookup(Addr inst_addr, RegVal &value); float getconf(Addr inst_addr, RegVal &value); void updateTable(Addr inst_addr, bool isValuePredicted, bool isValueTaken, RegVal &trueValue); static inline RegVal computeHash(RegVal data) { RegVal hash = 0; RegVal bits = 0; for (int i = 0; i < 8; ++i) { bits = ((1 << 8) - 1) & (data >> (8*i)); hash = hash ^ bits; } return hash; } private: /*Number of history values to track*/ const unsigned historyLength; /** Number of History Table Entries*/ const unsigned historyTableSize; /** Number of History Table Entries*/ const unsigned valuePredictorTableSize; /** Number of bits to control*/ const unsigned ctrBits; /*Array of counters*/ std::vector<SatCounter> classificationTable; /*Array of value predictions*/ std::vector<std::vector<RegVal>> valueHistoryTable; std::vector<RegVal> valuePredictionTable; /*Array of tag value*/ std::vector<Addr> tagTable; }; #endif // __CPU_VPRED_LVP_PRED_HH__
25.30303
102
0.601796
surya00060
cc7424858b6c72272f73481c941b9e55475c869c
1,032
cpp
C++
uva/507.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
3
2018-01-08T02:52:51.000Z
2021-03-03T01:08:44.000Z
uva/507.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
null
null
null
uva/507.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
1
2020-08-13T18:07:35.000Z
2020-08-13T18:07:35.000Z
#include <bits/stdc++.h> using namespace std; vector<int> v; int main(){ //freopen("input.txt", "r", stdin); //freopen("output.txt", "w", stdout); int t, co = 0, len, a; for(scanf("%d", &t); t--; ){ scanf("%d", &len); for(int i = 0; i < len - 1; scanf("%d", &a), v.push_back(a), i++); int g = v[0], m = v[0], sum = v[0]; pair<int, int> p = make_pair(1, 2); pair<int, int> q = make_pair(1, 2); for(int i = 1; i < v.size(); i++){ if(sum + v[i] >= v[i]){ sum += v[i]; q.second = i + 2; } else{ sum = v[i]; q = make_pair(i + 1, i + 2); } if(sum >= g){ if(sum > g) p = make_pair(q.first, q.second); else if(sum == g && (q.second - q.first) > (p.second - p.first)) p = make_pair(q.first, q.second); g = sum; } } if(g > 0) printf("The nicest part of route %d is between stops %d and %d\n", ++co, p.first, p.second, g); else printf("Route %d has no nice parts\n", ++co); v.clear(); } return 0; }
29.485714
109
0.471899
cosmicray001
cc79f3ef2c2041b41a4897dd9196dab1851b8bfb
6,268
hpp
C++
cmdstan/stan/lib/stan_math/stan/math/rev/mat/functor/ode_system.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/rev/mat/functor/ode_system.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
cmdstan/stan/lib/stan_math/stan/math/rev/mat/functor/ode_system.hpp
yizhang-cae/torsten
dc82080ca032325040844cbabe81c9a2b5e046f9
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_REV_MAT_FUNCTOR_ODE_SYSTEM_HPP #define STAN_MATH_REV_MAT_FUNCTOR_ODE_SYSTEM_HPP #include <stan/math/rev/core.hpp> #include <stan/math/prim/arr/fun/value_of.hpp> #include <iostream> #include <sstream> #include <string> #include <vector> namespace stan { namespace math { /** * Internal representation of an ODE model object which provides * convenient Jacobian functions to obtain gradients wrt to states * and parameters. Can be used to provide analytic Jacobians via * partial template specialisation. * * @tparam F type of functor for the base ode system. */ template <typename F> class ode_system { private: const F& f_; const std::vector<double> theta_; const std::vector<double>& x_; const std::vector<int>& x_int_; std::ostream* msgs_; std::string error_msg(size_t y_size, size_t dy_dt_size) const { std::stringstream msg; msg << "ode_system: size of state vector y (" << y_size << ")" << " and derivative vector dy_dt (" << dy_dt_size << ")" << " in the ODE functor do not match in size."; return msg.str(); } public: /** * Construct an ODE model with the specified base ODE system, * parameters, data, and a message stream. * * @param[in] f the base ODE system functor. * @param[in] theta parameters of the ode. * @param[in] x real data. * @param[in] x_int integer data. * @param[in] msgs stream to which messages are printed. */ ode_system(const F& f, const std::vector<double> theta, const std::vector<double>& x, const std::vector<int>& x_int, std::ostream* msgs) : f_(f), theta_(theta), x_(x), x_int_(x_int), msgs_(msgs) { } /** * Calculate the RHS of the ODE * * @param[in] t time. * @param[in] y state of the ode system at time t. * @param[out] dy_dt ODE RHS */ template <typename Derived1> inline void operator()(double t, const std::vector<double>& y, Eigen::MatrixBase<Derived1>& dy_dt) const { const std::vector<double> dy_dt_vec = f_(t, y, theta_, x_, x_int_, msgs_); if (unlikely(y.size() != dy_dt_vec.size())) throw std::runtime_error(error_msg(y.size(), dy_dt_vec.size())); dy_dt = Eigen::Map<const Eigen::VectorXd>(&dy_dt_vec[0], y.size()); } /** * Calculate the Jacobian of the ODE RHS wrt to states y. The * function expects the output objects to have correct sizes, * i.e. dy_dt must be length N and Jy a NxN matrix (N states). * * @param[in] t time. * @param[in] y state of the ode system at time t. * @param[out] dy_dt ODE RHS * @param[out] Jy Jacobian of ODE RHS wrt to y. */ template <typename Derived1, typename Derived2> inline void jacobian(double t, const std::vector<double>& y, Eigen::MatrixBase<Derived1>& dy_dt, Eigen::MatrixBase<Derived2>& Jy) const { using Eigen::Matrix; using Eigen::Map; using Eigen::RowVectorXd; using std::vector; vector<double> grad(y.size()); Map<RowVectorXd> grad_eig(&grad[0], y.size()); try { start_nested(); vector<var> y_var(y.begin(), y.end()); vector<var> dy_dt_var = f_(t, y_var, theta_, x_, x_int_, msgs_); if (unlikely(y.size() != dy_dt_var.size())) throw std::runtime_error(error_msg(y.size(), dy_dt_var.size())); for (size_t i = 0; i < dy_dt_var.size(); ++i) { dy_dt(i) = dy_dt_var[i].val(); set_zero_all_adjoints_nested(); dy_dt_var[i].grad(y_var, grad); Jy.row(i) = grad_eig; } } catch (const std::exception& e) { recover_memory_nested(); throw; } recover_memory_nested(); } /** * Calculate the Jacobian of the ODE RHS wrt to states y and * parameters theta. The function expects the output objects to * have correct sizes, i.e. dy_dt must be length N, Jy a NxN * matrix and Jtheta a NxM matrix (N states, M parameters). * * @param[in] t time. * @param[in] y state of the ode system at time t. * @param[out] dy_dt ODE RHS * @param[out] Jy Jacobian of ODE RHS wrt to y. * @param[out] Jtheta Jacobian of ODE RHS wrt to theta. */ template <typename Derived1, typename Derived2> inline void jacobian(double t, const std::vector<double>& y, Eigen::MatrixBase<Derived1>& dy_dt, Eigen::MatrixBase<Derived2>& Jy, Eigen::MatrixBase<Derived2>& Jtheta) const { using Eigen::Dynamic; using Eigen::Map; using Eigen::Matrix; using Eigen::RowVectorXd; using std::vector; vector<double> grad(y.size() + theta_.size()); Map<RowVectorXd> grad_eig(&grad[0], y.size() + theta_.size()); try { start_nested(); vector<var> y_var(y.begin(), y.end()); vector<var> theta_var(theta_.begin(), theta_.end()); vector<var> z_var; z_var.reserve(y.size() + theta_.size()); z_var.insert(z_var.end(), y_var.begin(), y_var.end()); z_var.insert(z_var.end(), theta_var.begin(), theta_var.end()); vector<var> dy_dt_var = f_(t, y_var, theta_var, x_, x_int_, msgs_); if (unlikely(y.size() != dy_dt_var.size())) throw std::runtime_error(error_msg(y.size(), dy_dt_var.size())); for (size_t i = 0; i < dy_dt_var.size(); ++i) { dy_dt(i) = dy_dt_var[i].val(); set_zero_all_adjoints_nested(); dy_dt_var[i].grad(z_var, grad); Jy.row(i) = grad_eig.leftCols(y.size()); Jtheta.row(i) = grad_eig.rightCols(theta_.size()); } } catch (const std::exception& e) { recover_memory_nested(); throw; } recover_memory_nested(); } }; } } #endif
38.219512
77
0.565571
yizhang-cae
cc7fbe6860a7b75ff0ae6877e7a2427095c20a03
3,570
hpp
C++
Source/GameComponents/PhysicsObject.hpp
storm20200/WaterEngine
537910bc03e6d4016c9b22cf616d25afe40f77af
[ "MIT" ]
null
null
null
Source/GameComponents/PhysicsObject.hpp
storm20200/WaterEngine
537910bc03e6d4016c9b22cf616d25afe40f77af
[ "MIT" ]
2
2015-03-17T01:32:10.000Z
2015-03-19T18:58:28.000Z
Source/GameComponents/PhysicsObject.hpp
storm20200/WaterEngine
537910bc03e6d4016c9b22cf616d25afe40f77af
[ "MIT" ]
null
null
null
#if !defined WATER_PHYSICS_OBJECT_INCLUDED #define WATER_PHYSICS_OBJECT_INCLUDED // Engine headers. #include <GameComponents/Collider.hpp> #include <GameComponents/GameObject.hpp> // Engine namespace. namespace water { /// <summary> /// An abstract class for physics objects. Any object which the physics system manages must inherit from this class. /// PhysicsObject's can be added to a GameState's collection of managed objects which will be given to the physics /// system every physicUpdate(), this will apply collision detection as well as other features of the system. /// </summary> class PhysicsObject : public GameObject { public: /////////////////////////////////// /// Constructors and destructor /// /////////////////////////////////// PhysicsObject() = default; PhysicsObject (const PhysicsObject& copy) = default; PhysicsObject& operator= (const PhysicsObject& copy) = default; PhysicsObject (PhysicsObject&& move); PhysicsObject& operator= (PhysicsObject&& move); // Ensure destructor is virtual. virtual ~PhysicsObject() override {} ///////////////// /// Collision /// ///////////////// /// <summary> /// This function is called every time two collision objects intersect. This will be called AFTER the objects have been moved /// by the physics system and will be called on both objects. /// </summary> /// <param name="collision"> The object being collided with. </param> virtual void onCollision (PhysicsObject* const collision) = 0; /// <summary> /// The function called on trigger objects when either another trigger object or a collision object intersects the trigger zone. /// This will be called every frame until the object leaves. /// </summary> /// <param name="collision"> The object intersecting the trigger zone. </param> virtual void onTrigger (PhysicsObject* const collision) = 0; /////////////////////////// /// Getters and setters /// /////////////////////////// /// <summary> Indicates whether the PhysicsObject is static or not. </summary> bool isStatic() const { return m_isStatic; } /// <summary> /// Obtain a reference to the collider of the physics object. This contains information relating to how the physics /// object should be handled by the engine. /// </summary> /// <returns> A reference to the collider. </returns> const Collider& getCollider() const { return m_collider; } /// <summary> Sets whether the PhysicsObject is static. If they're static they will not be moved by the physics system. </summary> /// <param name="isStatic"> Whether it should be static. </param> void setStatic (const bool isStatic) { m_isStatic = isStatic; } protected: /////////////////////////// /// Implementation data /// /////////////////////////// Collider m_collider { }; //!< The collision information of the PhysicsObject. bool m_isStatic { true }; //!< Determines whether collision should cause this object to move or not. }; } #endif
41.511628
142
0.557983
storm20200
cc82da22e8b2c843ea0f15028e5f447aa29db572
49,995
cpp
C++
unalz-0.65/UnAlz.cpp
kippler/unalz
457884d21962caa12085bfb6ec5bd12f3eb93c00
[ "Zlib" ]
1
2021-04-13T04:49:58.000Z
2021-04-13T04:49:58.000Z
unalz-0.65/UnAlz.cpp
kippler/unalz
457884d21962caa12085bfb6ec5bd12f3eb93c00
[ "Zlib" ]
null
null
null
unalz-0.65/UnAlz.cpp
kippler/unalz
457884d21962caa12085bfb6ec5bd12f3eb93c00
[ "Zlib" ]
null
null
null
 #ifdef _WIN32 # include "zlib/zlib.h" # include "bzip2/bzlib.h" #else # include <zlib.h> # include <bzlib.h> #endif #include "UnAlz.h" #ifdef _WIN32 # pragma warning( disable : 4996 ) // crt secure warning #endif // utime 함수 처리 #if defined(_WIN32) || defined(__CYGWIN__) # include <time.h> # include <sys/utime.h> #endif #ifdef __GNUC__ # include <time.h> # include <utime.h> #endif // mkdir #ifdef _WIN32 # include <direct.h> #else # include <sys/stat.h> #endif #ifdef _UNALZ_ICONV // code page support # include <iconv.h> #endif #if defined(__linux__) || defined(__GLIBC__) || defined(__GNU__) || defined(__APPLE__) # include <errno.h> #endif #if defined(__NetBSD__) # include <sys/param.h> // __NetBSD_Version__ # include <errno.h> // iconv.h 때문에 필요 #endif #ifdef _WIN32 // safe string 처리 # include <strsafe.h> #endif // ENDIAN 처리 #ifdef _WIN32 // (L) # define swapint64(a) (UINT64) ( (((a)&0x00000000000000FFL) << 56) | (((a)&0x000000000000FF00L) << 40) | (((a)&0x0000000000FF0000L) << 24) | (((a)&0x00000000FF000000L) << 8) | (((a)&0x000000FF00000000L) >> 8) | (((a)&0x0000FF0000000000L) >> 24) | (((a)&0x00FF000000000000L) >> 40) | (((a)&0xFF00000000000000L) >> 56) ) #else // (LL) # define swapint64(a) (UINT64) ( (((a)&0x00000000000000FFLL) << 56) | (((a)&0x000000000000FF00LL) << 40) | (((a)&0x0000000000FF0000LL) << 24) | (((a)&0x00000000FF000000LL) << 8) | (((a)&0x000000FF00000000LL) >> 8) | (((a)&0x0000FF0000000000LL) >> 24) | (((a)&0x00FF000000000000LL) >> 40) | (((a)&0xFF00000000000000LL) >> 56) ) #endif #define swapint32(a) ((((a)&0xff)<<24)+(((a>>8)&0xff)<<16)+(((a>>16)&0xff)<<8)+(((a>>24)&0xff))) #define swapint16(a) (((a)&0xff)<<8)+(((a>>8)&0xff)) typedef UINT16 (*_unalz_le16toh)(UINT16 a); typedef UINT32 (*_unalz_le32toh)(UINT32 a); typedef UINT64 (*_unalz_le64toh)(UINT64 a); static _unalz_le16toh unalz_le16toh=NULL; static _unalz_le32toh unalz_le32toh=NULL; static _unalz_le64toh unalz_le64toh=NULL; static UINT16 le16tole(UINT16 a){return a;} static UINT32 le32tole(UINT32 a){return a;} static UINT64 le64tole(UINT64 a){return a;} static UINT16 le16tobe(UINT16 a){return swapint16(a);} static UINT32 le32tobe(UINT32 a){return swapint32(a);} static UINT64 le64tobe(UINT64 a){return swapint64(a);} #ifndef MAX_PATH # define MAX_PATH 260*6 // 그냥 .. 충분히.. #endif #ifdef _WIN32 # define PATHSEP "\\" # define PATHSEPC '\\' #else # define PATHSEP "/" # define PATHSEPC '/' #endif static time_t dosTime2TimeT(UINT32 dostime) // from INFO-ZIP src { struct tm t; t.tm_isdst = -1; t.tm_sec = (((int)dostime) << 1) & 0x3e; t.tm_min = (((int)dostime) >> 5) & 0x3f; t.tm_hour = (((int)dostime) >> 11) & 0x1f; t.tm_mday = (int)(dostime >> 16) & 0x1f; t.tm_mon = ((int)(dostime >> 21) & 0x0f) - 1; t.tm_year = ((int)(dostime >> 25) & 0x7f) + 80; return mktime(&t); } static BOOL IsBigEndian(void) { union { short a; char b[2]; } endian; endian.a = 0x0102; if(endian.b[0] == 0x02) return FALSE; return TRUE; } #ifdef _WIN32 # define safe_sprintf StringCbPrintfA #else # define safe_sprintf snprintf #endif // 64bit file handling support #if (_FILE_OFFSET_BITS==64) # define unalz_fseek fseeko # define unalz_ftell ftello #else # define unalz_fseek fseek # define unalz_ftell ftell #endif // error string table <- CUnAlz::ERR 의 번역 static const char* errorstrtable[]= { "no error", // ERR_NOERR "general error", // ERR_GENERAL "can't open archive file", // ERR_CANT_OPEN_FILE "can't open dest file or path", // ERR_CANT_OPEN_DEST_FILE // "can't create dest path", // ERR_CANT_CREATE_DEST_PATH "corrupted file", // ERR_CORRUPTED_FILE "not alz file", // ERR_NOT_ALZ_FILE "can't read signature", // ERR_CANT_READ_SIG "can't read file", // ERR_CANT_READ_FILE "error at read header", // ERR_AT_READ_HEADER "invalid filename length", // ERR_INVALID_FILENAME_LENGTH "invalid extrafield length", // ERR_INVALID_EXTRAFIELD_LENGTH, "can't read central directory structure head", // ERR_CANT_READ_CENTRAL_DIRECTORY_STRUCTURE_HEAD, "invalid filename size", // ERR_INVALID_FILENAME_SIZE, "invalid extrafield size", // ERR_INVALID_EXTRAFIELD_SIZE, "invalid filecomment size", // ERR_INVALID_FILECOMMENT_SIZE, "cant' read header", // ERR_CANT_READ_HEADER, "memory allocation failed", // ERR_MEM_ALLOC_FAILED, "file read error", // ERR_FILE_READ_ERROR, "inflate failed", // ERR_INFLATE_FAILED, "bzip2 decompress failed", // ERR_BZIP2_FAILED, "invalid file CRC", // ERR_INVALID_FILE_CRC "unknown compression method", // ERR_UNKNOWN_COMPRESSION_METHOD "iconv-can't open iconv", // ERR_ICONV_CANT_OPEN, "iconv-invalid multisequence of characters", // ERR_ICONV_INVALID_MULTISEQUENCE_OF_CHARACTERS, "iconv-incomplete multibyte sequence", // ERR_ICONV_INCOMPLETE_MULTIBYTE_SEQUENCE, "iconv-not enough space of buffer to convert", // ERR_ICONV_NOT_ENOUGH_SPACE_OF_BUFFER_TO_CONVERT, "iconv-etc", // ERR_ICONV_ETC, "password was not set", // ERR_PASSWD_NOT_SET, "invalid password", // ERR_INVALID_PASSWD, "user aborted", }; //////////////////////////////////////////////////////////////////////////////////////////////////// /// ctor /// @date 2004-03-06 오후 11:19:49 //////////////////////////////////////////////////////////////////////////////////////////////////// CUnAlz::CUnAlz() { memset(m_files, 0, sizeof(m_files)); m_nErr = ERR_NOERR; m_posCur = m_fileList.end();//(FileList::iterator)NULL; m_pFuncCallBack = NULL; m_pCallbackParam = NULL; m_bHalt = FALSE; m_nFileCount = 0; m_nCurFile = -1; m_nVirtualFilePos = 0; m_nCurFilePos = 0; m_bIsEOF = FALSE; m_bIsEncrypted = FALSE; m_bIsDataDescr = FALSE; m_bPipeMode = FALSE; #ifdef _UNALZ_ICONV #ifdef _UNALZ_UTF8 safe_strcpy(m_szToCodepage, "UTF-8",UNALZ_LEN_CODEPAGE) ; // 기본적으로 utf-8 #else safe_strcpy(m_szToCodepage, "CP949",UNALZ_LEN_CODEPAGE) ; // 기본적으로 CP949 #endif // _UNALZ_UTF8 safe_strcpy(m_szFromCodepage, "CP949",UNALZ_LEN_CODEPAGE); // alz 는 949 만 지원 #endif // _UNALZ_ICONV // check endian if(unalz_le16toh==NULL) { if(IsBigEndian()) { unalz_le16toh = le16tobe; unalz_le32toh = le32tobe; unalz_le64toh = le64tobe; } else { unalz_le16toh = le16tole; unalz_le32toh = le32tole; unalz_le64toh = le64tole; } } } //////////////////////////////////////////////////////////////////////////////////////////////////// /// dtor /// @date 2004-03-06 오후 11:19:52 //////////////////////////////////////////////////////////////////////////////////////////////////// CUnAlz::~CUnAlz() { Close(); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// progress callback func setting /// @date 2004-03-01 오전 6:02:05 //////////////////////////////////////////////////////////////////////////////////////////////////// void CUnAlz::SetCallback(_UnAlzCallback* pFunc, void* param) { m_pFuncCallBack = pFunc; m_pCallbackParam = param; } #ifdef _WIN32 #if !defined(__GNUWIN32__) && !defined(__GNUC__) //////////////////////////////////////////////////////////////////////////////////////////////////// /// 파일 열기 /// @param szPathName /// @return /// @date 2004-03-06 오후 11:03:59 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::Open(LPCWSTR szPathName) { char szPathNameA[MAX_PATH]; ::WideCharToMultiByte(CP_ACP, 0, szPathName, -1, szPathNameA, MAX_PATH, NULL, NULL); return Open(szPathNameA); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 대상 파일 세팅하기. /// @param szFileName /// @return /// @date 2004-03-06 오후 11:06:20 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::SetCurrentFile(LPCWSTR szFileName) { char szFileNameA[MAX_PATH]; ::WideCharToMultiByte(CP_ACP, 0, szFileName, -1, szFileNameA, MAX_PATH, NULL, NULL); return SetCurrentFile(szFileNameA); } BOOL CUnAlz::IsFolder(LPCWSTR szPathName) { UINT32 dwRet; dwRet = GetFileAttributesW(szPathName); if(dwRet==0xffffffff) return FALSE; if(dwRet & FILE_ATTRIBUTE_DIRECTORY) return TRUE; return FALSE; } #endif // __GNUWIN32__ #endif // _WIN32 BOOL CUnAlz::Open(const char* szPathName) { if(FOpen(szPathName)==FALSE) { m_nErr = ERR_CANT_OPEN_FILE; return FALSE; } BOOL bValidAlzHeader = FALSE; // file 분석시작.. for(;;) { SIGNATURE sig; BOOL ret; if(FEof()) break; //int pos = unalz_ftell(m_fp); sig = ReadSignature(); if(sig==SIG_EOF) { break; } if(sig==SIG_ERROR) { if(bValidAlzHeader) m_nErr = ERR_CORRUPTED_FILE; // 손상된 파일 else m_nErr = ERR_NOT_ALZ_FILE; // alz 파일이 아니다. return FALSE; // 깨진 파일.. } if(sig==SIG_ALZ_FILE_HEADER) { ret = ReadAlzFileHeader(); bValidAlzHeader = TRUE; // alz 파일은 맞다. } else if(sig==SIG_LOCAL_FILE_HEADER) ret = ReadLocalFileheader(); else if(sig==SIG_CENTRAL_DIRECTORY_STRUCTURE) ret = ReadCentralDirectoryStructure(); else if(sig==SIG_ENDOF_CENTRAL_DIRECTORY_RECORD) ret = ReadEndofCentralDirectoryRecord(); else { // 미구현된 signature ? 깨진 파일 ? ASSERT(0); m_nErr = ERR_CORRUPTED_FILE; return FALSE; } if(ret==FALSE) { return FALSE; } if(FEof()) break; } return TRUE; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 파일 닫기.. /// @return /// @date 2004-03-06 오후 11:04:21 //////////////////////////////////////////////////////////////////////////////////////////////////// void CUnAlz::Close() { FClose(); // 목록 날리기.. FileList::iterator i; for(i=m_fileList.begin(); i<m_fileList.end(); i++) { i->Clear(); } m_posCur = m_fileList.end();//(FileList::iterator)NULL; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// FILE 내의 SIGNATURE 읽기 /// @return /// @date 2004-03-06 오후 11:04:47 //////////////////////////////////////////////////////////////////////////////////////////////////// CUnAlz::SIGNATURE CUnAlz::ReadSignature() { UINT32 dwSig; if(FRead(&dwSig, sizeof(dwSig))==FALSE) { if(FEof()) return SIG_EOF; m_nErr = ERR_CANT_READ_SIG; return SIG_ERROR; } return (SIGNATURE)unalz_le32toh(dwSig); // little to host; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// ALZ HEADER SIGNATURE 읽기 /// @return /// @date 2004-03-06 오후 11:05:11 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::ReadAlzFileHeader() { SAlzHeader header; if(FRead(&header, sizeof(header))==FALSE) { ASSERT(0); m_nErr = ERR_CANT_READ_FILE; return FALSE; } return TRUE; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 각각의 파일 헤더 읽기 /// @return /// @date 2004-03-06 오후 11:05:18 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::ReadLocalFileheader() { SAlzLocalFileHeader zipHeader; int ret; ret = FRead(&(zipHeader.head), sizeof(zipHeader.head)); if(ret==FALSE) { m_nErr = ERR_AT_READ_HEADER; return FALSE; } // ALZ 확장.. if( (zipHeader.head.fileDescriptor & (SHORT)1) != 0){ m_bIsEncrypted = TRUE; // 하나라도 암호 걸렸으면 세팅한다. } if( (zipHeader.head.fileDescriptor & (SHORT)8) != 0){ m_bIsDataDescr = TRUE; } int byteLen = zipHeader.head.fileDescriptor/0x10; if(byteLen) { FRead(&(zipHeader.compressionMethod), sizeof(zipHeader.compressionMethod)); FRead(&(zipHeader.unknown), sizeof(zipHeader.unknown)); FRead(&(zipHeader.fileCRC), sizeof(zipHeader.fileCRC)); FRead(&(zipHeader.compressedSize), byteLen); FRead(&(zipHeader.uncompressedSize), byteLen); // 압축 사이즈가 없다. } // little to system zipHeader.fileCRC = unalz_le32toh(zipHeader.fileCRC); zipHeader.head.fileNameLength = unalz_le16toh(zipHeader.head.fileNameLength); zipHeader.compressedSize = unalz_le64toh(zipHeader.compressedSize); zipHeader.uncompressedSize = unalz_le64toh(zipHeader.uncompressedSize); // FILE NAME zipHeader.fileName = (char*)malloc(zipHeader.head.fileNameLength+sizeof(char)); if(zipHeader.fileName==NULL) { m_nErr = ERR_INVALID_FILENAME_LENGTH; return FALSE; } FRead(zipHeader.fileName, zipHeader.head.fileNameLength); if(zipHeader.head.fileNameLength > MAX_PATH - 5) zipHeader.head.fileNameLength = MAX_PATH - 5; zipHeader.fileName[zipHeader.head.fileNameLength] = (CHAR)NULL; #ifdef _UNALZ_ICONV // codepage convert if(strlen(m_szToCodepage)) { #define ICONV_BUF_SIZE (260*6) // utf8 은 최대 6byte size_t ileft, oleft; iconv_t cd; size_t iconv_result; size_t size; char inbuf[ICONV_BUF_SIZE]; char outbuf[ICONV_BUF_SIZE]; #if defined(__FreeBSD__) || defined(__CYGWIN__) || defined(__NetBSD__) const char *inptr = inbuf; #else char *inptr = inbuf; #endif char *outptr = outbuf; size = strlen(zipHeader.fileName)+1; strncpy(inbuf, zipHeader.fileName, size); ileft = size; oleft = sizeof(outbuf); cd = iconv_open(m_szToCodepage, m_szFromCodepage); // 보통 "CP949" 에서 "UTF-8" 로 iconv(cd, NULL, NULL, NULL, NULL); if( cd == (iconv_t)(-1)) { m_nErr = ERR_ICONV_CANT_OPEN; // printf("Converting Error : Cannot open iconv"); return FALSE; } else { iconv_result = iconv(cd, &inptr, &ileft, &outptr, &oleft); if(iconv_result== (size_t)(-1)) // iconv 실패.. { if (errno == EILSEQ) m_nErr = ERR_ICONV_INVALID_MULTISEQUENCE_OF_CHARACTERS; // printf("Invalid Multibyte Sequence of Characters"); else if (errno == EINVAL) m_nErr = ERR_ICONV_INCOMPLETE_MULTIBYTE_SEQUENCE; //printf("Incomplete multibyte sequence"); else if (errno != E2BIG) m_nErr = ERR_ICONV_NOT_ENOUGH_SPACE_OF_BUFFER_TO_CONVERT; // printf("Not enough space of buffer to convert"); else m_nErr = ERR_ICONV_ETC; iconv_close(cd); return FALSE; } else { outbuf[ICONV_BUF_SIZE-oleft] = 0; if(zipHeader.fileName) free(zipHeader.fileName); zipHeader.fileName = strdup(outbuf); if (zipHeader.fileName == NULL) { m_nErr = ERR_ICONV_ETC; iconv_close(cd); return FALSE; } // printf("\n Converted File Name : %s", outbuf); } iconv_close(cd); } } #endif /* // EXTRA FIELD LENGTH if(zipHeader.head.extraFieldLength) { zipHeader.extraField = (BYTE*)malloc(zipHeader.head.extraFieldLength); if(zipHeader.extraField==NULL) { m_nErr = ERR_INVALID_EXTRAFIELD_LENGTH; return FALSE; } FRead(zipHeader.extraField, 1, zipHeader.head.extraFieldLength); } */ if(IsEncryptedFile(zipHeader.head.fileDescriptor)) FRead(zipHeader.encChk, ALZ_ENCR_HEADER_LEN); // xf86 // SKIP FILE DATA zipHeader.dwFileDataPos = FTell(); // data 의 위치 저장하기.. FSeek(FTell()+zipHeader.compressedSize); // DATA DESCRIPTOR /* if(zipHeader.head.generalPurposeBitFlag.bit1) { FRead(zipHeader.extraField, 1, sizeof(zipHeader.extraField),); } */ /* #ifdef _DEBUG printf("NAME:%s COMPRESSED SIZE:%d UNCOMPRESSED SIZE:%d COMP METHOD:%d\n", zipHeader.fileName, zipHeader.compressedSize, zipHeader.uncompressedSize, zipHeader.compressionMethod ); #endif */ // 파일을 목록에 추가한다.. m_fileList.push_back(zipHeader); return TRUE; } BOOL CUnAlz::ReadCentralDirectoryStructure() { SCentralDirectoryStructure header; if(FRead(&header, sizeof(header.head))==FALSE) { m_nErr = ERR_CANT_READ_CENTRAL_DIRECTORY_STRUCTURE_HEAD; return FALSE; } /* // read file name if(header.head.fileNameLength) { header.fileName = (char*)malloc(header.head.fileNameLength+1); if(header.fileName==NULL) { m_nErr = ERR_INVALID_FILENAME_SIZE; return FALSE; } FRead(header.fileName, 1, header.head.fileNameLength, m_fp); header.fileName[header.head.fileNameLength] = NULL; } // extra field; if(header.head.extraFieldLength) { header.extraField = (BYTE*)malloc(header.head.extraFieldLength); if(header.extraField==NULL) { m_nErr = ERR_INVALID_EXTRAFIELD_SIZE; return FALSE; } FRead(header.extraField, 1, header.head.extraFieldLength, m_fp); } // file comment; if(header.head.fileCommentLength) { header.fileComment = (char*)malloc(header.head.fileCommentLength+1); if(header.fileComment==NULL) { m_nErr = ERR_INVALID_FILECOMMENT_SIZE; return FALSE; } FRead(header.fileComment, 1, header.head.fileCommentLength, m_fp); header.fileComment[header.head.fileCommentLength] = NULL; } */ return TRUE; } BOOL CUnAlz::ReadEndofCentralDirectoryRecord() { /* SEndOfCentralDirectoryRecord header; if(FRead(&header, sizeof(header.head), 1, m_fp)!=1) { m_nErr = ERR_CANT_READ_HEADER; return FALSE; } if(header.head.zipFileCommentLength) { header.fileComment = (char*)malloc(header.head.zipFileCommentLength+1); if(header.fileComment==NULL) { m_nErr = ERR_INVALID_FILECOMMENT_SIZE; return FALSE; } FRead(header.fileComment, 1, header.head.zipFileCommentLength, m_fp); header.fileComment[header.head.zipFileCommentLength] = NULL; } */ return TRUE; } BOOL CUnAlz::SetCurrentFile(const char* szFileName) { FileList::iterator i; // 순차적으로 찾는다. for(i=m_fileList.begin(); i<m_fileList.end(); i++) { #ifdef _WIN32 if(stricmp(i->fileName, szFileName)==0) #else if(strcmp(i->fileName, szFileName)==0) #endif { m_posCur = i; return TRUE; } } m_posCur = m_fileList.end();//(FileList::iterator)NULL; return FALSE; } void CUnAlz::SetCurrentFile(FileList::iterator newPos) { m_posCur = newPos; } #ifndef MAX_WBITS # define MAX_WBITS 15 /* 32K LZ77 window */ #endif //////////////////////////////////////////////////////////////////////////////////////////////////// /// 버퍼에 압축 풀기. 버퍼는 당근 충분한 크기가 준비되어 있어야 한다. /// @param pDestBuf /// @return /// @date 2004-03-07 오전 12:26:13 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::ExtractCurrentFileToBuf(BYTE* pDestBuf, int nBufSize) { SExtractDest dest; dest.nType = ET_MEM; dest.buf = pDestBuf; dest.bufpos = 0; dest.bufsize = nBufSize; return ExtractTo(&dest); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 현재 파일 (SetCurrentFile로 지)을 대상 경로에 대상 파일로 푼다. /// @param szDestPathName - 대상 경로 /// @param szDestFileName - 대상 파일명, NULL 이면 원래 파일명 사용 /// @return /// @date 2004-03-06 오후 11:06:59 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::ExtractCurrentFile(const char* szDestPathName, const char* szDestFileName) { if(m_posCur==m_fileList.end()/*(FileList::iterator)NULL*/) {ASSERT(0); return FALSE;} BOOL ret=FALSE; SExtractDest dest; char szDestPathFileName[MAX_PATH]; if(chkValidPassword() == FALSE) { return FALSE; } if( szDestPathName==NULL|| strlen(szDestPathName) + (szDestFileName?strlen(szDestFileName):strlen(m_posCur->fileName))+1 > MAX_PATH ) // check buffer overflow { ASSERT(0); m_nErr = ERR_GENERAL; return FALSE; } // 경로명 safe_strcpy(szDestPathFileName, szDestPathName, MAX_PATH); if(szDestPathFileName[strlen(szDestPathFileName)]!=PATHSEPC) safe_strcat(szDestPathFileName, PATHSEP, MAX_PATH); // 파일명 if(szDestFileName) safe_strcat(szDestPathFileName, szDestFileName, MAX_PATH); else safe_strcat(szDestPathFileName, m_posCur->fileName, MAX_PATH); // ../../ 형식의 보안 버그 확인 if( strstr(szDestPathFileName, "../")|| strstr(szDestPathFileName, "..\\")) { ASSERT(0); m_nErr = ERR_GENERAL; return FALSE; } #ifndef _WIN32 { char* p = szDestPathFileName; // 경로 delimiter 바꾸기 while(*p) { if(*p=='\\') *p='/'; p++; } } #endif // 압축풀 대상 ( 파일 ) dest.nType = ET_FILE; if(m_bPipeMode) dest.fp = stdout; // pipe mode 일 경우 stdout 출력 else dest.fp = fopen(szDestPathFileName, "wb"); // 타입이 폴더일 경우.. if(m_bPipeMode==FALSE && (m_posCur->head.fileAttribute) & ALZ_FILEATTR_DIRECTORY ) { //printf("digpath:%s\n", szDestPathFileName); // 경로파기 DigPath(szDestPathFileName); return TRUE; // m_nErr = ERR_CANT_CREATE_DEST_PATH; // return FALSE; } // 파일 열기 실패시 - 경로를 파본다 if(dest.fp==NULL) { DigPath(szDestPathFileName); dest.fp = fopen(szDestPathFileName, "wb"); } // 그래도 파일열기 실패시. if(dest.fp==NULL) { // 대상 파일 열기 실패 m_nErr = ERR_CANT_OPEN_DEST_FILE; //printf("dest pathfilename:%s\n",szDestPathFileName); if(m_pFuncCallBack) { // CHAR buf[1024]; // sprintf(buf, "파일 열기 실패 : %s", szDestPathFileName); // m_pFuncCallBack(buf, 0,0,m_pCallbackParam, NULL); } return FALSE; } //#endif // CALLBACK 세팅 if(m_pFuncCallBack) m_pFuncCallBack(m_posCur->fileName, 0,m_posCur->uncompressedSize,m_pCallbackParam, NULL); ret = ExtractTo(&dest); if(dest.fp!=NULL) { fclose(dest.fp); // file time setting - from unalz_wcx_01i.zip utimbuf tmp; tmp.actime = 0; // 마지막 엑세스 타임 tmp.modtime = dosTime2TimeT(m_posCur->head.fileTimeDate); // 마지막 수정일자만 변경(만든 날자는 어떻게 바꾸지?) utime(m_posCur->fileName, &tmp); } return ret; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 대상에 압축 풀기.. /// @param dest /// @return /// @date 2004-03-07 오전 12:44:36 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::ExtractTo(SExtractDest* dest) { BOOL ret = FALSE; // 압축 방법에 따라서 압축 풀기 if(m_posCur->compressionMethod==COMP_NOCOMP) { ret = ExtractRawfile(dest, *m_posCur); } else if(m_posCur->compressionMethod==COMP_BZIP2) { ret = ExtractBzip2(dest, *m_posCur); // bzip2 } else if(m_posCur->compressionMethod==COMP_DEFLATE) { ret = ExtractDeflate2(dest, *m_posCur); // deflate } else // COMP_UNKNOWN { // alzip 5.6 부터 추가된 포맷(5.5 에서는 풀지 못한다. 영문 5.51 은 푼다 ) // 하지만 어떤 버전에서 이 포맷을 만들어 내는지 정확히 알 수 없다. // 공식으로 릴리즈된 알집은 이 포맷을 만들어내지 않는다. 비공식(베타?)으로 배포된 버전에서만 이 포맷을 만들어낸다. m_nErr = ERR_UNKNOWN_COMPRESSION_METHOD; ASSERT(0); ret = FALSE; } return ret; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// DEFLATE 로 풀기 - 테스트용 함수. 모든 파일을 한꺼번에 읽어서 푼다. 실제 사용 안함. /// @param fp - 대상 파일 /// @param file - 소스 파일 정보 /// @return /// @date 2004-03-06 오후 11:09:17 //////////////////////////////////////////////////////////////////////////////////////////////////// /* BOOL CUnAlz::ExtractDeflate(FILE* fp, SAlzLocalFileHeader& file) { z_stream stream; BYTE* pInBuf=NULL; BYTE* pOutBuf=NULL; int nInBufSize = file.compressedSize; int nOutBufSize = file.uncompressedSize; int err; int flush=Z_SYNC_FLUSH; BOOL ret = FALSE; memset(&stream, 0, sizeof(stream)); pInBuf = (BYTE*)malloc(nInBufSize); if(pInBuf==NULL) { m_nErr = ERR_MEM_ALLOC_FAILED; goto END; } pOutBuf = (BYTE*)malloc(nOutBufSize); if(pOutBuf==NULL) { m_nErr = ERR_MEM_ALLOC_FAILED; goto END; } // 한번에 읽어서 fseek(m_fp, file.dwFileDataPos, SEEK_SET); if(FRead(pInBuf, nInBufSize, 1, m_fp)!=1) { m_nErr = ERR_FILE_READ_ERROR; goto END; } // 초기화.. inflateInit2(&stream, -MAX_WBITS); stream.next_out = pOutBuf; stream.avail_out = nOutBufSize; stream.next_in = pInBuf; stream.avail_in = nInBufSize; err = inflate(&stream, flush); if(err!=Z_OK && err!=Z_STREAM_END ) { m_nErr = ERR_INFLATE_FAILED; goto END; } fwrite(pOutBuf, 1, nOutBufSize, fp); ret = TRUE; END : inflateEnd(&stream); if(pInBuf) free(pInBuf); if(pOutBuf) free(pOutBuf); return ret; } */ //////////////////////////////////////////////////////////////////////////////////////////////////// /// 대상 폴더에 현재 압축파일을 전부 풀기 /// @param szDestPathName - 대상 경로 /// @return /// @date 2004-03-06 오후 11:09:49 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::ExtractAll(const char* szDestPathName) { FileList::iterator i; for(i=m_fileList.begin(); i<m_fileList.end(); i++) { m_posCur = i; if(ExtractCurrentFile(szDestPathName)==FALSE) return FALSE; if(m_bHalt) break; // 멈추기.. } return TRUE; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 대상 경로 파기 - 압축 파일 내에 폴더 정보가 있을 경우, 다중 폴더를 판다(dig) /// @param szPathName /// @return /// @date 2004-03-06 오후 11:10:12 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::DigPath(const char* szPathName) { char* dup = strdup(szPathName); char seps[] = "/\\"; char* token; char path[MAX_PATH] = {0}; char* last; // 경로만 뽑기. last = dup + strlen(dup); while(last!=dup) { if(*last=='/' || *last=='\\') { *last = (char)NULL; break; } last --; } token = strtok( dup, seps ); while( token != NULL ) { if(strlen(path)==0) { if(szPathName[0]=='/') // is absolute path ? safe_strcpy(path,"/", MAX_PATH); else if(szPathName[0]=='\\' && szPathName[1]=='\\') // network drive ? safe_strcpy(path,"\\\\", MAX_PATH); safe_strcat(path, token, MAX_PATH); } else { safe_strcat(path, PATHSEP,MAX_PATH); safe_strcat(path, token,MAX_PATH); } if(IsFolder(path)==FALSE) #ifdef _WIN32 _mkdir(path); #else mkdir(path, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); #endif //printf("path:%s\n", path); token = strtok( NULL, seps ); } free(dup); if(IsFolder(szPathName)) return TRUE; return FALSE; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 제대로된 폴더 인가? /// @param szPathName /// @return /// @date 2004-03-06 오후 11:03:26 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::IsFolder(const CHAR* szPathName) { #ifdef _WIN32 UINT32 dwRet; dwRet = GetFileAttributesA(szPathName); if(dwRet==0xffffffff) return FALSE; if(dwRet & FILE_ATTRIBUTE_DIRECTORY) return TRUE; return FALSE; #else struct stat buf; int result; result = stat(szPathName, &buf); if(result!=0) return FALSE; //printf("isfolder:%s, %d,%d,%d\n", szPathName, buf.st_mode, S_IFDIR, buf.st_mode & S_IFDIR); if(buf.st_mode & S_IFDIR) return TRUE; return FALSE; #endif } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 압축을 풀 대상에 압축을 푼다. /// @param dest - 대상 OBJECT /// @param buf - 풀린 데이타 /// @param nSize - 데이타의 크기 /// @return 쓴 바이트수. 에러시 -1 리턴 /// @date 2004-03-07 오전 12:37:41 //////////////////////////////////////////////////////////////////////////////////////////////////// int CUnAlz::WriteToDest(SExtractDest* dest, BYTE* buf, int nSize) { if(dest->nType==ET_FILE) { return fwrite(buf, 1, nSize, dest->fp); } else if(dest->nType==ET_MEM) { if(dest->buf==NULL) return nSize; // 대상이 NULL 이다... 압축푸는 시늉만 한다.. if(dest->bufpos+nSize >dest->bufsize) // 에러.. 버퍼가 넘쳤다. { ASSERT(0); return -1; } // memcpy memcpy(dest->buf + dest->bufpos, buf, nSize); dest->bufpos += nSize; return nSize; } else { ASSERT(0); } return -1; } /* 실패한 방법.. 고생한게 아까워서 못지움. #define ALZDLZ_HEADER_SIZE 4 // alz 파일의 bzip2 헤더 크기 #define BZIP2_HEADER_SIZE 10 // bzip 파일의 헤더 크기 #define BZIP2_CRC_SIZE 4 // bzip2 의 crc #define BZIP2_TAIL_SIZE 10 // 대충 4+5 정도.? BYTE bzip2Header[BZIP2_HEADER_SIZE] = {0x42, 0x5a, 0x68, 0x39, 0x31, 0x41, 0x59, 0x26, 0x53, 0x59}; BOOL CUnAlz::ExtractBzip2_bak(FILE* fp, SAlzLocalFileHeader& file) { bz_stream stream; BYTE* pInBuf=NULL; BYTE* pOutBuf=NULL; int nInBufSize = file.compressedSize; int nOutBufSize = file.uncompressedSize; //int err; int flush=Z_SYNC_FLUSH; BOOL ret = FALSE; UINT32 crc = 0xffffffff; //BYTE temp[100]; memset(&stream, 0, sizeof(stream)); pInBuf = (BYTE*)malloc(nInBufSize + BZIP2_HEADER_SIZE + BZIP2_CRC_SIZE - ALZDLZ_HEADER_SIZE + BZIP2_TAIL_SIZE); if(pInBuf==NULL) { m_nErr = ERR_MEM_ALLOC_FAILED; goto END; } pOutBuf = (BYTE*)malloc(nOutBufSize); if(pOutBuf==NULL) { m_nErr = ERR_MEM_ALLOC_FAILED; goto END; } // ALZ 의 BZIP 헤더 ("DLZ.") 스킵하기. fseek(m_fp, ALZDLZ_HEADER_SIZE, SEEK_CUR); // BZIP2 헤더 삽입 memcpy(pInBuf, bzip2Header, BZIP2_HEADER_SIZE); // BZIP2 CRC memcpy(pInBuf+BZIP2_HEADER_SIZE, &(crc), BZIP2_CRC_SIZE); // 진짜 압축된 데이타를 한번에 읽어서 fseek(m_fp, file.dwFileDataPos+ALZDLZ_HEADER_SIZE, SEEK_SET); if(FRead(pInBuf+BZIP2_HEADER_SIZE+BZIP2_CRC_SIZE, nInBufSize-ALZDLZ_HEADER_SIZE, 1, m_fp)!=1) { m_nErr = ERR_FILE_READ_ERROR; goto END; } // 초기화.. stream.bzalloc = NULL; stream.bzfree = NULL; stream.opaque = NULL; ret = BZ2_bzDecompressInit ( &stream, 3,0 ); if (ret != BZ_OK) goto END; //memcpy(temp, pInBuf, 100); stream.next_in = (char*)pInBuf; stream.next_out = (char*)pOutBuf; stream.avail_in = nInBufSize+BZIP2_HEADER_SIZE+BZIP2_CRC_SIZE+BZIP2_TAIL_SIZE; stream.avail_out = nOutBufSize; ret = BZ2_bzDecompress ( &stream ); // BZ_DATA_ERROR 가 리턴될 수 있다.. //if (ret == BZ_OK) goto END; //if (ret != BZ_STREAM_END) goto END; BZ2_bzDecompressEnd(&stream); fwrite(pOutBuf, 1, nOutBufSize, fp); ret = TRUE; END : if(pInBuf) free(pInBuf); if(pOutBuf) free(pOutBuf); if(ret==FALSE) BZ2_bzDecompressEnd(&stream); return ret; } */ //////////////////////////////////////////////////////////////////////////////////////////////////// /// RAW 로 압축된 파일 풀기 /// @param fp - 대상 파일 /// @param file - 소스 파일 /// @return /// @date 2004-03-06 오후 11:10:53 //////////////////////////////////////////////////////////////////////////////////////////////////// #define BUF_LEN (4096*2) BOOL CUnAlz::ExtractRawfile(SExtractDest* dest, SAlzLocalFileHeader& file) { BOOL ret = FALSE; BYTE buf[BUF_LEN]; INT64 read; INT64 sizeToRead; INT64 bufLen = BUF_LEN; INT64 nWritten = 0; BOOL bHalt = FALSE; BOOL bIsEncrypted = IsEncryptedFile(); // 암호걸린 파일인가? UINT32 dwCRC32= 0; // 위치 잡고. FSeek(file.dwFileDataPos); sizeToRead = file.compressedSize; // 읽을 크기. m_nErr = ERR_NOERR; while(sizeToRead) { read = min(sizeToRead, bufLen); if(FRead(buf, (int)read)==FALSE) { break; } if(bIsEncrypted) DecryptingData((int)read, buf); // xf86 dwCRC32 = crc32(dwCRC32, buf, (UINT)(read)); WriteToDest(dest, buf, (int)read); //fwrite(buf, read, 1, fp); sizeToRead -= read; nWritten+=read; // progress callback if(m_pFuncCallBack) { m_pFuncCallBack(NULL, nWritten, file.uncompressedSize, m_pCallbackParam, &bHalt); if(bHalt) { break; } } } m_bHalt = bHalt; if(m_nErr==ERR_NOERR) // 성공적으로 압축을 풀었다.. CRC 검사하기.. { if(file.fileCRC==dwCRC32) { ret = TRUE; } else { m_nErr = ERR_INVALID_FILE_CRC; } } return ret; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// BZIP2 압축 풀기.. /// @param fp_w - 대상 파일 /// @param file - 소스 파일 정보 /// @return /// @date 2004-03-01 오전 5:47:36 //////////////////////////////////////////////////////////////////////////////////////////////////// #define BZIP2_EXTRACT_BUF_SIZE 0x2000 BOOL CUnAlz::ExtractBzip2(SExtractDest* dest, SAlzLocalFileHeader& file) { BZFILE *bzfp = NULL; int smallMode = 0; int verbosity = 1; int bzerr; INT64 len; BYTE buff[BZIP2_EXTRACT_BUF_SIZE]; INT64 nWritten = 0; BOOL bHalt = FALSE; UINT32 dwCRC32= 0; BOOL ret = FALSE; FSeek(file.dwFileDataPos); bzfp = BZ2_bzReadOpen(&bzerr,this,verbosity,smallMode,0,0); if(bzfp==NULL){ASSERT(0); return FALSE;} m_nErr = ERR_NOERR; while((len=BZ2_bzread(bzfp,buff,BZIP2_EXTRACT_BUF_SIZE))>0) { WriteToDest(dest, (BYTE*)buff, (int)len); //fwrite(buff,1,len,fp_w); dwCRC32 = crc32(dwCRC32,buff, (UINT)(len)); nWritten+=len; // progress callback if(m_pFuncCallBack) { m_pFuncCallBack(NULL, nWritten, file.uncompressedSize, m_pCallbackParam, &bHalt); if(bHalt) { break; } } } if(len<0) // 에러 상황.. { m_nErr = ERR_INFLATE_FAILED; } BZ2_bzReadClose( &bzerr, bzfp); m_bHalt = bHalt; if(m_nErr==ERR_NOERR) // 성공적으로 압축을 풀었다.. CRC 검사하기.. { if(file.fileCRC==dwCRC32) { ret = TRUE; } else { m_nErr = ERR_INVALID_FILE_CRC; } } /* // FILE* 를 사용할경우 사용하던 코드. - 멀티 볼륨 지원 안함.. BZFILE *bzfp = NULL; int smallMode = 0; int verbosity = 1; int bzerr; int len; char buff[BZIP2_EXTRACT_BUF_SIZE]; INT64 nWritten = 0; BOOL bHalt = FALSE; FSeek(file.dwFileDataPos, SEEK_SET); bzfp = BZ2_bzReadOpen(&bzerr,m_fp,verbosity,smallMode,0,0); while((len=BZ2_bzread(bzfp,buff,BZIP2_EXTRACT_BUF_SIZE))>0) { WriteToDest(dest, (BYTE*)buff, len); //fwrite(buff,1,len,fp_w); nWritten+=len; // progress callback if(m_pFuncCallBack) { m_pFuncCallBack(NULL, nWritten, file.uncompressedSize, m_pCallbackParam, &bHalt); if(bHalt) { break; } } } BZ2_bzReadClose( &bzerr, bzfp); m_bHalt = bHalt; */ return ret; } #ifndef UNZ_BUFSIZE #define UNZ_BUFSIZE 0x1000 // (16384) #endif #define IN_BUF_SIZE UNZ_BUFSIZE #define OUT_BUF_SIZE 0x1000 //IN_BUF_SIZE //////////////////////////////////////////////////////////////////////////////////////////////////// /// deflate 로 압축 풀기. ExtractDeflate() 와 달리 조금씩 읽어서 푼다. /// @param fp /// @param file /// @return /// @date 2004-03-06 오후 11:11:36 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::ExtractDeflate2(SExtractDest* dest, SAlzLocalFileHeader& file) { z_stream stream; BYTE pInBuf[IN_BUF_SIZE]; BYTE pOutBuf[OUT_BUF_SIZE]; int nInBufSize = IN_BUF_SIZE; int nOutBufSize = OUT_BUF_SIZE; int err; int flush=Z_SYNC_FLUSH; BOOL ret = FALSE; INT64 nRestReadCompressed; UINT32 dwCRC32= 0; INT64 rest_read_uncompressed; UINT iRead = 0; INT64 nWritten = 0; BOOL bHalt = FALSE; BOOL bIsEncrypted = IsEncryptedFile(); // 암호걸린 파일인가? memset(&stream, 0, sizeof(stream)); FSeek(file.dwFileDataPos); inflateInit2(&stream, -MAX_WBITS); nRestReadCompressed = file.compressedSize; rest_read_uncompressed = file.uncompressedSize; // 출력 부분. stream.next_out = pOutBuf; stream.avail_out = OUT_BUF_SIZE; m_nErr = ERR_NOERR; while(stream.avail_out>0) { if(stream.avail_in==0 && nRestReadCompressed>0) { UINT uReadThis = UNZ_BUFSIZE; if (nRestReadCompressed<(int)uReadThis) uReadThis = (UINT)nRestReadCompressed; // 읽을 크기. if (uReadThis == 0) break; // 중지 if(FRead(pInBuf, uReadThis)==FALSE) { m_nErr = ERR_CANT_READ_FILE; goto END; } if(bIsEncrypted) DecryptingData(uReadThis, pInBuf); // xf86 // dwCRC32 = crc32(dwCRC32,pInBuf, (UINT)(uReadThis)); nRestReadCompressed -= uReadThis; stream.next_in = pInBuf; stream.avail_in = uReadThis; } UINT uTotalOutBefore,uTotalOutAfter; const BYTE *bufBefore; UINT uOutThis; int flush=Z_SYNC_FLUSH; uTotalOutBefore = stream.total_out; bufBefore = stream.next_out; err=inflate(&stream,flush); uTotalOutAfter = stream.total_out; uOutThis = uTotalOutAfter-uTotalOutBefore; dwCRC32 = crc32(dwCRC32,bufBefore, (UINT)(uOutThis)); rest_read_uncompressed -= uOutThis; iRead += (UINT)(uTotalOutAfter - uTotalOutBefore); WriteToDest(dest, pOutBuf, uOutThis); //fwrite(pOutBuf, uOutThis, 1, fp); // file 에 쓰기. stream.next_out = pOutBuf; stream.avail_out = OUT_BUF_SIZE; nWritten+=uOutThis; // progress callback if(m_pFuncCallBack) { m_pFuncCallBack(NULL, nWritten, file.uncompressedSize, m_pCallbackParam, &bHalt); if(bHalt) { m_nErr = ERR_USER_ABORTED; break; } } if (err==Z_STREAM_END) break; //if(iRead==0) break; // UNZ_EOF; if (err!=Z_OK) { m_nErr = ERR_INFLATE_FAILED; goto END; } } m_bHalt = bHalt; if(m_nErr==ERR_NOERR) // 성공적으로 압축을 풀었다.. CRC 검사하기.. { if(file.fileCRC==dwCRC32) { ret = TRUE; } else { m_nErr = ERR_INVALID_FILE_CRC; } } END : inflateEnd(&stream); return ret; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 파일 열기 /// @param szPathName /// @return /// @date 2004-10-02 오후 11:47:14 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::FOpen(const char* szPathName) { char* temp = strdup(szPathName); // 파일명 복사.. int i; int nLen = strlen(szPathName); UINT64 nFileSizeLow; UINT32 dwFileSizeHigh; m_nFileCount = 0; m_nCurFile = 0; m_nVirtualFilePos = 0; m_nCurFilePos = 0; m_bIsEOF = FALSE; for(i=0;i<MAX_FILES;i++) // aa.alz 파일명을 가지고 aa.a00 aa.a01 aa.a02 .. 만들기 { if(i>0) safe_sprintf(temp+nLen-3, 4, "%c%02d", (i-1)/100+'a', (i-1)%100); #ifdef _WIN32 m_files[i].fp = CreateFileA(temp, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, NULL); if(m_files[i].fp==INVALID_HANDLE_VALUE) break; nFileSizeLow = GetFileSize(m_files[i].fp, (DWORD*)&dwFileSizeHigh); #else m_files[i].fp = fopen(temp, "rb"); if(m_files[i].fp==NULL) break; dwFileSizeHigh=0; unalz_fseek(m_files[i].fp,0,SEEK_END); nFileSizeLow=unalz_ftell(m_files[i].fp); unalz_fseek(m_files[i].fp,0,SEEK_SET); #endif m_nFileCount++; m_files[i].nFileSize = ((INT64)nFileSizeLow) + (((INT64)dwFileSizeHigh)<<32); if(i==0) m_files[i].nMultivolHeaderSize = 0; else m_files[i].nMultivolHeaderSize = MULTIVOL_HEAD_SIZE; m_files[i].nMultivolTailSize = MULTIVOL_TAIL_SIZE; } free(temp); if(m_nFileCount==0) return FALSE; m_files[m_nFileCount-1].nMultivolTailSize = 0; // 마지막 파일은 꼴랑지가 없다.. return TRUE; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 파일 닫기 /// @return /// @date 2004-10-02 오후 11:48:53 //////////////////////////////////////////////////////////////////////////////////////////////////// void CUnAlz::FClose() { int i; #ifdef _WIN32 for(i=0;i<m_nFileCount;i++) CloseHandle(m_files[i].fp); #else for(i=0;i<m_nFileCount;i++) fclose(m_files[i].fp); #endif memset(m_files, 0, sizeof(m_files)); m_nFileCount = 0; m_nCurFile = -1; m_nVirtualFilePos = 0; m_nCurFilePos = 0; m_bIsEOF = FALSE; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 파일의 끝인가? /// @return /// @date 2004-10-02 오후 11:48:21 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::FEof() { return m_bIsEOF; /* if(m_fp==NULL){ASSERT(0); return TRUE;} if(feof(m_fp)) return TRUE; return FALSE; */ } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 현재 파일 위치 /// @return /// @date 2004-10-02 오후 11:50:50 //////////////////////////////////////////////////////////////////////////////////////////////////// INT64 CUnAlz::FTell() { return m_nVirtualFilePos; // return ftell(m_fp); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 파일 위치 세팅 /// @param offset /// @param origin /// @return /// @date 2004-10-02 오후 11:51:53 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::FSeek(INT64 offset) { m_nVirtualFilePos = offset; int i; INT64 remain=offset; LONG remainHigh; m_bIsEOF = FALSE; for(i=0;i<m_nFileCount;i++) // 앞에서 루프를 돌면서 위치 선정하기.. { if(remain<=m_files[i].nFileSize-m_files[i].nMultivolHeaderSize-m_files[i].nMultivolTailSize) { m_nCurFile = i; m_nCurFilePos = remain+m_files[i].nMultivolHeaderSize; // 물리적 위치. remainHigh = (LONG)((m_nCurFilePos>>32)&0xffffffff); #ifdef _WIN32 SetFilePointer(m_files[i].fp, LONG(m_nCurFilePos), &remainHigh, FILE_BEGIN); #else unalz_fseek(m_files[i].fp, m_nCurFilePos, SEEK_SET); #endif return TRUE; } remain -= (m_files[i].nFileSize-m_files[i].nMultivolHeaderSize-m_files[i].nMultivolTailSize); } // 실패..? ASSERT(0); return FALSE; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 파일 읽기 /// @param buffer /// @param size /// @param count /// @return /// @date 2004-10-02 오후 11:44:05 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::FRead(void* buffer, UINT32 nBytesToRead, int* pTotRead ) { BOOL ret; UINT32 nNumOfBytesRead; INT64 dwRemain; UINT32 dwRead; UINT32 dwTotRead; dwRemain = nBytesToRead; dwTotRead = 0; if(pTotRead) *pTotRead=0; while(dwRemain) { dwRead = (UINT32)min(dwRemain, (m_files[m_nCurFile].nFileSize-m_nCurFilePos-m_files[m_nCurFile].nMultivolTailSize)); if(dwRead==0) { m_bIsEOF = TRUE;return FALSE; } #ifdef _WIN32 ret = ReadFile(m_files[m_nCurFile].fp, ((BYTE*)buffer)+dwTotRead, dwRead, (DWORD*)&nNumOfBytesRead, NULL); if(ret==FALSE && GetLastError()==ERROR_HANDLE_EOF) { m_bIsEOF = TRUE;return FALSE; } #else nNumOfBytesRead = fread(((BYTE*)buffer)+dwTotRead, 1,dwRead ,m_files[m_nCurFile].fp); if(nNumOfBytesRead<=0) { m_bIsEOF = TRUE;return FALSE; } ret=TRUE; #endif if(dwRead!=nNumOfBytesRead) // 발생하면 안된다.. { ASSERT(0); return FALSE; } m_nVirtualFilePos += nNumOfBytesRead; // virtual 파일 위치.. m_nCurFilePos+=nNumOfBytesRead; // 물리적 파일 위치. dwRemain-=nNumOfBytesRead; dwTotRead+=nNumOfBytesRead; if(pTotRead) *pTotRead=dwTotRead; if(m_nCurFilePos==m_files[m_nCurFile].nFileSize-m_files[m_nCurFile].nMultivolTailSize) // overflow { m_nCurFile++; #ifdef _WIN32 if(m_files[m_nCurFile].fp==INVALID_HANDLE_VALUE) #else if(m_files[m_nCurFile].fp==NULL) #endif { m_bIsEOF = TRUE; if(dwRemain==0) return TRUE; // 완전히 끝까지 읽었다.. return FALSE; } m_nCurFilePos = m_files[m_nCurFile].nMultivolHeaderSize; // header skip #ifdef _WIN32 SetFilePointer(m_files[m_nCurFile].fp, (int)m_nCurFilePos, NULL, FILE_BEGIN); #else unalz_fseek(m_files[m_nCurFile].fp, m_nCurFilePos, SEEK_SET); #endif } else if(m_nCurFilePos>m_files[m_nCurFile].nFileSize-m_files[m_nCurFile].nMultivolTailSize) ASSERT(0); } return ret; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// error code 를 스트링으로 바꿔 준다. /// @param nERR /// @return /// @date 2004-10-24 오후 3:28:39 //////////////////////////////////////////////////////////////////////////////////////////////////// const char* CUnAlz::LastErrToStr(ERR nERR) { if(nERR>= sizeof(errorstrtable)/sizeof(errorstrtable[0])) {ASSERT(0); return NULL; } return errorstrtable[nERR]; } // by xf86 BOOL CUnAlz::chkValidPassword() { if(IsEncryptedFile()==FALSE) {return TRUE;} if (getPasswordLen() == 0){ m_nErr = ERR_PASSWD_NOT_SET; return FALSE; } InitCryptKeys(m_szPasswd); if(CryptCheck(m_posCur->encChk) == FALSE){ m_nErr = ERR_INVALID_PASSWD; return FALSE; } return TRUE; } /* //////////////////////////////////////////////////////////////////////////////////////////////////// // from CZipArchive // Copyright (C) 2000 - 2004 Tadeusz Dracz // // http://www.artpol-software.com // // it's under GPL. //////////////////////////////////////////////////////////////////////////////////////////////////// void CUnAlz::CryptDecodeBuffer(UINT32 uCount, CHAR *buf) { if (IsEncrypted()) for (UINT32 i = 0; i < uCount; i++) CryptDecode(buf[i]); } void CUnAlz::CryptInitKeys() { m_keys[0] = 305419896L; m_keys[1] = 591751049L; m_keys[2] = 878082192L; for (int i = 0; i < strlen(m_szPasswd); i++) CryptUpdateKeys(m_szPasswd[i]); } void CUnAlz::CryptUpdateKeys(CHAR c) { m_keys[0] = CryptCRC32(m_keys[0], c); m_keys[1] += m_keys[0] & 0xff; m_keys[1] = m_keys[1] * 134775813L + 1; c = CHAR(m_keys[1] >> 24); m_keys[2] = CryptCRC32(m_keys[2], c); } BOOL CUnAlz::CryptCheck(CHAR *buf) { CHAR b = 0; for (int i = 0; i < ALZ_ENCR_HEADER_LEN; i++) { b = buf[i]; CryptDecode((CHAR&)b); } if (IsDataDescr()) // Data descriptor present return CHAR(m_posCur->head.fileTimeDate >> 8) == b; else return CHAR(m_posCur->maybeCRC >> 24) == b; } CHAR CUnAlz::CryptDecryptCHAR() { int temp = (m_keys[2] & 0xffff) | 2; return (CHAR)(((temp * (temp ^ 1)) >> 8) & 0xff); } void CUnAlz::CryptDecode(CHAR &c) { c ^= CryptDecryptCHAR(); CryptUpdateKeys(c); } UINT32 CUnAlz::CryptCRC32(UINT32 l, CHAR c) { const ULONG *CRC_TABLE = get_crc_table(); return CRC_TABLE[(l ^ c) & 0xff] ^ (l >> 8); } */ //////////////////////////////////////////////////////////////////////////////////////////////////// /// 암호걸린 파일인지 여부 /// @param fileDescriptor /// @return /// @date 2004-11-27 오후 11:25:32 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::IsEncryptedFile(BYTE fileDescriptor) { return fileDescriptor&0x01; } BOOL CUnAlz::IsEncryptedFile() { return m_posCur->head.fileDescriptor&0x01; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 암호로 키 초기화 /// @param szPassword /// @return /// @date 2004-11-27 오후 11:04:01 //////////////////////////////////////////////////////////////////////////////////////////////////// void CUnAlz::InitCryptKeys(const CHAR* szPassword) { m_key[0] = 305419896; m_key[1] = 591751049; m_key[2] = 878082192; int i; for(i=0;i<(int)strlen(szPassword);i++) { UpdateKeys(szPassword[i]); } } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 데이타로 키 업데이트하기 /// @param c /// @return /// @date 2004-11-27 오후 11:04:09 //////////////////////////////////////////////////////////////////////////////////////////////////// void CUnAlz::UpdateKeys(BYTE c) { m_key[0] = CRC32(m_key[0], c); m_key[1] = m_key[1]+(m_key[0]&0x000000ff); m_key[1] = m_key[1]*134775813+1; m_key[2] = CRC32(m_key[2],m_key[1]>>24); } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 암호가 맞는지 헤더 체크하기 /// @param buf /// @return /// @date 2004-11-27 오후 11:04:24 //////////////////////////////////////////////////////////////////////////////////////////////////// BOOL CUnAlz::CryptCheck(const BYTE* buf) { int i; BYTE c; BYTE temp[ALZ_ENCR_HEADER_LEN]; memcpy(temp, buf, ALZ_ENCR_HEADER_LEN); // 임시 복사. for(i=0;i<ALZ_ENCR_HEADER_LEN;i++) { c = temp[i] ^ DecryptByte(); UpdateKeys(c); temp[i] = c; } if (IsDataDescr()) // Data descriptor present return (m_posCur->head.fileTimeDate >> 8) == c; else return ( ((m_posCur->fileCRC)>>24) ) == c; // 파일 crc 의 최상위 byte } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 키에서 데이타 추출 /// @return /// @date 2004-11-27 오후 11:05:36 //////////////////////////////////////////////////////////////////////////////////////////////////// BYTE CUnAlz::DecryptByte() { UINT16 temp; temp = m_key[2] | 2; return (temp * (temp^1))>>8; } //////////////////////////////////////////////////////////////////////////////////////////////////// /// 데이타 압축 풀기 /// @param nSize /// @param data /// @return /// @date 2004-11-27 오후 11:03:30 //////////////////////////////////////////////////////////////////////////////////////////////////// void CUnAlz::DecryptingData(int nSize, BYTE* data) { BYTE* p = data; BYTE temp; while(nSize) { temp = *p ^ DecryptByte(); UpdateKeys(temp); *p = temp; nSize--; p++; } } //////////////////////////////////////////////////////////////////////////////////////////////////// /// CRC 테이블 참조 /// @param l /// @param c /// @return /// @date 2004-11-27 오후 11:14:16 //////////////////////////////////////////////////////////////////////////////////////////////////// UINT32 CUnAlz::CRC32(UINT32 l, BYTE c) { const z_crc_t *CRC_TABLE = get_crc_table(); return CRC_TABLE[(l ^ c) & 0xff] ^ (l >> 8); } void CUnAlz::SetPassword(char *passwd) { if(strlen(passwd) == 0) return; safe_strcpy(m_szPasswd, passwd, UNALZ_LEN_PASSWORD); } #ifdef _UNALZ_ICONV void CUnAlz::SetDestCodepage(const char* szToCodepage) { safe_strcpy(m_szToCodepage, szToCodepage, UNALZ_LEN_CODEPAGE); } #endif //////////////////////////////////////////////////////////////////////////////////////////////////// /// 문자열 처리 함수들 /// @param l /// @param c /// @return /// @date 2007-02 //////////////////////////////////////////////////////////////////////////////////////////////////// unsigned int CUnAlz::_strlcpy (char *dest, const char *src, unsigned int size) { register unsigned int i = 0; if (size > 0) { size--; for (i=0; size > 0 && src[i] != '\0'; ++i, size--) dest[i] = src[i]; dest[i] = '\0'; } while (src[i++]); return i; } unsigned int CUnAlz::_strlcat (char *dest, const char *src, unsigned int size) { register char *d = dest; for (; size > 0 && *d != '\0'; size--, d++); return (d - dest) + _strlcpy(d, src, size); } // 안전한 strcpy void CUnAlz::safe_strcpy(char* dst, const char* src, size_t dst_size) { #ifdef _WIN32 lstrcpynA(dst, src, dst_size); #else _strlcpy(dst, src, dst_size); #endif } void CUnAlz::safe_strcat(char* dst, const char* src, size_t dst_size) { #ifdef _WIN32 StringCchCatExA(dst, dst_size, src, NULL, NULL, STRSAFE_FILL_BEHIND_NULL); //lstrcatA(dst, src); // not safe!! #else _strlcat(dst, src, dst_size); #endif }
25.288316
328
0.566417
kippler
cc845d41a4cda951e0c2a35a8a448fb72c79ac7d
2,767
cpp
C++
popcnt-harley-seal.cpp
kimwalisch/sse-popcount
8f7441afb60847088aac9566d711969c48a03387
[ "BSD-2-Clause" ]
275
2015-04-06T19:49:18.000Z
2022-03-19T06:23:47.000Z
popcnt-harley-seal.cpp
kimwalisch/sse-popcount
8f7441afb60847088aac9566d711969c48a03387
[ "BSD-2-Clause" ]
20
2015-09-02T04:41:15.000Z
2021-02-24T17:48:51.000Z
popcnt-harley-seal.cpp
kimwalisch/sse-popcount
8f7441afb60847088aac9566d711969c48a03387
[ "BSD-2-Clause" ]
57
2015-06-01T01:08:02.000Z
2022-01-02T12:49:43.000Z
namespace { /// This uses fewer arithmetic operations than any other known /// implementation on machines with fast multiplication. /// It uses 12 arithmetic operations, one of which is a multiply. /// http://en.wikipedia.org/wiki/Hamming_weight#Efficient_implementation /// uint64_t popcount_mul(uint64_t x) { const uint64_t m1 = UINT64_C(0x5555555555555555); const uint64_t m2 = UINT64_C(0x3333333333333333); const uint64_t m4 = UINT64_C(0x0F0F0F0F0F0F0F0F); const uint64_t h01 = UINT64_C(0x0101010101010101); x -= (x >> 1) & m1; x = (x & m2) + ((x >> 2) & m2); x = (x + (x >> 4)) & m4; return (x * h01) >> 56; } /// Carry-save adder (CSA). /// @see Chapter 5 in "Hacker's Delight". /// void CSA(uint64_t& h, uint64_t& l, uint64_t a, uint64_t b, uint64_t c) { uint64_t u = a ^ b; h = (a & b) | (u & c); l = u ^ c; } /// Harley-Seal popcount (4th iteration). /// The Harley-Seal popcount algorithm is one of the fastest algorithms /// for counting 1 bits in an array using only integer operations. /// This implementation uses only 5.69 instructions per 64-bit word. /// @see Chapter 5 in "Hacker's Delight" 2nd edition. /// uint64_t popcnt_harley_seal_64bit(const uint64_t* data, const uint64_t size) { uint64_t total = 0; uint64_t ones = 0, twos = 0, fours = 0, eights = 0, sixteens = 0; uint64_t twosA, twosB, foursA, foursB, eightsA, eightsB; uint64_t limit = size - size % 16; uint64_t i = 0; for(; i < limit; i += 16) { CSA(twosA, ones, ones, data[i+0], data[i+1]); CSA(twosB, ones, ones, data[i+2], data[i+3]); CSA(foursA, twos, twos, twosA, twosB); CSA(twosA, ones, ones, data[i+4], data[i+5]); CSA(twosB, ones, ones, data[i+6], data[i+7]); CSA(foursB, twos, twos, twosA, twosB); CSA(eightsA,fours, fours, foursA, foursB); CSA(twosA, ones, ones, data[i+8], data[i+9]); CSA(twosB, ones, ones, data[i+10], data[i+11]); CSA(foursA, twos, twos, twosA, twosB); CSA(twosA, ones, ones, data[i+12], data[i+13]); CSA(twosB, ones, ones, data[i+14], data[i+15]); CSA(foursB, twos, twos, twosA, twosB); CSA(eightsB, fours, fours, foursA, foursB); CSA(sixteens, eights, eights, eightsA, eightsB); total += popcount_mul(sixteens); } total *= 16; total += 8 * popcount_mul(eights); total += 4 * popcount_mul(fours); total += 2 * popcount_mul(twos); total += 1 * popcount_mul(ones); for(; i < size; i++) total += popcount_mul(data[i]); return total; } } // namespace uint64_t popcnt_harley_seal(const uint8_t* data, const size_t size) { uint64_t total = popcnt_harley_seal_64bit((const uint64_t*) data, size / 8); for (size_t i = size - size % 8; i < size; i++) total += lookup8bit[data[i]]; return total; }
31.089888
78
0.64185
kimwalisch
cc92e631f99cd32b1e9c3eee1a2ee8e50332cb88
1,867
cpp
C++
Controller/FileController.cpp
SAarronB/Vector
225342800beff75e19513bbb6d68a0dcd3eab1e2
[ "MIT" ]
null
null
null
Controller/FileController.cpp
SAarronB/Vector
225342800beff75e19513bbb6d68a0dcd3eab1e2
[ "MIT" ]
null
null
null
Controller/FileController.cpp
SAarronB/Vector
225342800beff75e19513bbb6d68a0dcd3eab1e2
[ "MIT" ]
null
null
null
// // FileController.cpp // Vector // // Created by Bonilla, Sean on 2/5/19. // Copyright © 2019 CTEC. All rights reserved. // #include "FileController.hpp" using namespace std; vector<CrimeData> FileController :: readCrimeDataToVector(string filename){ vector<CrimeData> crimes; string currentCSVLine; int rowCount = 0; ifstream dataFile(filename); //if the file exists at that path. if(dataFile.is_open()){ //Keep Reading Until you are at the end of the file while(!dataFile.eof()){ //Grab each line from the VSV separated by the carriage return character. getline(dataFile, currentCSVLine, '\r'); if(rowCount != 0){ //Create a CrimeData instace forom the line. exclude a black line (usually if opened separeately if(currentCSVLine.length() != 0){ CrimeData row(currentCSVLine); crimes.push_back(row); } } rowCount++; } dataFile.close(); }else{ cerr << "No File" << endl; } return crimes; } vector<Music> FileController :: musicDataToVector(string fileName){ vector<Music> musicList; string currentCSVLine; int rowCount = 0; ifstream dataFile(fileName); //if the file exists at that path if(dataFile.is_open()){ //keepreading until you are tat the end of the file while(!dataFile.eof()){ getline(dataFile, currentCSVLine, '\r'); if(rowCount != 0){ if(currentCSVLine.length() !=0){ Music row(currentCSVLine); musicList.push_back(row); } } rowCount++; } dataFile.close(); }else{ cerr <<"No File"<< endl; } return musicList; }
28.723077
112
0.561864
SAarronB
cc94c1ed84af0a8037617af724c7a2a7fa0f4d9d
728
hpp
C++
source/tm/evaluate/move_scores.hpp
davidstone/technical-machine
fea3306e58cd026846b8f6c71d51ffe7bab05034
[ "BSL-1.0" ]
7
2021-03-05T16:50:19.000Z
2022-02-02T04:30:07.000Z
source/tm/evaluate/move_scores.hpp
davidstone/technical-machine
fea3306e58cd026846b8f6c71d51ffe7bab05034
[ "BSL-1.0" ]
47
2021-02-01T18:54:23.000Z
2022-03-06T19:06:16.000Z
source/tm/evaluate/move_scores.hpp
davidstone/technical-machine
fea3306e58cd026846b8f6c71d51ffe7bab05034
[ "BSL-1.0" ]
1
2021-01-28T13:10:41.000Z
2021-01-28T13:10:41.000Z
// Copyright David Stone 2020. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #pragma once #include <tm/move/max_moves_per_pokemon.hpp> #include <containers/static_vector.hpp> #include <tm/generation.hpp> namespace technicalmachine { struct MoveScores { MoveScores(Generation, StaticVectorMove legal_selections, bool ai); void set(Moves move_name, double score); auto ordered_moves(bool ai) const -> StaticVectorMove; private: struct value_type { Moves move_name; double score; }; containers::static_vector<value_type, bounded::builtin_max_value<MoveSize>> m_scores; }; } // namespace technicalmachine
25.103448
86
0.774725
davidstone
cca1994074eed5734a9fbc22fbe4099d5f9fc42f
2,075
hpp
C++
src/Module/Modem/SCMA/Modem_SCMA.hpp
OlivierHartmann/aff3ct
58c66228b24e09463bd43ea6453ef18bcacd4d8f
[ "MIT" ]
null
null
null
src/Module/Modem/SCMA/Modem_SCMA.hpp
OlivierHartmann/aff3ct
58c66228b24e09463bd43ea6453ef18bcacd4d8f
[ "MIT" ]
4
2018-09-27T16:46:31.000Z
2018-11-22T11:10:41.000Z
src/Module/Modem/SCMA/Modem_SCMA.hpp
OlivierHartmann/aff3ct
58c66228b24e09463bd43ea6453ef18bcacd4d8f
[ "MIT" ]
null
null
null
#ifndef MODEM_SCMA_HPP_ #define MODEM_SCMA_HPP_ #include <complex> #include <vector> #include "Tools/Code/SCMA/modem_SCMA_functions.hpp" #include "../Modem.hpp" namespace aff3ct { namespace module { template <typename B = int, typename R = float, typename Q = R, tools::proto_psi<Q> PSI = tools::psi_0> class Modem_SCMA : public Modem<B,R,Q> { private: const static std::complex<float> CB[6][4][4]; const int re_user[4][3] = {{1,2,4},{0,2,5},{1,3,5},{0,3,4}}; Q arr_phi[4][4][4][4] = {}; // probability functions const bool disable_sig2; R n0; // 1 / n0 = 179.856115108 const int n_ite; public: Modem_SCMA(const int N, const tools::Noise<R>& noise = tools::Sigma<R>(), const int bps = 3, const bool disable_sig2 = false, const int n_ite = 1, const int n_frames = 6); virtual ~Modem_SCMA() = default; virtual void set_noise(const tools::Noise<R>& noise); virtual void modulate ( const B* X_N1, R *X_N2, const int frame_id = -1); using Modem<B,R,Q>::modulate; virtual void demodulate ( const Q *Y_N1, Q *Y_N2, const int frame_id = -1); using Modem<B,R,Q>::demodulate; virtual void demodulate_wg(const R *H_N, const Q *Y_N1, Q *Y_N2, const int frame_id = -1); using Modem<B,R,Q>::demodulate_wg; virtual void filter ( const R *Y_N1, R *Y_N2, const int frame_id = -1); using Modem<B,R,Q>::filter; static bool is_complex_mod() { return true; } static bool is_complex_fil() { return true; } static int size_mod(const int N, const int bps) { return ((int)std::pow(2,bps) * ((N +1) / 2)); } static int size_fil(const int N, const int bps) { return size_mod(N, bps); } private: Q phi(const Q* Y_N1, int i, int j, int k, int re, int batch); Q phi(const Q* Y_N1, int i, int j, int k, int re, int batch, const R* H_N); void demodulate_batch(const Q* Y_N1, Q* Y_N2, int batch); }; } } #include "Modem_SCMA.hxx" #endif /* MODEM_SCMA_HPP_ */
30.072464
126
0.61012
OlivierHartmann
cca36cc4b702dcbc13369012d2af07499411556b
1,180
cpp
C++
core/optimization/Variable.cpp
metalicn20/charge
038bbfa14d8f08ffc359d877419b6b984c60ab85
[ "MIT" ]
null
null
null
core/optimization/Variable.cpp
metalicn20/charge
038bbfa14d8f08ffc359d877419b6b984c60ab85
[ "MIT" ]
null
null
null
core/optimization/Variable.cpp
metalicn20/charge
038bbfa14d8f08ffc359d877419b6b984c60ab85
[ "MIT" ]
null
null
null
#include "Variable.h" using namespace std; Variable::Variable(Alloymaker &alloymaker) { setAlloymaker(alloymaker); } void Variable::setAlloymaker(Alloymaker &value) { alloymaker = &value; } Alloymaker &Variable::getAlloymaker() { return *alloymaker; } double Variable::composition(Standard &std) { vector<string> &symbols = std.getSymbols(); size_t length = symbols.size(); double sum = 0; for (size_t i = 0; i < length; i++) { string element = symbols[i]; auto &cmp = getAlloymaker().getCompositions().get(element); sum += cmp.getPercentage(); } return sum * amount(); } double Variable::goal() { return alloymaker->getPrice(); } double Variable::amount() { return 1 - alloymaker->getLossPercentage() / 100; } double Variable::capacity() { return 1; } double Variable::lowerBound() { return alloymaker->getLowerBound(); } double Variable::upperBound() { return alloymaker->getUpperBound(); } bool Variable::isInteger() { return alloymaker->getIsQuantified(); } void Variable::setAnswer(double value) { answer = value; } double Variable::getAnswer() { return answer; }
15.733333
67
0.659322
metalicn20
ccb2eda4b66331f8b88bdf846cb6e661b814ea75
1,107
hpp
C++
include/service_log.hpp
magicmoremagic/bengine-core
fc9e1c309e62f5b2d7d4797d4b537ecfb3350d19
[ "MIT" ]
null
null
null
include/service_log.hpp
magicmoremagic/bengine-core
fc9e1c309e62f5b2d7d4797d4b537ecfb3350d19
[ "MIT" ]
null
null
null
include/service_log.hpp
magicmoremagic/bengine-core
fc9e1c309e62f5b2d7d4797d4b537ecfb3350d19
[ "MIT" ]
null
null
null
#pragma once #ifndef BE_CORE_SERVICE_LOG_HPP_ #define BE_CORE_SERVICE_LOG_HPP_ #include "service.hpp" #include "service_ids.hpp" #include "console_log_sink.hpp" #include "log.hpp" namespace be { /////////////////////////////////////////////////////////////////////////////// template <> struct SuppressUndefinedService<Log> : True { }; /////////////////////////////////////////////////////////////////////////////// template <> struct ServiceTraits<Log> : ServiceTraits<> { using lazy_ids = yes; }; /////////////////////////////////////////////////////////////////////////////// template <> struct ServiceName<Log> { const char* operator()() { return "Log"; } }; /////////////////////////////////////////////////////////////////////////////// template <> struct ServiceFactory<Log> { std::unique_ptr<Log> operator()(Id id) { std::unique_ptr<Log> ptr = std::make_unique<Log>(); if (id == Id()) { ptr->sink(ConsoleLogSink()); } else if (id == ids::core_service_log_void) { ptr->verbosity_mask(0); } return ptr; } }; } // be #endif
23.0625
79
0.455285
magicmoremagic
ccbb82240f83480c1dff283a2e241ccafbe73505
2,169
cc
C++
2015/day16.cc
triglav/advent_of_code
e96bd0aea417076d997eeb4e49bf6e1cc04b31e0
[ "MIT" ]
null
null
null
2015/day16.cc
triglav/advent_of_code
e96bd0aea417076d997eeb4e49bf6e1cc04b31e0
[ "MIT" ]
null
null
null
2015/day16.cc
triglav/advent_of_code
e96bd0aea417076d997eeb4e49bf6e1cc04b31e0
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <unordered_map> #include "string_utils.h" bool Check(std::unordered_map<std::string_view, int> const &known_facts, std::vector<std::string_view> const &tokens) { for (int i = 2; i < tokens.size(); i += 2) { auto const thing = Trim(tokens[i], ":,"); auto const it = known_facts.find(thing); if (it == known_facts.end()) { continue; } auto const count = sv2number<int>(Trim(tokens[i + 1], ":,")); if (it->second != count) { return false; } } return true; } bool Check2(std::unordered_map<std::string_view, int> const &known_facts, std::vector<std::string_view> const &tokens) { for (int i = 2; i < tokens.size(); i += 2) { auto const thing = Trim(tokens[i], ":,"); auto const it = known_facts.find(thing); if (it == known_facts.end()) { continue; } auto const count = sv2number<int>(Trim(tokens[i + 1], ":,")); if (thing == "cats" || thing == "trees") { if (it->second >= count) { return false; } continue; } if (thing == "pomeranians" || thing == "goldfish") { if (it->second <= count) { return false; } continue; } if (it->second != count) { return false; } } return true; } int main() { std::unordered_map<std::string_view, int> known_facts; known_facts.emplace("children", 3); known_facts.emplace("cats", 7); known_facts.emplace("samoyeds", 2); known_facts.emplace("pomeranians", 3); known_facts.emplace("akitas", 0); known_facts.emplace("vizslas", 0); known_facts.emplace("goldfish", 5); known_facts.emplace("trees", 3); known_facts.emplace("cars", 2); known_facts.emplace("perfumes", 1); int idx1 = 0; int idx2 = 0; std::string line; while (std::getline(std::cin, line)) { auto const t = SplitString(line); if (Check(known_facts, t)) { assert(idx1 == 0); idx1 = sv2number<int>(Trim(t[1], ":,")); } if (Check2(known_facts, t)) { assert(idx2 == 0); idx2 = sv2number<int>(Trim(t[1], ":,")); } } std::cout << idx1 << "\n" << idx2 << "\n"; return 0; }
25.821429
73
0.573997
triglav
ccbff3113c7f71866afd884399212a87286ec115
875
hpp
C++
src/ofxSwizzle/detail/functional/increment_decrement.hpp
t6tn4k/ofxSwizzle
7d5841e738d0f08cb5456b040c5f827be7775131
[ "MIT" ]
null
null
null
src/ofxSwizzle/detail/functional/increment_decrement.hpp
t6tn4k/ofxSwizzle
7d5841e738d0f08cb5456b040c5f827be7775131
[ "MIT" ]
null
null
null
src/ofxSwizzle/detail/functional/increment_decrement.hpp
t6tn4k/ofxSwizzle
7d5841e738d0f08cb5456b040c5f827be7775131
[ "MIT" ]
null
null
null
#ifndef OFX_SWIZZLE_DETAIL_FUNCTIONAL_INCREMENT_DECREMENT_HPP #define OFX_SWIZZLE_DETAIL_FUNCTIONAL_INCREMENT_DECREMENT_HPP #include <utility> namespace ofxSwizzle { namespace detail { struct pre_increment { template <typename T> constexpr auto operator()(T& t) const -> decltype(++t) { return ++t; } }; struct post_increment { template <typename T> constexpr auto operator()(T& t) const -> decltype(t++) { return t++; } }; struct pre_decrement { template <typename T> constexpr auto operator()(T& t) const -> decltype(--t) { return --t; } }; struct post_decrement { template <typename T> constexpr auto operator()(T& t) const -> decltype(t--) { return t--; } }; } } // namespace ofxSwizzle::detail #endif // #ifndef OFX_SWIZZLE_DETAIL_FUNCTIONAL_INCREMENT_DECREMENT_HPP
18.617021
71
0.659429
t6tn4k
ccc12c1372e0e0c2f549742135a4899726092225
1,172
cpp
C++
bench/bench_message.cpp
motion-workshop/shadowmocap-sdk-cpp
2df32936bbfb82b17401734ee850a7b710aa3806
[ "BSD-2-Clause" ]
null
null
null
bench/bench_message.cpp
motion-workshop/shadowmocap-sdk-cpp
2df32936bbfb82b17401734ee850a7b710aa3806
[ "BSD-2-Clause" ]
null
null
null
bench/bench_message.cpp
motion-workshop/shadowmocap-sdk-cpp
2df32936bbfb82b17401734ee850a7b710aa3806
[ "BSD-2-Clause" ]
null
null
null
#include <benchmark/benchmark.h> #include <shadowmocap/message.hpp> #include <algorithm> #include <random> #include <vector> std::vector<char> make_random_bytes(std::size_t n) { std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<int> dis(-128, 127); std::vector<char> buf(n); std::generate(std::begin(buf), std::end(buf), [&]() { return dis(gen); }); return buf; } template <int N> void BM_MessageViewCreation(benchmark::State &state) { using namespace shadowmocap; using item_type = message_view_item<N>; auto data = make_random_bytes(state.range(0) * sizeof(item_type)); for (auto _ : state) { auto v = make_message_view<N>(data); benchmark::DoNotOptimize(v); } state.SetBytesProcessed( static_cast<int64_t>(state.iterations()) * state.range(0) * sizeof(item_type)); } BENCHMARK_TEMPLATE(BM_MessageViewCreation, 8)->Range(1 << 3, 1 << 7); BENCHMARK_TEMPLATE(BM_MessageViewCreation, 16)->Range(1 << 2, 1 << 8); BENCHMARK_TEMPLATE(BM_MessageViewCreation, 32)->Range(1 << 1, 1 << 9); BENCHMARK_TEMPLATE(BM_MessageViewCreation, 64)->Range(1 << 0, 1 << 10);
26.636364
78
0.674061
motion-workshop
cccb113e383cab85bb0427179ecb4cbe2936ba12
1,485
cpp
C++
dvdinfo/detect.cpp
XULPlayer/XULPlayer-legacy
1ab0ad2a196373d81d350bf45c03f690a0bfb8a2
[ "MIT" ]
3
2017-11-29T07:11:24.000Z
2020-03-03T19:23:33.000Z
dvdinfo/detect.cpp
XULPlayer/XULPlayer-legacy
1ab0ad2a196373d81d350bf45c03f690a0bfb8a2
[ "MIT" ]
null
null
null
dvdinfo/detect.cpp
XULPlayer/XULPlayer-legacy
1ab0ad2a196373d81d350bf45c03f690a0bfb8a2
[ "MIT" ]
1
2018-07-12T12:48:52.000Z
2018-07-12T12:48:52.000Z
#include "dvd_reader.h" #include "ifo_types.h" #include "ifo_read.h" #include "nav_read.h" #include "cdrom.h" #include "dvdinfo.h" int detect_media_type(const char *psz_path) { int i_type; char *psz_dup; char psz_tmp[20]; dvd_reader_t *dvd; vcddev_t* p_cddev; WIN32_FIND_DATA FindFileData; HANDLE hFind; if (psz_path == NULL) return TYPE_UNKNOWN; psz_dup = _strdup(psz_path); if( psz_path[0] && psz_path[1] == ':' && psz_path[2] == '\\' && psz_path[3] == '\0' ) { psz_dup[2] = '\0'; } sprintf(psz_tmp, "%c:\\*", psz_path[0]); hFind = FindFirstFile(psz_tmp, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) { free(psz_dup); return TYPE_NOMEDIA; } do { /*CD?*/ sprintf(psz_tmp, "%c:\\Track*.cda", psz_path[0]); hFind = FindFirstFile(psz_tmp, &FindFileData); if (hFind != INVALID_HANDLE_VALUE) { i_type = TYPE_CD; } else { /*VCD?*/ sprintf(psz_tmp, "%c:\\MPEGAV", psz_path[0]); hFind = FindFirstFile(psz_tmp, &FindFileData); if (hFind == INVALID_HANDLE_VALUE) break; i_type = TYPE_VCD; } /*go deeper*/ p_cddev = ioctl_Open(psz_dup); if(p_cddev == NULL) break; ioctl_Close(p_cddev); free(psz_dup); return i_type; } while (0); i_type = TYPE_UNKNOWN; /*DVD?*/ dvd = DVDOpen(psz_dup); if(dvd != NULL) { /*go deeper*/ ifo_handle_t *vmg_file; vmg_file = ifoOpen(dvd, 0); if(vmg_file != NULL) { ifoClose(vmg_file); i_type = TYPE_DVD; } DVDClose(dvd); } free(psz_dup); return i_type; }
19.038462
51
0.642424
XULPlayer
ccce06e6b4fdbb371e2d9d97416f8c732c9fff2c
1,540
cpp
C++
Aoba/src/Core/TaskRunner/TimeoutTaskManager.cpp
KondoA9/OpenSiv3d-GUIKit
355b2e7940bf00a8ef5fc3001243e450dccdeab9
[ "MIT" ]
null
null
null
Aoba/src/Core/TaskRunner/TimeoutTaskManager.cpp
KondoA9/OpenSiv3d-GUIKit
355b2e7940bf00a8ef5fc3001243e450dccdeab9
[ "MIT" ]
32
2021-10-09T10:04:11.000Z
2022-02-25T06:10:13.000Z
Aoba/src/Core/TaskRunner/TimeoutTaskManager.cpp
athnomedical/Aoba
355b2e7940bf00a8ef5fc3001243e450dccdeab9
[ "MIT" ]
null
null
null
#include "TimeoutTaskManager.hpp" namespace s3d::aoba { size_t TimeoutTaskManager::addTask(const std::function<void()>& task, double ms, bool threading) { m_timeouts.emplace_back(task, ms, threading); return m_timeouts[m_timeouts.size() - 1].id(); } bool TimeoutTaskManager::isAlive(size_t id) const { for (const auto& timeout : m_timeouts) { if (timeout.id() == id) { return timeout.isAlive(); } } return false; } bool TimeoutTaskManager::isRunning(size_t id) const { for (const auto& timeout : m_timeouts) { if (timeout.id() == id) { return timeout.isRunning(); } } return false; } void TimeoutTaskManager::update() { bool timeoutDeletable = true; for (auto& timeout : m_timeouts) { timeout.update(); timeoutDeletable &= !timeout.isAlive(); } if (timeoutDeletable) { m_timeouts.clear(); m_timeouts.shrink_to_fit(); } } bool TimeoutTaskManager::stop(size_t id) { for (auto& timeout : m_timeouts) { if (timeout.id() == id) { return timeout.stop(); } } return false; } bool TimeoutTaskManager::restart(size_t id) { for (auto& timeout : m_timeouts) { if (timeout.id() == id) { return timeout.restart(); } } return false; } }
26.101695
102
0.521429
KondoA9
ef9adb4af0ba3756488f6a0f2409d695b815528d
1,875
cpp
C++
src/flapGame/flapGame/LoadPNG.cpp
KnyazQasan/First-Game-c-
417d312bb57bb2373d6d0a89892a55718bc597dc
[ "MIT" ]
239
2020-11-26T12:53:51.000Z
2022-03-24T01:02:49.000Z
src/flapGame/flapGame/LoadPNG.cpp
KnyazQasan/First-Game-c-
417d312bb57bb2373d6d0a89892a55718bc597dc
[ "MIT" ]
6
2020-11-27T04:00:44.000Z
2021-07-07T03:02:57.000Z
src/flapGame/flapGame/LoadPNG.cpp
KnyazQasan/First-Game-c-
417d312bb57bb2373d6d0a89892a55718bc597dc
[ "MIT" ]
24
2020-11-26T22:59:27.000Z
2022-02-06T04:02:50.000Z
#include <flapGame/Core.h> #include <flapGame/GLHelpers.h> // clang-format off #define STBI_MALLOC(sz) PLY_HEAP.alloc(sz) #define STBI_REALLOC(p, newsz) PLY_HEAP.realloc(p, newsz) #define STBI_FREE(p) PLY_HEAP.free(p) // clang-format om #define STB_IMAGE_IMPLEMENTATION #define STBI_ONLY_PNG #include "stb/stb_image.h" namespace flap { void premultiplySRGB(image::Image& dst) { PLY_ASSERT(dst.stride >= dst.width * 4); char* dstRow = dst.data; char* dstRowEnd = dstRow + dst.stride * dst.height; while (dstRow < dstRowEnd) { u32* d = (u32*) dstRow; u32* dEnd = d + dst.width; while (d < dEnd) { Float4 orig = ((Int4<u8>*) d)->to<Float4>() * (1.f / 255.f); Float3 linearPremultipliedColor = fromSRGB(orig.asFloat3()) * orig.a(); Float4 result = {toSRGB(linearPremultipliedColor), 1.f - orig.a()}; *(Int4<u8>*) d = (result * 255.f + 0.5f).to<Int4<u8>>(); d++; } dstRow += dst.stride; } } image::OwnImage loadPNG(StringView src, bool premultiply) { s32 w = 0; s32 h = 0; s32 numChannels = 0; stbi_set_flip_vertically_on_load(true); u8* data = stbi_load_from_memory((const stbi_uc*) src.bytes, src.numBytes, &w, &h, &numChannels, 0); if (!data) return {}; image::Format fmt = image::Format::Byte; if (numChannels == 4) { fmt = image::Format::RGBA; } else if (numChannels != 1) { PLY_ASSERT(0); } u8 bytespp = image::Image::FormatToBPP[(u32) fmt]; image::OwnImage result; result.data = (char*) data; result.stride = w * bytespp; result.width = w; result.height = h; result.bytespp = bytespp; result.format = fmt; if (premultiply && numChannels == 4) { premultiplySRGB(result); } return result; } } // namespace ply
28.409091
104
0.597333
KnyazQasan
ef9f57549e1dd00801d74e754e07ec188ad918e1
973
cpp
C++
Strings/Longest-Prefix-Suffix.cpp
Bhannasa/CP-DSA
395dbdb6b5eb5896cc4182711ff086e1fb76ef7a
[ "MIT" ]
22
2021-10-01T20:14:15.000Z
2022-02-22T15:27:20.000Z
Strings/Longest-Prefix-Suffix.cpp
Bhannasa/CP-DSA
395dbdb6b5eb5896cc4182711ff086e1fb76ef7a
[ "MIT" ]
15
2021-10-01T20:24:55.000Z
2021-10-31T05:55:14.000Z
Strings/Longest-Prefix-Suffix.cpp
Bhannasa/CP-DSA
395dbdb6b5eb5896cc4182711ff086e1fb76ef7a
[ "MIT" ]
76
2021-10-01T20:01:06.000Z
2022-03-02T16:15:24.000Z
// https://practice.geeksforgeeks.org/viewSol.php?subId=58bdb4aa62394291d57f659e2c839932&pid=703402&user=tomarshiv51 // Initial template for C++ #include <bits/stdc++.h> using namespace std; // } Driver Code Ends //User function template for C++ class Solution{ public: int lps(string s) { // Your code goes here int n=s.size(),j=0; int a[n]; a[0]=0; int i=1; while(i<n){ if(s[i]==s[j]){ a[i]=j+1; j++; i++; } else{ if(j==0){ a[i]=0; i++; } else{ j=a[j-1]; } } } return a[n-1]; } }; // { Driver Code Starts. int main() { ios_base::sync_with_stdio(0); cin.tie(NULL); cout.tie(NULL); int t; cin >> t; while(t--) { string str; cin >> str; Solution ob; cout << ob.lps(str) << "\n"; } return 0; } // } Driver Code Ends
15.693548
116
0.463515
Bhannasa
efa401af672bc08b39212830123acadded6ac823
1,764
cpp
C++
mvp_tips/CPUID/CPUID/ExtendedCPU5Intel.cpp
allen7575/The-CPUID-Explorer
77d0feef70482b2e36cff300ea24271384329f60
[ "Naumen", "Condor-1.1", "MS-PL" ]
9
2017-08-31T06:03:18.000Z
2019-01-06T05:07:26.000Z
mvp_tips/CPUID/CPUID/ExtendedCPU5Intel.cpp
allen7575/The-CPUID-Explorer
77d0feef70482b2e36cff300ea24271384329f60
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
mvp_tips/CPUID/CPUID/ExtendedCPU5Intel.cpp
allen7575/The-CPUID-Explorer
77d0feef70482b2e36cff300ea24271384329f60
[ "Naumen", "Condor-1.1", "MS-PL" ]
8
2017-08-31T06:23:22.000Z
2022-01-24T06:47:19.000Z
// ExtendedCPU5Intel.cpp : implementation file // #include "stdafx.h" #include "resource.h" #include "ExtendedCPU5Intel.h" #include "CPUIDx86.h" #include "ReportRegs.h" // CExtendedCPU5Intel dialog IMPLEMENT_DYNCREATE(CExtendedCPU5Intel, CLeaves) CExtendedCPU5Intel::CExtendedCPU5Intel() : CLeaves(CExtendedCPU5Intel::IDD) { } CExtendedCPU5Intel::~CExtendedCPU5Intel() { } void CExtendedCPU5Intel::DoDataExchange(CDataExchange* pDX) { CLeaves::DoDataExchange(pDX); DDX_Control(pDX, IDC_EAX, c_EAX); DDX_Control(pDX, IDC_EBX, c_EBX); DDX_Control(pDX, IDC_ECX, c_ECX); DDX_Control(pDX, IDC_EDX, c_EDX); } BEGIN_MESSAGE_MAP(CExtendedCPU5Intel, CLeaves) END_MESSAGE_MAP() // CExtendedCPU5Intel message handlers /**************************************************************************** * CExtendedCPU5Intel::OnSetActive * Result: BOOL * * Effect: * Reports the registers ****************************************************************************/ BOOL CExtendedCPU5Intel::OnSetActive() { CPUregs regs; GetAndReport(0x80000005, regs); return CLeaves::OnSetActive(); } /**************************************************************************** * CExtendedCPU5Intel::OnInitDialog * Result: BOOL * TRUE, always * Effect: * Initializes the dialog ****************************************************************************/ BOOL CExtendedCPU5Intel::OnInitDialog() { CLeaves::OnInitDialog(); SetFixedFont(c_EAX); SetFixedFont(c_EBX); SetFixedFont(c_ECX); SetFixedFont(c_EDX); return TRUE; // return TRUE unless you set the focus to a control // EXCEPTION: OCX Property Pages should return FALSE }
23.837838
77
0.573696
allen7575