hexsha
stringlengths
40
40
size
int64
19
11.4M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
3
270
max_stars_repo_name
stringlengths
5
110
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
float64
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
3
270
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
78
max_issues_repo_licenses
listlengths
1
9
max_issues_count
float64
1
67k
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
3
270
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
78
max_forks_repo_licenses
listlengths
1
9
max_forks_count
float64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
19
11.4M
avg_line_length
float64
1.93
229k
max_line_length
int64
12
688k
alphanum_fraction
float64
0.07
0.99
matches
listlengths
1
10
ba82be75655fedff2b2458cebfbe39ceec7a0a1c
13,131
hpp
C++
include/libTAU/blockchain/blockchain.hpp
Tau-Coin/libTAU
2e8cace4195faa75b6a75c0ce02496346936bc79
[ "BSL-1.0", "BSD-3-Clause" ]
6
2021-08-16T17:27:10.000Z
2022-01-12T09:18:02.000Z
include/libTAU/blockchain/blockchain.hpp
Tau-Coin/libTAU
2e8cace4195faa75b6a75c0ce02496346936bc79
[ "BSL-1.0", "BSD-3-Clause" ]
null
null
null
include/libTAU/blockchain/blockchain.hpp
Tau-Coin/libTAU
2e8cace4195faa75b6a75c0ce02496346936bc79
[ "BSL-1.0", "BSD-3-Clause" ]
3
2022-01-03T03:06:54.000Z
2022-03-11T03:15:32.000Z
/* Copyright (c) 2021, TaiXiang Cui All rights reserved. You may use, distribute and modify this code under the terms of the BSD license, see LICENSE file. */ #ifndef LIBTAU_BLOCKCHAIN_HPP #define LIBTAU_BLOCKCHAIN_HPP #include <map> #include <set> #include <vector> #include "libTAU/time.hpp" #include "libTAU/aux_/alert_manager.hpp" // for alert_manager #include "libTAU/aux_/common.h" #include "libTAU/aux_/deadline_timer.hpp" #include "libTAU/aux_/session_interface.hpp" #include "libTAU/kademlia/item.hpp" #include "libTAU/kademlia/node_entry.hpp" #include "libTAU/blockchain/blockchain_signal.hpp" #include "libTAU/blockchain/chain_url.hpp" #include "libTAU/blockchain/constants.hpp" #include "libTAU/blockchain/repository.hpp" #include "libTAU/blockchain/repository_impl.hpp" #include "libTAU/blockchain/repository_track.hpp" #include "libTAU/blockchain/tx_pool.hpp" #include "libTAU/common/entry_type.hpp" namespace libTAU { namespace blockchain { using system_clock = std::chrono::system_clock; // default refresh time of main task(100)(ms) constexpr int blockchain_default_refresh_time = 100; // max task size constexpr int blockchain_max_task_size = 10000; // max access peer frequency(interval: 3000 ms) constexpr int blockchain_max_access_peer_interval = 3000; // salt length (first 16 bytes of public key) constexpr int blockchain_salt_length = 16; // max tx list size constexpr int blockchain_max_tx_list_size = 10; constexpr int blockchain_immutable_payload_put_node_size = 1; enum RESULT { SUCCESS, FAIL, MISSING, }; //#if !defined TORRENT_DISABLE_LOGGING || TORRENT_USE_ASSERTS // This is the basic logging and debug interface offered by the blockchain. // a release build with logging disabled (which is the default) will // not have this class at all struct TORRENT_EXTRA_EXPORT blockchain_logger { //#ifndef TORRENT_DISABLE_LOGGING virtual bool should_log() const = 0; virtual void log(char const* fmt, ...) const TORRENT_FORMAT(2,3) = 0; //#endif protected: ~blockchain_logger() {} }; //#endif // TORRENT_DISABLE_LOGGING || TORRENT_USE_ASSERTS class TORRENT_EXPORT blockchain final: public std::enable_shared_from_this<blockchain>, blockchain_logger { public: blockchain(io_context& mIoc, aux::session_interface &mSes) : m_ioc(mIoc), m_ses(mSes), m_refresh_timer(mIoc), m_vote_timer(mIoc), m_exchange_tx_timer(mIoc) { m_repository = std::make_shared<repository_impl>(m_ses.sqldb(), m_ses.kvdb()); } // start blockchain bool start(); // stop bool stop(); // create chain id aux::bytes create_chain_id(std::string community_name); // create new community bool createNewCommunity(const aux::bytes &chain_id, const std::map<dht::public_key, account>& accounts); // follow a chain by url(chain id, peers) bool followChain(const chain_url &url); // un-follow a chain bool unfollowChain(const aux::bytes &chain_id); // send new transaction bool submitTransaction(const transaction& tx); // get account by public key account getAccountInfo(const aux::bytes &chain_id, dht::public_key publicKey); // get main chain block by number block getBlock(const aux::bytes &chain_id, std::int64_t block_number); // get main chain block by hash block getBlock(const aux::bytes &chain_id, sha256_hash block_hash); // get top tip blocks std::vector<block> getTopTipBlocks(const aux::bytes &chain_id, int topNum); // get median tx fee std::int64_t getMedianTxFee(const aux::bytes &chain_id); // set blockchain main loop time interval (ms) void set_blockchain_loop_interval(int milliseconds); // mutable data is pushed here void on_dht_item(dht::item const& i); private: // initialize member variables bool init(); // get current time(ms) static std::int64_t get_total_milliseconds(); // create and follow tau chain bool create_TAU_chain(); // clear all cache void clear_all_cache(); // clear chain cache void clear_chain_cache(const aux::bytes &chain_id); std::shared_ptr<blockchain> self() { return shared_from_this(); } //#ifndef TORRENT_DISABLE_LOGGING bool should_log() const override; void log(char const* fmt, ...) const noexcept override TORRENT_FORMAT(2,3); //#endif void refresh_timeout(error_code const& e); void refresh_vote_timeout(error_code const& e); void refresh_tx_timeout(error_code const& e); void add_entry_task_to_queue(const aux::bytes &chain_id, const common::blockchain_entry_task &task); // follow a chain by chain id and peers bool followChain(const aux::bytes &chain_id, const std::set<dht::public_key>& peers); // load chain all info bool load_chain(const aux::bytes &chain_id); // refresh unchoked peers if timeout // void try_to_refresh_unchoked_peers(const aux::bytes &chain_id); // select a chain randomly aux::bytes select_chain_randomly(); // select a peer randomly dht::public_key select_peer_randomly(const aux::bytes &chain_id); // select an un-choked peer randomly // dht::public_key select_unchoked_peer_randomly(const aux::bytes &chain_id); // select a peer randomly std::set<dht::public_key> select_unchoked_peers(const aux::bytes &chain_id); // try to mine block block try_to_mine_block(const aux::bytes &chain_id); // try to update consensus point block if best voting block changed // void try_to_update_consensus_point_block(const aux::bytes &chain_id); // try to update voting point block if chain changed void try_to_update_voting_point_block(const aux::bytes &chain_id); void try_to_update_visiting_peer(const aux::bytes &chain_id, const dht::public_key& peer); // verify block RESULT verify_block(const aux::bytes &chain_id, block &b, block &previous_block, repository *repo); // process block RESULT process_block(const aux::bytes &chain_id, block &b); // check if a chain is empty, true if has no info, false otherwise bool is_empty_chain(const aux::bytes &chain_id); // check if a block immutable certainly bool is_block_immutable_certainly(const aux::bytes &chain_id, const block &blk); // check if consensus point block immutable, true if it is same to voting block, false otherwise // bool is_voting_point_immutable(const aux::bytes &chain_id); // check if current chain sync completed bool is_sync_completed(const aux::bytes &chain_id); // check if a block in cache or db bool is_block_in_cache_or_db(const aux::bytes &chain_id, const sha256_hash &hash); // get block from block cache or db block get_block_from_cache_or_db(const aux::bytes &chain_id, const sha256_hash &hash); // remove all relevant blocks those on the same chain from cache void remove_all_same_chain_blocks_from_cache(const block &blk); // remove all relevant blocks those on the same chain from cache void remove_all_ancestor_blocks_from_cache(const block &blk); void try_to_slim_down_cache(const aux::bytes &chain_id); // try to rebranch a more difficult chain or a voting chain RESULT try_to_rebranch(const aux::bytes &chain_id, const block &target); // count votes void refresh_vote(const aux::bytes &chain_id); // 使用LevenshteinDistance算法寻找最佳匹配,并提取相应解需要的中间信息(missing tx) void find_best_solution(std::vector<transaction>& txs, const aux::bytes& hash_prefix_array, std::vector<transaction> &missing_txs); // make a salt on mutable channel static std::string make_salt(const aux::bytes &chain_id); // send data to peer void send_to(const aux::bytes &chain_id, const dht::public_key &peer, entry const& data); // request signal from a given peer // void request_signal(const aux::bytes &chain_id, const dht::public_key& peer); // publish online/new message signal to a given peer // void publish_signal(const aux::bytes &chain_id, const dht::public_key& peer, // const blockchain_signal &peer_signal = blockchain_signal()); // process signal from dht // void process_signal(const blockchain_signal & signal, const aux::bytes &chain_id, const dht::public_key &peer); // immutable data callback // void get_immutable_block_callback(aux::bytes const& chain_id, sha256_hash target, dht::item const& i); // // get immutable item from dht // void dht_get_immutable_block_item(aux::bytes const& chain_id, sha256_hash const& target, std::vector<dht::node_entry> const& eps); // // // immutable data callback // void get_immutable_tx_callback(aux::bytes const& chain_id, sha256_hash target, dht::item const& i); // get immutable item from dht // void dht_get_immutable_tx_item(aux::bytes const& chain_id, sha256_hash const& target, std::vector<dht::node_entry> const& eps); // mutable data callback // void get_mutable_callback(aux::bytes const& chain_id, dht::item const& i, bool); // // get mutable item from dht // void dht_get_mutable_item(aux::bytes const& chain_id, std::array<char, 32> key // , std::string salt, dht::timestamp t); // put immutable item to dht // void dht_put_immutable_item(entry const& data, std::vector<dht::node_entry> const& eps, sha256_hash target); // put mutable item to dht void dht_put_mutable_item(std::array<char, 32> key , std::function<void(entry&, std::array<char,64>& , std::int64_t&, std::string const&)> cb , std::string salt, const dht::public_key &peer); // io context io_context& m_ioc; // session interface aux::session_interface& m_ses; // refresh time interval int m_refresh_time = blockchain_default_refresh_time; // deadline timer aux::deadline_timer m_refresh_timer; // vote timer aux::deadline_timer m_vote_timer; // tx timer aux::deadline_timer m_exchange_tx_timer; // blockchain db std::shared_ptr<repository> m_repository; // tx pool std::map<aux::bytes, tx_pool> m_tx_pools; // chain status bool m_stop = false; // all chains std::vector<aux::bytes> m_chains; // // all chain peers // std::map<aux::bytes, std::set<dht::public_key>> m_chain_peers; // // // all chain gossip peers // std::map<aux::bytes, std::set<dht::public_key>> m_chain_gossip_peers; // // un-choked peers // std::map<aux::bytes, std::set<dht::public_key>> m_unchoked_peers; // // // un-choked peers signal // std::map<aux::bytes, std::map<dht::public_key, blockchain_signal>> m_unchoked_peer_signal; // // // update un-choked peers time(s) // std::map<aux::bytes, std::int64_t> m_update_peer_time; // the time that last got data from dht(ms) // std::map<aux::bytes, std::int64_t> m_last_got_data_time; // all tasks std::map<aux::bytes, std::set<common::blockchain_entry_task>> m_tasks; std::map<aux::bytes, std::set<dht::public_key>> m_visiting_history; std::map<aux::bytes, std::pair<dht::public_key, std::int64_t>> m_visiting_time; std::map<aux::bytes, std::map<dht::public_key, std::int64_t>> m_last_visiting_time; // block cache todo:100000? std::map<aux::bytes, std::map<sha256_hash, block>> m_blocks; // head blocks std::map<aux::bytes, block> m_head_blocks; // tail blocks std::map<aux::bytes, block> m_tail_blocks; // consensus point blocks std::map<aux::bytes, block> m_consensus_point_blocks; // voting point blocks std::map<aux::bytes, block> m_voting_point_blocks; // current best votes std::map<aux::bytes, vote> m_best_votes; // votes std::map<aux::bytes, std::map<dht::public_key, vote>> m_votes; // blockchain signal time(map:key1->chain id, key2->peer, value->signal time(ms))(1min) // std::map<aux::bytes, std::map<dht::public_key, std::int64_t>> m_latest_signal_time; // the latest item timestamp of peer // std::map<aux::bytes, std::map<dht::public_key, dht::timestamp>> m_latest_item_timestamp; }; } } #endif //LIBTAU_BLOCKCHAIN_HPP
36.074176
140
0.656538
[ "vector" ]
ba8af44e0fef14a1016dcecf4cb937ba47a46506
3,251
cpp
C++
src/common/pointcloud_conversions.cpp
myalfred03/dynamic_robot_localization
d26e4563ab98171ae724a527a2c63d1b1abb1843
[ "BSD-3-Clause" ]
3
2017-06-13T07:02:17.000Z
2019-05-04T12:37:24.000Z
src/common/pointcloud_conversions.cpp
myalfred03/dynamic_robot_localization
d26e4563ab98171ae724a527a2c63d1b1abb1843
[ "BSD-3-Clause" ]
null
null
null
src/common/pointcloud_conversions.cpp
myalfred03/dynamic_robot_localization
d26e4563ab98171ae724a527a2c63d1b1abb1843
[ "BSD-3-Clause" ]
3
2019-06-06T08:08:09.000Z
2019-12-02T14:07:52.000Z
/**\file pointcloud_conversions.cpp * \brief Description... * * @version 1.0 * @author Carlos Miguel Correia da Costa */ // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <includes> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #include <dynamic_robot_localization/common/common.h> #include <dynamic_robot_localization/common/impl/pointcloud_conversions.hpp> // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </includes> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> <template instantiations> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< #ifndef DRL_NO_PRECOMPILE #include <pcl/impl/instantiate.hpp> #include <pcl/point_types.h> #define PCL_INSTANTIATE_DRLPointcloudConversionsFromROSMsg(T) template bool dynamic_robot_localization::pointcloud_conversions::fromROSMsg<T>(const nav_msgs::OccupancyGrid&, pcl::PointCloud<T>&, dynamic_robot_localization::pointcloud_conversions::OccupancyGridValuesPtr, int); PCL_INSTANTIATE(DRLPointcloudConversionsFromROSMsg, DRL_POINT_TYPES) #define PCL_INSTANTIATE_DRLPointcloudConversionsFlipPointCloudNormalsUsingOccpancyGrid(T) template size_t dynamic_robot_localization::pointcloud_conversions::flipPointCloudNormalsUsingOccpancyGrid<T>(const nav_msgs::OccupancyGrid&, pcl::PointCloud<T>&, int, float, bool); PCL_INSTANTIATE(DRLPointcloudConversionsFlipPointCloudNormalsUsingOccpancyGrid, DRL_POINT_TYPES) #define PCL_INSTANTIATE_DRLPointcloudConversionsFromFile(T) template bool dynamic_robot_localization::pointcloud_conversions::fromFile< pcl::PointCloud<T> >(const std::string&, pcl::PointCloud<T>&); PCL_INSTANTIATE(DRLPointcloudConversionsFromFile, DRL_POINT_TYPES) PCL_INSTANTIATE(DRLPointcloudConversionsFromFile, DRL_DESCRIPTOR_TYPES) #define PCL_INSTANTIATE_DRLPointcloudConversionsToFile(T) template bool dynamic_robot_localization::pointcloud_conversions::toFile< pcl::PointCloud<T> >(const std::string&, const pcl::PointCloud<T>&, bool); PCL_INSTANTIATE(DRLPointcloudConversionsToFile, DRL_POINT_TYPES) #endif namespace dynamic_robot_localization { namespace pointcloud_conversions { template<> bool fromFile(const std::string& filename, pcl::PCLPointCloud2& pointcloud) { std::string::size_type index = filename.rfind("."); if (index == std::string::npos) return false; std::string extension = filename.substr(index + 1); if (extension == "pcd") { if (pcl::io::loadPCDFile(filename, pointcloud) == 0 && !pointcloud.data.empty()) return true; } else if (extension == "ply") { if (pcl::io::loadPLYFile(filename, pointcloud) == 0 && !pointcloud.data.empty()) return true; } else { pcl::PolygonMesh mesh; if (pcl::io::loadPolygonFile(filename, mesh) != 0) { // obj | ply | stl | vtk | doesn't load normals curvature | doesn't load normals from .ply .stl pointcloud = mesh.cloud; return !pointcloud.data.empty(); } } return false; } } } // >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> </template instantiations> <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
50.796875
276
0.639188
[ "mesh" ]
ba9644091f1651d73bf69c3fe5767dcc126f6cf8
3,026
hpp
C++
include/MemeCore/StandardLib.hpp
Gurman8r/CppSandbox
a0f1cf0ade69ecaba4d167c0611a620914155e53
[ "MIT" ]
null
null
null
include/MemeCore/StandardLib.hpp
Gurman8r/CppSandbox
a0f1cf0ade69ecaba4d167c0611a620914155e53
[ "MIT" ]
null
null
null
include/MemeCore/StandardLib.hpp
Gurman8r/CppSandbox
a0f1cf0ade69ecaba4d167c0611a620914155e53
[ "MIT" ]
null
null
null
#ifndef _ML_STANDARD_LIB_HPP_ #define _ML_STANDARD_LIB_HPP_ /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <MemeCore/Config.hpp> /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #include <algorithm> #include <array> #include <cassert> #include <cctype> #include <chrono> #include <csignal> #include <cstddef> #include <ctime> #include <fstream> #include <future> #include <initializer_list> #include <iomanip> #include <iostream> #include <iterator> #include <limits> #include <locale> #include <map> #include <mutex> #include <queue> #include <random> #include <regex> #include <stack> #include <sstream> #include <stdarg.h> #include <stdint.h> #include <string> #include <thread> #include <type_traits> #include <typeindex> #include <typeinfo> #include <unordered_map> #include <utility> #include <vector> /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ namespace ml { /* * * * * * * * * * * * * * * * * * * * */ using int8_t = typename signed char; // 1 byte using int16_t = typename signed short; // 2 bytes using int32_t = typename signed int; // 4 bytes using int64_t = typename signed long long; // 8 bytes /* * * * * * * * * * * * * * * * * * * * */ using uint8_t = typename unsigned char; // 1 byte using uint16_t = typename unsigned short; // 2 bytes using uint32_t = typename unsigned int; // 4 bytes using uint64_t = typename unsigned long long; // 8 bytes /* * * * * * * * * * * * * * * * * * * * */ #ifdef ML_x64 using size_t = typename uint64_t; using ptrdiff_t = typename int64_t; using intptr_t = typename int64_t; using intmax_t = typename int64_t; #else using size_t = typename uint32_t; using ptrdiff_t = typename int32_t; using intptr_t = typename int32_t; using intmax_t = typename int32_t; #endif /* * * * * * * * * * * * * * * * * * * * */ } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ namespace ml { // IO /* * * * * * * * * * * * * * * * * * * * */ static std::ostream & cout = std::cout; static std::ostream & cerr = std::cerr; static std::istream & cin = std::cin; template <class Elem, class Traits> inline std::basic_ostream<Elem, Traits> & endl(std::basic_ostream<Elem, Traits> & out) { out.put(out.widen('\n')); out.flush(); return (out); } // Usings /* * * * * * * * * * * * * * * * * * * * */ template <class K, class V> using HashMap = typename std::unordered_map <K, V>; template <class T> using Initializer = typename std::initializer_list<T>; template <class K, class V> using Map = typename std::map <K, V>; template <class K, class V> using MultiMap = typename std::multimap <K, V>; template <class K, class V> using Pair = typename std::pair <K, V>; using StreamBuf = typename std::streambuf; } /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */ #endif // !_ML_STANDARD_LIB_HPP_
27.761468
87
0.542961
[ "vector" ]
ba98a1f4e683c426661bb427c070b98f4c9317fe
43,459
cc
C++
chaps/chaps_proxy.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
chaps/chaps_proxy.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
chaps/chaps_proxy.cc
Toromino/chromiumos-platform2
97e6ba18f0e5ab6723f3448a66f82c1a07538d87
[ "BSD-3-Clause" ]
null
null
null
// Copyright (c) 2011 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chaps/chaps_proxy.h" #include <utility> #include <base/logging.h> #include <base/macros.h> #include <base/memory/ptr_util.h> #include <base/memory/ref_counted.h> #include <brillo/dbus/dbus_method_invoker.h> #include <dbus/message.h> #include <dbus/object_path.h> #include "chaps/chaps.h" #include "chaps/chaps_utility.h" #include "chaps/isolate.h" #include "pkcs11/cryptoki.h" using brillo::Blob; using brillo::SecureBlob; using brillo::dbus_utils::ExtractMethodCallResults; using std::string; using std::vector; namespace { // 5 minutes, since some TPM operations can take a while. constexpr base::TimeDelta kDBusTimeout = base::Minutes(5); // TODO(yich): We should remove this after chromeos-dbus-binding support // SecureBlob. inline const Blob ToBlob(const SecureBlob& blob) { return Blob(blob.begin(), blob.end()); } // We need to be able to shadow AtExitManagers because we don't know if the // caller has an AtExitManager already or not (on Chrome it might, but on Linux // it probably won't). class ProxyAtExitManager : public base::AtExitManager { public: ProxyAtExitManager() : AtExitManager(true) {} ProxyAtExitManager(const ProxyAtExitManager&) = delete; ProxyAtExitManager& operator=(const ProxyAtExitManager&) = delete; }; } // namespace namespace chaps { // Below is the real implementation. ChapsProxyImpl::ChapsProxyImpl(std::unique_ptr<base::AtExitManager> at_exit) : at_exit_(std::move(at_exit)) {} ChapsProxyImpl::~ChapsProxyImpl() {} // static std::unique_ptr<ChapsProxyImpl> ChapsProxyImpl::Create(bool shadow_at_exit) { std::unique_ptr<base::AtExitManager> at_exit; if (shadow_at_exit) { at_exit = std::make_unique<ProxyAtExitManager>(); } auto chaps_proxy_impl = base::WrapUnique(new ChapsProxyImpl(std::move(at_exit))); base::Thread::Options options(base::MessagePumpType::IO, 0); chaps_proxy_impl->dbus_thread_ = std::make_unique<ChapsProxyThread>(chaps_proxy_impl.get()); chaps_proxy_impl->dbus_thread_->StartWithOptions(std::move(options)); base::WaitableEvent event(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); bool connected = false; chaps_proxy_impl->dbus_thread_->task_runner()->PostTask( FROM_HERE, base::BindOnce(&ChapsProxyImpl::InitializationTask, base::Unretained(chaps_proxy_impl.get()), &event, &connected)); event.Wait(); if (!connected) { // We should return nullptr when failed to connect to system D-Bus, and let // C_Initialize return CKR_GENERAL_ERROR. LOG(ERROR) << "Failed to connect to system D-Bus"; return nullptr; } return chaps_proxy_impl; } void ChapsProxyImpl::InitializationTask(base::WaitableEvent* completion, bool* connected) { CHECK(completion); CHECK(dbus_thread_->task_runner()->BelongsToCurrentThread()); dbus::Bus::Options options; options.bus_type = dbus::Bus::SYSTEM; bus_ = base::MakeRefCounted<dbus::Bus>(options); *connected = bus_->Connect(); default_proxy_ = std::make_unique<org::chromium::ChapsProxy>(bus_); proxy_ = default_proxy_.get(); completion->Signal(); } void ChapsProxyImpl::ShutdownTask() { default_proxy_.reset(); bus_->ShutdownAndBlock(); bus_.reset(); } template <typename MethodType, typename... Args> bool ChapsProxyImpl::SendRequestAndWait(const MethodType& method, Args... args) { base::WaitableEvent event(base::WaitableEvent::ResetPolicy::MANUAL, base::WaitableEvent::InitialState::NOT_SIGNALED); bool success = true; dbus_thread_->task_runner()->PostTask( FROM_HERE, base::BindOnce( [](org::chromium::ChapsProxyInterface* proxy, base::WaitableEvent* completion, bool* success, const MethodType& method, Args... args) { brillo::ErrorPtr error = nullptr; if (!(proxy->*method)(args..., &error, kDBusTimeout.InMilliseconds()) || error) { *success = false; } completion->Signal(); }, proxy_, &event, &success, method, args...)); event.Wait(); return success; } bool ChapsProxyImpl::OpenIsolate(SecureBlob* isolate_credential, bool* new_isolate_created) { Blob isolate_credential_out; bool result = false; bool success = SendRequestAndWait(&org::chromium::ChapsProxyInterface::OpenIsolate, ToBlob(*isolate_credential), &isolate_credential_out, new_isolate_created, &result); *isolate_credential = SecureBlob(isolate_credential_out); return success && result; } void ChapsProxyImpl::CloseIsolate(const SecureBlob& isolate_credential) { SendRequestAndWait(&org::chromium::ChapsProxyInterface::CloseIsolate, ToBlob(isolate_credential)); } bool ChapsProxyImpl::LoadToken(const SecureBlob& isolate_credential, const string& path, const SecureBlob& auth_data, const string& label, uint64_t* slot_id) { bool result = false; bool success = SendRequestAndWait(&org::chromium::ChapsProxyInterface::LoadToken, ToBlob(isolate_credential), path, ToBlob(auth_data), label, slot_id, &result); return success && result; } void ChapsProxyImpl::UnloadToken(const SecureBlob& isolate_credential, const string& path) { SendRequestAndWait(&org::chromium::ChapsProxyInterface::UnloadToken, ToBlob(isolate_credential), path); } void ChapsProxyImpl::ChangeTokenAuthData( const string& path, const brillo::SecureBlob& old_auth_data, const brillo::SecureBlob& new_auth_data) { SendRequestAndWait(&org::chromium::ChapsProxyInterface::ChangeTokenAuthData, path, ToBlob(old_auth_data), ToBlob(new_auth_data)); } bool ChapsProxyImpl::GetTokenPath(const SecureBlob& isolate_credential, uint64_t slot_id, string* path) { bool result = false; bool success = SendRequestAndWait(&org::chromium::ChapsProxyInterface::GetTokenPath, ToBlob(isolate_credential), slot_id, path, &result); return success && result; } void ChapsProxyImpl::SetLogLevel(const int32_t& level) { SendRequestAndWait(&org::chromium::ChapsProxyInterface::SetLogLevel, level); } uint32_t ChapsProxyImpl::GetSlotList(const SecureBlob& isolate_credential, bool token_present, vector<uint64_t>* slot_list) { LOG_CK_RV_AND_RETURN_IF(!slot_list, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::GetSlotList, ToBlob(isolate_credential), token_present, slot_list, &result); return result; } uint32_t ChapsProxyImpl::GetSlotInfo(const SecureBlob& isolate_credential, uint64_t slot_id, SlotInfo* slot_info) { LOG_CK_RV_AND_RETURN_IF(!slot_info, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::GetSlotInfo, ToBlob(isolate_credential), slot_id, slot_info, &result); return result; } uint32_t ChapsProxyImpl::GetTokenInfo(const SecureBlob& isolate_credential, uint64_t slot_id, TokenInfo* token_info) { LOG_CK_RV_AND_RETURN_IF(!token_info, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::GetTokenInfo, ToBlob(isolate_credential), slot_id, token_info, &result); return result; } uint32_t ChapsProxyImpl::GetMechanismList(const SecureBlob& isolate_credential, uint64_t slot_id, vector<uint64_t>* mechanism_list) { LOG_CK_RV_AND_RETURN_IF(!mechanism_list, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::GetMechanismList, ToBlob(isolate_credential), slot_id, mechanism_list, &result); return result; } uint32_t ChapsProxyImpl::GetMechanismInfo(const SecureBlob& isolate_credential, uint64_t slot_id, uint64_t mechanism_type, MechanismInfo* mechanism_info) { LOG_CK_RV_AND_RETURN_IF(!mechanism_info, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::GetMechanismInfo, ToBlob(isolate_credential), slot_id, mechanism_type, mechanism_info, &result); return result; } uint32_t ChapsProxyImpl::InitToken(const SecureBlob& isolate_credential, uint64_t slot_id, const string* so_pin, const vector<uint8_t>& label) { uint32_t result = CKR_GENERAL_ERROR; string tmp_pin; if (so_pin) tmp_pin = *so_pin; SendRequestAndWait(&org::chromium::ChapsProxyInterface::InitToken, ToBlob(isolate_credential), slot_id, (so_pin == nullptr), tmp_pin, label, &result); return result; } uint32_t ChapsProxyImpl::InitPIN(const SecureBlob& isolate_credential, uint64_t session_id, const string* pin) { uint32_t result = CKR_GENERAL_ERROR; string tmp_pin; if (pin) tmp_pin = *pin; SendRequestAndWait(&org::chromium::ChapsProxyInterface::InitPIN, ToBlob(isolate_credential), session_id, (pin == nullptr), tmp_pin, &result); return result; } uint32_t ChapsProxyImpl::SetPIN(const SecureBlob& isolate_credential, uint64_t session_id, const string* old_pin, const string* new_pin) { uint32_t result = CKR_GENERAL_ERROR; string tmp_old_pin; if (old_pin) tmp_old_pin = *old_pin; string tmp_new_pin; if (new_pin) tmp_new_pin = *new_pin; SendRequestAndWait(&org::chromium::ChapsProxyInterface::SetPIN, ToBlob(isolate_credential), session_id, (old_pin == nullptr), tmp_old_pin, (new_pin == nullptr), tmp_new_pin, &result); return result; } uint32_t ChapsProxyImpl::OpenSession(const SecureBlob& isolate_credential, uint64_t slot_id, uint64_t flags, uint64_t* session_id) { LOG_CK_RV_AND_RETURN_IF(!session_id, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::OpenSession, ToBlob(isolate_credential), slot_id, flags, session_id, &result); return result; } uint32_t ChapsProxyImpl::CloseSession(const SecureBlob& isolate_credential, uint64_t session_id) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::CloseSession, ToBlob(isolate_credential), session_id, &result); return result; } uint32_t ChapsProxyImpl::GetSessionInfo(const SecureBlob& isolate_credential, uint64_t session_id, SessionInfo* session_info) { LOG_CK_RV_AND_RETURN_IF(!session_info, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::GetSessionInfo, ToBlob(isolate_credential), session_id, session_info, &result); return result; } uint32_t ChapsProxyImpl::GetOperationState(const SecureBlob& isolate_credential, uint64_t session_id, vector<uint8_t>* operation_state) { LOG_CK_RV_AND_RETURN_IF(!operation_state, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::GetOperationState, ToBlob(isolate_credential), session_id, operation_state, &result); return result; } uint32_t ChapsProxyImpl::SetOperationState( const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& operation_state, uint64_t encryption_key_handle, uint64_t authentication_key_handle) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::SetOperationState, ToBlob(isolate_credential), session_id, operation_state, encryption_key_handle, authentication_key_handle, &result); return result; } uint32_t ChapsProxyImpl::Login(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t user_type, const string* pin) { uint32_t result = CKR_GENERAL_ERROR; string tmp_pin; if (pin) tmp_pin = *pin; SendRequestAndWait(&org::chromium::ChapsProxyInterface::Login, ToBlob(isolate_credential), session_id, user_type, (pin == nullptr), tmp_pin, &result); return result; } uint32_t ChapsProxyImpl::Logout(const SecureBlob& isolate_credential, uint64_t session_id) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::Logout, ToBlob(isolate_credential), session_id, &result); return result; } uint32_t ChapsProxyImpl::CreateObject(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& attributes, uint64_t* new_object_handle) { LOG_CK_RV_AND_RETURN_IF(!new_object_handle, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::CreateObject, ToBlob(isolate_credential), session_id, attributes, new_object_handle, &result); return result; } uint32_t ChapsProxyImpl::CopyObject(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t object_handle, const vector<uint8_t>& attributes, uint64_t* new_object_handle) { LOG_CK_RV_AND_RETURN_IF(!new_object_handle, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::CopyObject, ToBlob(isolate_credential), session_id, object_handle, attributes, new_object_handle, &result); return result; } uint32_t ChapsProxyImpl::DestroyObject(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t object_handle) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::DestroyObject, ToBlob(isolate_credential), session_id, object_handle, &result); return result; } uint32_t ChapsProxyImpl::GetObjectSize(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t object_handle, uint64_t* object_size) { LOG_CK_RV_AND_RETURN_IF(!object_size, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::GetObjectSize, ToBlob(isolate_credential), session_id, object_handle, object_size, &result); return result; } uint32_t ChapsProxyImpl::GetAttributeValue(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t object_handle, const vector<uint8_t>& attributes_in, vector<uint8_t>* attributes_out) { LOG_CK_RV_AND_RETURN_IF(!attributes_out, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::GetAttributeValue, ToBlob(isolate_credential), session_id, object_handle, attributes_in, attributes_out, &result); return result; } uint32_t ChapsProxyImpl::SetAttributeValue(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t object_handle, const vector<uint8_t>& attributes) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::SetAttributeValue, ToBlob(isolate_credential), session_id, object_handle, attributes, &result); return result; } uint32_t ChapsProxyImpl::FindObjectsInit(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& attributes) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::FindObjectsInit, ToBlob(isolate_credential), session_id, attributes, &result); return result; } uint32_t ChapsProxyImpl::FindObjects(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t max_object_count, vector<uint64_t>* object_list) { if (!object_list || object_list->size() > 0) LOG_CK_RV_AND_RETURN(CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::FindObjects, ToBlob(isolate_credential), session_id, max_object_count, object_list, &result); return result; } uint32_t ChapsProxyImpl::FindObjectsFinal(const SecureBlob& isolate_credential, uint64_t session_id) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::FindObjectsFinal, ToBlob(isolate_credential), session_id, &result); return result; } uint32_t ChapsProxyImpl::EncryptInit(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t mechanism_type, const vector<uint8_t>& mechanism_parameter, uint64_t key_handle) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::EncryptInit, ToBlob(isolate_credential), session_id, mechanism_type, mechanism_parameter, key_handle, &result); return result; } uint32_t ChapsProxyImpl::Encrypt(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& data_in, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* data_out) { LOG_CK_RV_AND_RETURN_IF(!actual_out_length || !data_out, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::Encrypt, ToBlob(isolate_credential), session_id, data_in, max_out_length, actual_out_length, data_out, &result); return result; } uint32_t ChapsProxyImpl::EncryptUpdate(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& data_in, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* data_out) { LOG_CK_RV_AND_RETURN_IF(!actual_out_length || !data_out, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::EncryptUpdate, ToBlob(isolate_credential), session_id, data_in, max_out_length, actual_out_length, data_out, &result); return result; } uint32_t ChapsProxyImpl::EncryptFinal(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* data_out) { LOG_CK_RV_AND_RETURN_IF(!actual_out_length || !data_out, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::EncryptFinal, ToBlob(isolate_credential), session_id, max_out_length, actual_out_length, data_out, &result); return result; } void ChapsProxyImpl::EncryptCancel(const SecureBlob& isolate_credential, uint64_t session_id) { SendRequestAndWait(&org::chromium::ChapsProxyInterface::EncryptCancel, ToBlob(isolate_credential), session_id); } uint32_t ChapsProxyImpl::DecryptInit(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t mechanism_type, const vector<uint8_t>& mechanism_parameter, uint64_t key_handle) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::DecryptInit, ToBlob(isolate_credential), session_id, mechanism_type, mechanism_parameter, key_handle, &result); return result; } uint32_t ChapsProxyImpl::Decrypt(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& data_in, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* data_out) { LOG_CK_RV_AND_RETURN_IF(!actual_out_length || !data_out, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::Decrypt, ToBlob(isolate_credential), session_id, data_in, max_out_length, actual_out_length, data_out, &result); return result; } uint32_t ChapsProxyImpl::DecryptUpdate(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& data_in, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* data_out) { LOG_CK_RV_AND_RETURN_IF(!actual_out_length || !data_out, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::DecryptUpdate, ToBlob(isolate_credential), session_id, data_in, max_out_length, actual_out_length, data_out, &result); return result; } uint32_t ChapsProxyImpl::DecryptFinal(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* data_out) { LOG_CK_RV_AND_RETURN_IF(!actual_out_length || !data_out, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::DecryptFinal, ToBlob(isolate_credential), session_id, max_out_length, actual_out_length, data_out, &result); return result; } void ChapsProxyImpl::DecryptCancel(const SecureBlob& isolate_credential, uint64_t session_id) { SendRequestAndWait(&org::chromium::ChapsProxyInterface::DecryptCancel, ToBlob(isolate_credential), session_id); } uint32_t ChapsProxyImpl::DigestInit( const SecureBlob& isolate_credential, uint64_t session_id, uint64_t mechanism_type, const vector<uint8_t>& mechanism_parameter) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::DigestInit, ToBlob(isolate_credential), session_id, mechanism_type, mechanism_parameter, &result); return result; } uint32_t ChapsProxyImpl::Digest(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& data_in, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* digest) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::Digest, ToBlob(isolate_credential), session_id, data_in, max_out_length, actual_out_length, digest, &result); return result; } uint32_t ChapsProxyImpl::DigestUpdate(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& data_in) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::DigestUpdate, ToBlob(isolate_credential), session_id, data_in, &result); return result; } uint32_t ChapsProxyImpl::DigestKey(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t key_handle) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::DigestKey, ToBlob(isolate_credential), session_id, key_handle, &result); return result; } uint32_t ChapsProxyImpl::DigestFinal(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* digest) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::DigestFinal, ToBlob(isolate_credential), session_id, max_out_length, actual_out_length, digest, &result); return result; } void ChapsProxyImpl::DigestCancel(const SecureBlob& isolate_credential, uint64_t session_id) { SendRequestAndWait(&org::chromium::ChapsProxyInterface::DigestCancel, ToBlob(isolate_credential), session_id); } uint32_t ChapsProxyImpl::SignInit(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t mechanism_type, const vector<uint8_t>& mechanism_parameter, uint64_t key_handle) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::SignInit, ToBlob(isolate_credential), session_id, mechanism_type, mechanism_parameter, key_handle, &result); return result; } uint32_t ChapsProxyImpl::Sign(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& data, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* signature) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::Sign, ToBlob(isolate_credential), session_id, data, max_out_length, actual_out_length, signature, &result); return result; } uint32_t ChapsProxyImpl::SignUpdate(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& data_part) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::SignUpdate, ToBlob(isolate_credential), session_id, data_part, &result); return result; } uint32_t ChapsProxyImpl::SignFinal(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* signature) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::SignFinal, ToBlob(isolate_credential), session_id, max_out_length, actual_out_length, signature, &result); return result; } void ChapsProxyImpl::SignCancel(const SecureBlob& isolate_credential, uint64_t session_id) { SendRequestAndWait(&org::chromium::ChapsProxyInterface::SignCancel, ToBlob(isolate_credential), session_id); } uint32_t ChapsProxyImpl::SignRecoverInit( const SecureBlob& isolate_credential, uint64_t session_id, uint64_t mechanism_type, const vector<uint8_t>& mechanism_parameter, uint64_t key_handle) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::SignRecoverInit, ToBlob(isolate_credential), session_id, mechanism_type, mechanism_parameter, key_handle, &result); return result; } uint32_t ChapsProxyImpl::SignRecover(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& data, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* signature) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::SignRecover, ToBlob(isolate_credential), session_id, data, max_out_length, actual_out_length, signature, &result); return result; } uint32_t ChapsProxyImpl::VerifyInit(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t mechanism_type, const vector<uint8_t>& mechanism_parameter, uint64_t key_handle) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::VerifyInit, ToBlob(isolate_credential), session_id, mechanism_type, mechanism_parameter, key_handle, &result); return result; } uint32_t ChapsProxyImpl::Verify(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& data, const vector<uint8_t>& signature) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::Verify, ToBlob(isolate_credential), session_id, data, signature, &result); return result; } uint32_t ChapsProxyImpl::VerifyUpdate(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& data_part) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::VerifyUpdate, ToBlob(isolate_credential), session_id, data_part, &result); return result; } uint32_t ChapsProxyImpl::VerifyFinal(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& signature) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::VerifyFinal, ToBlob(isolate_credential), session_id, signature, &result); return result; } void ChapsProxyImpl::VerifyCancel(const SecureBlob& isolate_credential, uint64_t session_id) { SendRequestAndWait(&org::chromium::ChapsProxyInterface::VerifyCancel, ToBlob(isolate_credential), session_id); } uint32_t ChapsProxyImpl::VerifyRecoverInit( const SecureBlob& isolate_credential, uint64_t session_id, uint64_t mechanism_type, const vector<uint8_t>& mechanism_parameter, uint64_t key_handle) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::VerifyRecoverInit, ToBlob(isolate_credential), session_id, mechanism_type, mechanism_parameter, key_handle, &result); return result; } uint32_t ChapsProxyImpl::VerifyRecover(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& signature, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* data) { uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::VerifyRecover, ToBlob(isolate_credential), session_id, signature, max_out_length, actual_out_length, data, &result); return result; } uint32_t ChapsProxyImpl::DigestEncryptUpdate( const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& data_in, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* data_out) { LOG_CK_RV_AND_RETURN_IF(!actual_out_length || !data_out, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::DigestEncryptUpdate, ToBlob(isolate_credential), session_id, data_in, max_out_length, actual_out_length, data_out, &result); return result; } uint32_t ChapsProxyImpl::DecryptDigestUpdate( const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& data_in, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* data_out) { LOG_CK_RV_AND_RETURN_IF(!actual_out_length || !data_out, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::DecryptDigestUpdate, ToBlob(isolate_credential), session_id, data_in, max_out_length, actual_out_length, data_out, &result); return result; } uint32_t ChapsProxyImpl::SignEncryptUpdate(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& data_in, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* data_out) { LOG_CK_RV_AND_RETURN_IF(!actual_out_length || !data_out, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::SignEncryptUpdate, ToBlob(isolate_credential), session_id, data_in, max_out_length, actual_out_length, data_out, &result); return result; } uint32_t ChapsProxyImpl::DecryptVerifyUpdate( const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& data_in, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* data_out) { LOG_CK_RV_AND_RETURN_IF(!actual_out_length || !data_out, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::DecryptVerifyUpdate, ToBlob(isolate_credential), session_id, data_in, max_out_length, actual_out_length, data_out, &result); return result; } uint32_t ChapsProxyImpl::GenerateKey(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t mechanism_type, const vector<uint8_t>& mechanism_parameter, const vector<uint8_t>& attributes, uint64_t* key_handle) { LOG_CK_RV_AND_RETURN_IF(!key_handle, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::GenerateKey, ToBlob(isolate_credential), session_id, mechanism_type, mechanism_parameter, attributes, key_handle, &result); return result; } uint32_t ChapsProxyImpl::GenerateKeyPair( const SecureBlob& isolate_credential, uint64_t session_id, uint64_t mechanism_type, const vector<uint8_t>& mechanism_parameter, const vector<uint8_t>& public_attributes, const vector<uint8_t>& private_attributes, uint64_t* public_key_handle, uint64_t* private_key_handle) { LOG_CK_RV_AND_RETURN_IF(!public_key_handle || !private_key_handle, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::GenerateKeyPair, ToBlob(isolate_credential), session_id, mechanism_type, mechanism_parameter, public_attributes, private_attributes, public_key_handle, private_key_handle, &result); return result; } uint32_t ChapsProxyImpl::WrapKey(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t mechanism_type, const vector<uint8_t>& mechanism_parameter, uint64_t wrapping_key_handle, uint64_t key_handle, uint64_t max_out_length, uint64_t* actual_out_length, vector<uint8_t>* wrapped_key) { LOG_CK_RV_AND_RETURN_IF(!actual_out_length || !wrapped_key, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::WrapKey, ToBlob(isolate_credential), session_id, mechanism_type, mechanism_parameter, wrapping_key_handle, key_handle, max_out_length, actual_out_length, wrapped_key, &result); return result; } uint32_t ChapsProxyImpl::UnwrapKey(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t mechanism_type, const vector<uint8_t>& mechanism_parameter, uint64_t wrapping_key_handle, const vector<uint8_t>& wrapped_key, const vector<uint8_t>& attributes, uint64_t* key_handle) { LOG_CK_RV_AND_RETURN_IF(!key_handle, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::UnwrapKey, ToBlob(isolate_credential), session_id, mechanism_type, mechanism_parameter, wrapping_key_handle, wrapped_key, attributes, key_handle, &result); return result; } uint32_t ChapsProxyImpl::DeriveKey(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t mechanism_type, const vector<uint8_t>& mechanism_parameter, uint64_t base_key_handle, const vector<uint8_t>& attributes, uint64_t* key_handle) { LOG_CK_RV_AND_RETURN_IF(!key_handle, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::DeriveKey, ToBlob(isolate_credential), session_id, mechanism_type, mechanism_parameter, base_key_handle, attributes, key_handle, &result); return result; } uint32_t ChapsProxyImpl::SeedRandom(const SecureBlob& isolate_credential, uint64_t session_id, const vector<uint8_t>& seed) { LOG_CK_RV_AND_RETURN_IF(seed.size() == 0, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::SeedRandom, ToBlob(isolate_credential), session_id, seed, &result); return result; } uint32_t ChapsProxyImpl::GenerateRandom(const SecureBlob& isolate_credential, uint64_t session_id, uint64_t num_bytes, vector<uint8_t>* random_data) { LOG_CK_RV_AND_RETURN_IF(!random_data || num_bytes == 0, CKR_ARGUMENTS_BAD); uint32_t result = CKR_GENERAL_ERROR; SendRequestAndWait(&org::chromium::ChapsProxyInterface::GenerateRandom, ToBlob(isolate_credential), session_id, num_bytes, random_data, &result); return result; } } // namespace chaps
44.21058
80
0.613797
[ "vector" ]
ba9b238be5f331d859c4fb6457c6065d7b81b7e3
2,012
cpp
C++
codeforces/e53/D/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
codeforces/e53/D/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
19
2016-05-04T02:46:31.000Z
2021-11-27T06:18:33.000Z
codeforces/e53/D/main.cpp
Johniel/contests
b692eff913c20e2c1eb4ff0ce3cd4c57900594e0
[ "Unlicense" ]
null
null
null
#include <bits/stdc++.h> #define each(i, c) for (auto& i : c) #define unless(cond) if (!(cond)) using namespace std; typedef long long int lli; typedef unsigned long long ull; typedef complex<double> point; template<typename P, typename Q> ostream& operator << (ostream& os, pair<P, Q> p) { os << "(" << p.first << "," << p.second << ")"; return os; } template<typename P, typename Q> istream& operator >> (istream& is, pair<P, Q>& p) { is >> p.first >> p.second; return is; } template<typename T> ostream& operator << (ostream& os, vector<T> v) { os << "("; each (i, v) os << i << ","; os << ")"; return os; } template<typename T> istream& operator >> (istream& is, vector<T>& v) { each (i, v) is >> i; return is; } template<typename T> inline T setmax(T& a, T b) { return a = std::max(a, b); } template<typename T> inline T setmin(T& a, T b) { return a = std::min(a, b); } template<typename T> class BIT { public: BIT(int n_) { n = n_; bit.resize(n + 1, 0); } void add(int i, T x) { assert(0 <= i); return _add(i + 1, x); } T sum(int i) { T s = 0; while (i > 0) { s += bit[i]; i -= i & -i; } return s; } private: vector<T> bit; int n; void _add(int i, T x) { while (i <= n) { bit[i] += x; i += i & -i; } return ; } }; int main(int argc, char *argv[]) { ios_base::sync_with_stdio(0); cin.tie(0); int n; lli t; while (cin >> n >> t) { vector<lli> a(n); cin >> a; BIT<lli> bit(n); for (int i = 0; i < n; ++i) { bit.add(i, a[i]); } lli x = 0; for (int i = 0; i < n; ++i) { lli y = bit.sum(n); if (y <= t) { x += (t / y) * (n - i); t %= y; } int small = 0; int large = n; while (small + 1 < large) { int mid = (small + large) / 2; if (bit.sum(mid) <= t) small = mid; else large = mid; } bit.add(small, -1 * a[small]); } cout << x << endl; } return 0; }
21.178947
144
0.492048
[ "vector" ]
ba9e88d328eb23ca9d19a08dbb0c27769d282bc3
3,608
cpp
C++
networkit/cpp/generators/DynamicForestFireGenerator.cpp
tsapko3628/networkit
2953c9f30b676f930e301953f00f014c47edcf69
[ "MIT" ]
1
2019-08-15T10:35:07.000Z
2019-08-15T10:35:07.000Z
networkit/cpp/generators/DynamicForestFireGenerator.cpp
tsapko3628/networkit
2953c9f30b676f930e301953f00f014c47edcf69
[ "MIT" ]
null
null
null
networkit/cpp/generators/DynamicForestFireGenerator.cpp
tsapko3628/networkit
2953c9f30b676f930e301953f00f014c47edcf69
[ "MIT" ]
null
null
null
/* * ForestFireGenerator.cpp * * Created on: 17.01.2014 * Author: cls */ #include <networkit/generators/DynamicForestFireGenerator.hpp> #include <networkit/auxiliary/Random.hpp> #include <networkit/auxiliary/Log.hpp> #include <set> #include <unordered_map> #include <queue> namespace NetworKit { typedef std::function<std::vector<node>(node)> neighborFunction; DynamicForestFireGenerator::DynamicForestFireGenerator(double p, bool directed, double r) :p(p), directed(directed), r(r), firstCall(true) { G = Graph(0, false, directed); } std::vector<GraphEvent> DynamicForestFireGenerator::generate(count nSteps) { std::vector<GraphEvent> stream; std::set<node> empty; /* this function creates a new node and connects it to * other nodes according to the forest fire model */ auto connectNewNode = [&]() { //list of nodes that were visited std::unordered_map<node, bool> visited; // nodes which were found but not processed std::queue<node> activeNodes; /* vector of nodes that visited * and the new node will connect to */ std::vector<node> burnedNodes; auto forwardNeighbors = [&](node u) { std::vector<node> validEdges; G.forNeighborsOf(u, [&](node x){ if (! visited[x]) { validEdges.push_back(x); } }); return validEdges; }; auto backwardNeighbors = [&](node u) { std::vector<node> validEdges; G.forInNeighborsOf(u, [&](node, node x){ if (! visited[x]) { validEdges.push_back(x); } }); return validEdges; }; // select "edges" of node u auto selectEdges = [&](node u, double prob, neighborFunction getNeighbors) { /* combine all valid edges (edges to non-visited nodes) * into a vector that we can randomly select one */ std::vector<node> validEdges = getNeighbors(u); std::set<node> edges; while (true) { /* get geometric distribution by burning edges * until first failure */ double q = Aux::Random::real(1.0); if (q > prob || validEdges.empty()) { break; } count index = Aux::Random::integer(validEdges.size() - 1); edges.insert(validEdges[index]); validEdges[index] = validEdges.back(); validEdges.pop_back(); } return edges; }; // select ambassador node node a = none; do { a = Aux::Random::integer(G.upperNodeIdBound()); } while (! G.hasNode(a)); assert (a != none); DEBUG("selected ambassador: ", a); node v = G.addNode(); stream.push_back(GraphEvent(GraphEvent::NODE_ADDITION, v)); DEBUG("created node ", v); visited[a] = true; activeNodes.push(a); burnedNodes.push_back(a); // burn through the graph in a BFS-like fashion while (! activeNodes.empty()) { node w = activeNodes.front(); activeNodes.pop(); std::set<node> edges = selectEdges(w, p, forwardNeighbors);; if (directed) { std::set<node> backwardEdges = selectEdges(w, p*r, backwardNeighbors); edges.insert(backwardEdges.begin(), backwardEdges.end()); } for (node x : edges) { activeNodes.push(x); burnedNodes.push_back(x); visited[x] = true; } } for (node w : burnedNodes) { G.addEdge(v, w); stream.push_back(GraphEvent(GraphEvent::EDGE_ADDITION, v, w)); } }; // initial graph if (firstCall && nSteps > 0) { node s = G.addNode(); stream.push_back(GraphEvent(GraphEvent::NODE_ADDITION, s)); stream.push_back(GraphEvent(GraphEvent::TIME_STEP)); firstCall = false; --nSteps; } for (index step = 0; step < nSteps; ++step) { connectNewNode(); stream.push_back(GraphEvent(GraphEvent::TIME_STEP)); } return stream; } } /* namespace NetworKit */
25.230769
140
0.659922
[ "vector", "model" ]
ba9f6cd753c6bbf6909953e2f178a5071999f296
1,418
tcc
C++
TurboCpp/proj/imgview/jpeglib/jconfig.tcc
vividos/OldStuff
dbfcce086d1101b576d99d25ef051efbd8dd117c
[ "BSD-2-Clause" ]
1
2015-03-26T02:35:13.000Z
2015-03-26T02:35:13.000Z
TurboCpp/proj/imgview/jpeglib/jconfig.tcc
vividos/OldStuff
dbfcce086d1101b576d99d25ef051efbd8dd117c
[ "BSD-2-Clause" ]
null
null
null
TurboCpp/proj/imgview/jpeglib/jconfig.tcc
vividos/OldStuff
dbfcce086d1101b576d99d25ef051efbd8dd117c
[ "BSD-2-Clause" ]
null
null
null
/* jconfig.bcc --- jconfig.h for Borland C (Turbo C) on MS-DOS or OS/2. */ /* see jconfig.txt for explanations */ #define HAVE_PROTOTYPES #define HAVE_UNSIGNED_CHAR #define HAVE_UNSIGNED_SHORT /* #define void char */ /* #define const */ #undef CHAR_IS_UNSIGNED #define HAVE_STDDEF_H #define HAVE_STDLIB_H #undef NEED_BSD_STRINGS #undef NEED_SYS_TYPES_H #ifdef __MSDOS__ #define NEED_FAR_POINTERS /* for small or medium memory model */ #endif #undef NEED_SHORT_EXTERNAL_NAMES #undef INCOMPLETE_TYPES_BROKEN /* this assumes you have -w-stu in CFLAGS */ #ifdef JPEG_INTERNALS #undef RIGHT_SHIFT_IS_UNSIGNED #ifdef __MSDOS__ #define USE_MSDOS_MEMMGR /* Define this if you use jmemdos.c */ #define MAX_ALLOC_CHUNK 65520L /* Maximum request to malloc() */ //#define USE_FMEM /* Borland has _fmemcpy() and _fmemset() */ #endif #endif /* JPEG_INTERNALS */ #ifdef JPEG_CJPEG_DJPEG #define BMP_SUPPORTED /* BMP image file format */ #define GIF_SUPPORTED /* GIF image file format */ #define PPM_SUPPORTED /* PBMPLUS PPM/PGM image file format */ #undef RLE_SUPPORTED /* Utah RLE image file format */ #define TARGA_SUPPORTED /* Targa image file format */ #define TWO_FILE_COMMANDLINE #define USE_SETMODE /* Borland has setmode() */ #ifdef __MSDOS__ #define NEED_SIGNAL_CATCHER /* Define this if you use jmemdos.c */ #endif #undef DONT_USE_B_MODE #undef PROGRESS_REPORT /* optional */ #endif /* JPEG_CJPEG_DJPEG */
28.938776
75
0.75811
[ "model" ]
baa02501fd0852eb09315d122ce9bac6f0348127
8,333
cpp
C++
src/Solid.cpp
tomtix/display3r
00c5d7be1b2bea685c7df053f0333bb6828d48f8
[ "MIT" ]
null
null
null
src/Solid.cpp
tomtix/display3r
00c5d7be1b2bea685c7df053f0333bb6828d48f8
[ "MIT" ]
null
null
null
src/Solid.cpp
tomtix/display3r
00c5d7be1b2bea685c7df053f0333bb6828d48f8
[ "MIT" ]
null
null
null
#include <iostream> #include <sstream> #include <locale> #include <boost/algorithm/string.hpp> #include "display3r/Solid.hpp" #include "display3r/Exception.hpp" #include "display3r/Renderer.hpp" using namespace std; using namespace display3r; namespace display3r { static inline double strtod(string const &s) { istringstream istr(s); double d; istr.imbue(locale("C")); istr >> d; return d; } static inline int atoi(string const &s) { return ::atoi(s.c_str()); } }; // end namespace display3r void Solid::ParseVertex(vector<string> const &s, vector<vec3> &vertex) { vec3 v; if (s.size() != 4) throw exception("invalid vertex"); v.x = strtod(s[1]); v.y = strtod(s[2]); v.z = strtod(s[3]); vertex.push_back(v); } void Solid::ParseNormal(vector<string> const &s, vector<vec3> &normal) { vec3 n; if (s.size() != 4) throw exception("invalid normal"); n.x = strtod(s[1]); n.y = strtod(s[2]); n.z = strtod(s[3]); normal.push_back(n); } void Solid::ParseTexCoord(vector<string> const &s, vector<vec2> &texcoord) { vec2 t; if (s.size() != 3) throw exception("invalid texcoord"); t.x = strtod(s[1]); t.y = strtod(s[2]); t.y = 1 - t.y; texcoord.push_back(t); } Vertex Solid::ParseVertexIndex(string rep, vector<vec3>const &vertex, vector<vec3>const &normal, vector<vec2>const &texcoord) { Vertex v; vector<string> s; boost::trim(rep); boost::split(s, rep, boost::is_any_of("/")); if (!s.size() || s.size() > 3) throw exception("bad face element"); v.position = vertex[atoi(s[0])-1]; if (s.size() >= 2 && s[1] != "") v.texcoord = texcoord[atoi(s[1])-1]; if (s.size() == 3) v.normal = normal[atoi(s[2])-1]; return v; } void Solid::ParseFace(vector<string> const &s, vector<vec3>const &v/*ertex*/, vector<vec3>const &n/*ormal*/, vector<vec2>const &t/*excoord*/) { if (s.size() < 4) throw exception("invalid face"); Face f(ParseVertexIndex(s[1], v, n, t), ParseVertexIndex(s[2], v, n, t), ParseVertexIndex(s[3], v, n, t)); m_faces.push_back(f); // triangle fan if more than 3 points: Vertex last = f.C; for (unsigned i = 4; i < s.size(); ++i) { Face g(f.A, last, ParseVertexIndex(s[i], v, n, t)); last = g.C; m_faces.push_back(g); } } void Solid::LoadOBJ(ifstream &file) { m_faces.clear(); vector<vec3> normals; vector<vec3> vertex; vector<vec2> texcoords; string line; int line_count = 1; while (getline(file, line)) { boost::trim(line); vector<string> s; boost::split(s, line, boost::is_any_of(" ")); string const &type = s[0]; try { if (type == "v") ParseVertex(s, vertex); else if (type == "vn") ParseNormal(s, normals); else if (type == "vt") ParseTexCoord(s, texcoords); else if (type == "f") ParseFace(s, vertex, normals, texcoords); else if (type == "o" && s.size() >= 2) m_name = s[1]; } catch (exception &e) { throw exception( string(e.what())+ " line "+to_string(line_count)); } ++ line_count; } } Solid::Solid(string filepath, Texture *texture): m_texture(texture), m_name("Unnamed") { ifstream f(filepath); if (!f.is_open()) throw exception(filepath+": "+strerror(errno)); LoadOBJ(f); cout << "Object " << filepath <<":"<<m_name<< " LOADED." << endl; cout << "texture pointer" << texture << endl; f.close(); } void Solid::DrawHandler(Renderer &renderer) { renderer.BindTexture(m_texture); for (auto &f : m_faces) renderer.DrawFace(f); renderer.BindTexture(NULL); // unbind texture } Solid::Solid(Equation const&, Texture*) { throw display3r::exception("equation loading not implemented, sorry"); } // Solid::Solid(Equation &eq, string texpath) // { // float minS, maxS, minT, maxT; // int precisionS, precisionT; // char x[MAXLENGTH]; // char y[MAXLENGTH]; // char z[MAXLENGTH]; // if (!initEquation(&minS, &maxS, &precisionS, // &minT, &maxT, &precisionT, // x, y, z, MAXLENGTH, eqName)) { // fprintf(stderr, "Error loading equation\n"); // return NULL; // } else // printf("Equation successfully initialized\n"); // Solid *solid = malloc(sizeof(Solid)); // int p, f = 0; // float s = minS, t = minT; // float ds = (maxS - minS) / (precisionS - 1); // float dt = (maxT - minT) / (precisionT - 1); // solid->numVertices = precisionS * precisionT; // solid->numNormals = solid->numVertices; // solid->numCoords = 4; // solid->numFaces = 2 * (precisionS - 1) * (precisionT - 1); // solid->vertices = malloc(solid->numVertices * sizeof(Point)); // solid->normals = malloc(solid->numNormals * sizeof(Point)); // solid->coords = malloc(solid->numCoords * sizeof(Texture)); // solid->faces = malloc(solid->numFaces * sizeof(Face)); // setTexture(&solid->coords[0], 0., 0.); // setTexture(&solid->coords[1], 0., 1.); // setTexture(&solid->coords[2], 1., 0.); // setTexture(&solid->coords[3], 1., 1.); // if ((solid->texture = SDL_LoadBMP(texpath.c_str())) == NULL) // fprintf(stderr, "%s\n", SDL_GetError()); // if (solid->numVertices > 0) // getValueFromEquation(x, y, z, s, t, &solid->vertices[0]); // for (p = 0; p < solid->numVertices; p++) { // Point *A; // Point *B; // Point *O = &solid->vertices[p]; // Point *normal = &solid->normals[p]; // Point u; // Point v; // printf("%d => s: %f, t: %f\n", p, s, t); // printf("%d => x: %f, y: %f, z: %f\n", p, O->x, O->y, O->z); // if (p == solid->numVertices - 1) { // north-east // A = &solid->vertices[p - 1]; // B = &solid->vertices[p - precisionS]; // } else if (p % precisionS == precisionS - 1) { // east // A = &solid->vertices[p + precisionS]; // B = &solid->vertices[p - 1]; // getValueFromEquation(x, y, z, s, t + dt, A); // s = minS; // t += dt; // } else if (p >= (solid->numVertices - precisionS)) { // north // A = &solid->vertices[p - precisionS]; // B = &solid->vertices[p + 1]; // s += ds; // } else if (p < precisionS) { // south // A = &solid->vertices[p + 1]; // B = &solid->vertices[p + precisionS]; // getValueFromEquation(x, y, z, s + ds, t, A); // getValueFromEquation(x, y, z, s, t + dt, B); // s += ds; // } else { // elsewhere // A = &solid->vertices[p + 1]; // B = &solid->vertices[p + precisionS]; // getValueFromEquation(x, y, z, s, t + dt, B); // s += ds; // } // diffPoint(A, O, &u); // diffPoint(B, O, &v); // pointProduct(&u, &v, normal); // normalizePoint(normal, normal); // } // p = 0; // while (f < solid->numFaces) { // if (p % precisionS != precisionS - 1) { // solid->faces[f].vertices[0].point = p; // solid->faces[f].vertices[1].point = p + 1; // solid->faces[f].vertices[2].point = p + precisionS; // solid->faces[f].vertices[0].normal = p; // solid->faces[f].vertices[1].normal = p + 1; // solid->faces[f].vertices[2].normal = p + precisionS; // solid->faces[f].vertices[0].coord = 1; // solid->faces[f].vertices[1].coord = 3; // solid->faces[f].vertices[2].coord = 0; // f++; // solid->faces[f].vertices[0].point = p + precisionS; // solid->faces[f].vertices[1].point = p + 1; // solid->faces[f].vertices[2].point = p + 1 + precisionS; // solid->faces[f].vertices[0].normal = p + precisionS; // solid->faces[f].vertices[1].normal = p + 1; // solid->faces[f].vertices[2].normal = p + 1 + precisionS; // solid->faces[f].vertices[0].coord = 0; // solid->faces[f].vertices[1].coord = 3; // solid->faces[f].vertices[2].coord = 2; // f++; // } // p++; // } // solid->computeOrigin(); // freeEquation(); // printf("Equation successfully loaded\n"); // return solid; // }
28.152027
74
0.539662
[ "object", "vector", "solid" ]
baa539457f74c9badda9783c45ae24d2bce5075a
3,082
cpp
C++
src/fvrequiregrid.cpp
szmurlor/fiver
083251420eb934d860c99dcf1eb07ae5b8ba7e8c
[ "Apache-2.0" ]
null
null
null
src/fvrequiregrid.cpp
szmurlor/fiver
083251420eb934d860c99dcf1eb07ae5b8ba7e8c
[ "Apache-2.0" ]
null
null
null
src/fvrequiregrid.cpp
szmurlor/fiver
083251420eb934d860c99dcf1eb07ae5b8ba7e8c
[ "Apache-2.0" ]
null
null
null
/***************************************************************************** * Copyright (C) 2006 Robert Szmurlo <robert@iem.pw.edu.pl> * * * * 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 "fvrequiregrid.h" #include <QtDebug> FVRequireGrid::FVRequireGrid() { } FVRequireGrid::~FVRequireGrid() { } Grid * FVRequireGrid::getGrid( FVObject * fvo, FVObject * alternateObject ) { FVGridInterface * fvi = 0; if (fvo != 0) fvi = (FVGridInterface*) fvo->getInterface( QString("FVGridInterface") ); else { if (alternateObject != 0) fvi = (FVGridInterface*) alternateObject->getInterface( QString("FVGridInterface") ); } if (fvi != 0) return fvi->getGrid(); else { qDebug() << "FVRequireGrid: Unable to get grid from " << fvo->classType() << "!"; return 0; } } dolfin::Mesh * FVRequireGrid::getMesh( FVObject * fvo, FVObject * alternateObject ) { FVGridInterface * fvi = 0; if (fvo != 0) fvi = (FVGridInterface*) fvo->getInterface( QString("FVGridInterface") ); else { if (alternateObject != 0) fvi = (FVGridInterface*) alternateObject->getInterface( QString("FVGridInterface") ); } if (fvi != 0) return fvi->getMesh(); else { qDebug() << "FVRequireGrid: Unable to get mesh from " << fvo->classType() << "!"; return 0; } } dolfin::BoundaryMesh * FVRequireGrid::getBoundaryMesh( FVObject * fvo, FVObject * alternateObject ) { FVGridInterface * fvi = 0; if (fvo != 0) fvi = (FVGridInterface*) fvo->getInterface( QString("FVBoundaryMeshInterface") ); else { if (alternateObject != 0) fvi = (FVGridInterface*) alternateObject->getInterface( QString("FVBoundaryMeshInterface") ); } if (fvi != 0) return fvi->getBoundaryMesh(); else { qDebug() << "FVRequireGrid: Unable to get boundary mesh from " << fvo->classType() << "!"; return 0; } }
37.13253
117
0.498378
[ "mesh" ]
baa55cb88fdfcb0284ef5ff03678d42ab4156ad8
66,693
cpp
C++
src/qt/qtbase/src/widgets/dialogs/qfilesystemmodel.cpp
chihlee/phantomjs
644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/src/widgets/dialogs/qfilesystemmodel.cpp
chihlee/phantomjs
644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c
[ "BSD-3-Clause" ]
null
null
null
src/qt/qtbase/src/widgets/dialogs/qfilesystemmodel.cpp
chihlee/phantomjs
644e0b3a6c9c16bcc6f7ce2c24274bf7d764f53c
[ "BSD-3-Clause" ]
null
null
null
/**************************************************************************** ** ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies). ** Contact: http://www.qt-project.org/legal ** ** This file is part of the QtWidgets module of the Qt Toolkit. ** ** $QT_BEGIN_LICENSE:LGPL21$ ** Commercial License Usage ** Licensees holding valid commercial Qt licenses may use this file in ** accordance with the commercial license agreement provided with the ** Software or, alternatively, in accordance with the terms contained in ** a written agreement between you and Digia. For licensing terms and ** conditions see http://qt.digia.com/licensing. For further information ** use the contact form at http://qt.digia.com/contact-us. ** ** GNU Lesser General Public License Usage ** Alternatively, this file may be used under the terms of the GNU Lesser ** General Public License version 2.1 or version 3 as published by the Free ** Software Foundation and appearing in the file LICENSE.LGPLv21 and ** LICENSE.LGPLv3 included in the packaging of this file. Please review the ** following information to ensure the GNU Lesser General Public License ** requirements will be met: https://www.gnu.org/licenses/lgpl.html and ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html. ** ** In addition, as a special exception, Digia gives you certain additional ** rights. These rights are described in the Digia Qt LGPL Exception ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package. ** ** $QT_END_LICENSE$ ** ****************************************************************************/ #include "qfilesystemmodel_p.h" #include "qfilesystemmodel.h" #include <qlocale.h> #include <qmimedata.h> #include <qurl.h> #include <qdebug.h> #include <qmessagebox.h> #include <qapplication.h> #include <algorithm> #ifdef Q_OS_WIN # include <QtCore/QVarLengthArray> # include <qt_windows.h> #endif QT_BEGIN_NAMESPACE #ifndef QT_NO_FILESYSTEMMODEL /*! \enum QFileSystemModel::Roles \value FileIconRole \value FilePathRole \value FileNameRole \value FilePermissions */ /*! \class QFileSystemModel \since 4.4 \brief The QFileSystemModel class provides a data model for the local filesystem. \ingroup model-view \inmodule QtWidgets This class provides access to the local filesystem, providing functions for renaming and removing files and directories, and for creating new directories. In the simplest case, it can be used with a suitable display widget as part of a browser or filter. QFileSystemModel can be accessed using the standard interface provided by QAbstractItemModel, but it also provides some convenience functions that are specific to a directory model. The fileInfo(), isDir(), fileName() and filePath() functions provide information about the underlying files and directories related to items in the model. Directories can be created and removed using mkdir(), rmdir(). \note QFileSystemModel requires an instance of a GUI application. \section1 Example Usage A directory model that displays the contents of a default directory is usually constructed with a parent object: \snippet shareddirmodel/main.cpp 2 A tree view can be used to display the contents of the model \snippet shareddirmodel/main.cpp 4 and the contents of a particular directory can be displayed by setting the tree view's root index: \snippet shareddirmodel/main.cpp 7 The view's root index can be used to control how much of a hierarchical model is displayed. QFileSystemModel provides a convenience function that returns a suitable model index for a path to a directory within the model. \section1 Caching and Performance QFileSystemModel will not fetch any files or directories until setRootPath() is called. This will prevent any unnecessary querying on the file system until that point such as listing the drives on Windows. Unlike QDirModel, QFileSystemModel uses a separate thread to populate itself so it will not cause the main thread to hang as the file system is being queried. Calls to rowCount() will return 0 until the model populates a directory. QFileSystemModel keeps a cache with file information. The cache is automatically kept up to date using the QFileSystemWatcher. \sa {Model Classes} */ /*! \fn bool QFileSystemModel::rmdir(const QModelIndex &index) Removes the directory corresponding to the model item \a index in the file system model and \b{deletes the corresponding directory from the file system}, returning true if successful. If the directory cannot be removed, false is returned. \warning This function deletes directories from the file system; it does \b{not} move them to a location where they can be recovered. \sa remove() */ /*! \fn QIcon QFileSystemModel::fileName(const QModelIndex &index) const Returns the file name for the item stored in the model under the given \a index. */ /*! \fn QIcon QFileSystemModel::fileIcon(const QModelIndex &index) const Returns the icon for the item stored in the model under the given \a index. */ /*! \fn QFileInfo QFileSystemModel::fileInfo(const QModelIndex &index) const Returns the QFileInfo for the item stored in the model under the given \a index. */ /*! \fn void QFileSystemModel::rootPathChanged(const QString &newPath); This signal is emitted whenever the root path has been changed to a \a newPath. */ /*! \fn void QFileSystemModel::fileRenamed(const QString &path, const QString &oldName, const QString &newName) This signal is emitted whenever a file with the \a oldName is successfully renamed to \a newName. The file is located in in the directory \a path. */ /*! \since 4.7 \fn void QFileSystemModel::directoryLoaded(const QString &path) This signal is emitted when the gatherer thread has finished to load the \a path. */ /*! \fn bool QFileSystemModel::remove(const QModelIndex &index) Removes the model item \a index from the file system model and \b{deletes the corresponding file from the file system}, returning true if successful. If the item cannot be removed, false is returned. \warning This function deletes files from the file system; it does \b{not} move them to a location where they can be recovered. \sa rmdir() */ bool QFileSystemModel::remove(const QModelIndex &aindex) { const QString path = filePath(aindex); #ifndef QT_NO_FILESYSTEMWATCHER QFileSystemModelPrivate * d = const_cast<QFileSystemModelPrivate*>(d_func()); d->fileInfoGatherer.removePath(path); #endif if (QFileInfo(path).isFile()) return QFile::remove(path); return QDir(path).removeRecursively(); } /*! Constructs a file system model with the given \a parent. */ QFileSystemModel::QFileSystemModel(QObject *parent) : QAbstractItemModel(*new QFileSystemModelPrivate, parent) { Q_D(QFileSystemModel); d->init(); } /*! \internal */ QFileSystemModel::QFileSystemModel(QFileSystemModelPrivate &dd, QObject *parent) : QAbstractItemModel(dd, parent) { Q_D(QFileSystemModel); d->init(); } /*! Destroys this file system model. */ QFileSystemModel::~QFileSystemModel() { } /*! \reimp */ QModelIndex QFileSystemModel::index(int row, int column, const QModelIndex &parent) const { Q_D(const QFileSystemModel); if (row < 0 || column < 0 || row >= rowCount(parent) || column >= columnCount(parent)) return QModelIndex(); // get the parent node QFileSystemModelPrivate::QFileSystemNode *parentNode = (d->indexValid(parent) ? d->node(parent) : const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&d->root)); Q_ASSERT(parentNode); // now get the internal pointer for the index QString childName = parentNode->visibleChildren[d->translateVisibleLocation(parentNode, row)]; const QFileSystemModelPrivate::QFileSystemNode *indexNode = parentNode->children.value(childName); Q_ASSERT(indexNode); return createIndex(row, column, const_cast<QFileSystemModelPrivate::QFileSystemNode*>(indexNode)); } /*! \overload Returns the model item index for the given \a path and \a column. */ QModelIndex QFileSystemModel::index(const QString &path, int column) const { Q_D(const QFileSystemModel); QFileSystemModelPrivate::QFileSystemNode *node = d->node(path, false); QModelIndex idx = d->index(node); if (idx.column() != column) idx = idx.sibling(idx.row(), column); return idx; } /*! \internal Return the QFileSystemNode that goes to index. */ QFileSystemModelPrivate::QFileSystemNode *QFileSystemModelPrivate::node(const QModelIndex &index) const { if (!index.isValid()) return const_cast<QFileSystemNode*>(&root); QFileSystemModelPrivate::QFileSystemNode *indexNode = static_cast<QFileSystemModelPrivate::QFileSystemNode*>(index.internalPointer()); Q_ASSERT(indexNode); return indexNode; } #ifdef Q_OS_WIN32 static QString qt_GetLongPathName(const QString &strShortPath) { if (strShortPath.isEmpty() || strShortPath == QLatin1String(".") || strShortPath == QLatin1String("..")) return strShortPath; if (strShortPath.length() == 2 && strShortPath.endsWith(QLatin1Char(':'))) return strShortPath.toUpper(); const QString absPath = QDir(strShortPath).absolutePath(); if (absPath.startsWith(QLatin1String("//")) || absPath.startsWith(QLatin1String("\\\\"))) // unc return QDir::fromNativeSeparators(absPath); if (absPath.startsWith(QLatin1Char('/'))) return QString(); const QString inputString = QLatin1String("\\\\?\\") + QDir::toNativeSeparators(absPath); QVarLengthArray<TCHAR, MAX_PATH> buffer(MAX_PATH); DWORD result = ::GetLongPathName((wchar_t*)inputString.utf16(), buffer.data(), buffer.size()); if (result > DWORD(buffer.size())) { buffer.resize(result); result = ::GetLongPathName((wchar_t*)inputString.utf16(), buffer.data(), buffer.size()); } if (result > 4) { QString longPath = QString::fromWCharArray(buffer.data() + 4); // ignoring prefix longPath[0] = longPath.at(0).toUpper(); // capital drive letters return QDir::fromNativeSeparators(longPath); } else { return QDir::fromNativeSeparators(strShortPath); } } #endif /*! \internal Given a path return the matching QFileSystemNode or &root if invalid */ QFileSystemModelPrivate::QFileSystemNode *QFileSystemModelPrivate::node(const QString &path, bool fetch) const { Q_Q(const QFileSystemModel); Q_UNUSED(q); if (path.isEmpty() || path == myComputer() || path.startsWith(QLatin1Char(':'))) return const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&root); // Construct the nodes up to the new root path if they need to be built QString absolutePath; #ifdef Q_OS_WIN32 QString longPath = qt_GetLongPathName(path); #else QString longPath = path; #endif if (longPath == rootDir.path()) absolutePath = rootDir.absolutePath(); else absolutePath = QDir(longPath).absolutePath(); // ### TODO can we use bool QAbstractFileEngine::caseSensitive() const? QStringList pathElements = absolutePath.split(QLatin1Char('/'), QString::SkipEmptyParts); if ((pathElements.isEmpty()) #if !defined(Q_OS_WIN) || defined(Q_OS_WINCE) && QDir::fromNativeSeparators(longPath) != QLatin1String("/") #endif ) return const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&root); QModelIndex index = QModelIndex(); // start with "My Computer" #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) if (absolutePath.startsWith(QLatin1String("//"))) { // UNC path QString host = QLatin1String("\\\\") + pathElements.first(); if (absolutePath == QDir::fromNativeSeparators(host)) absolutePath.append(QLatin1Char('/')); if (longPath.endsWith(QLatin1Char('/')) && !absolutePath.endsWith(QLatin1Char('/'))) absolutePath.append(QLatin1Char('/')); int r = 0; QFileSystemModelPrivate::QFileSystemNode *rootNode = const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&root); if (!root.children.contains(host.toLower())) { if (pathElements.count() == 1 && !absolutePath.endsWith(QLatin1Char('/'))) return rootNode; QFileInfo info(host); if (!info.exists()) return rootNode; QFileSystemModelPrivate *p = const_cast<QFileSystemModelPrivate*>(this); p->addNode(rootNode, host,info); p->addVisibleFiles(rootNode, QStringList(host)); } r = rootNode->visibleLocation(host); r = translateVisibleLocation(rootNode, r); index = q->index(r, 0, QModelIndex()); pathElements.pop_front(); } else #endif #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) { if (!pathElements.at(0).contains(QLatin1String(":"))) { QString rootPath = QDir(longPath).rootPath(); pathElements.prepend(rootPath); } if (pathElements.at(0).endsWith(QLatin1Char('/'))) pathElements[0].chop(1); } #else // add the "/" item, since it is a valid path element on Unix if (absolutePath[0] == QLatin1Char('/')) pathElements.prepend(QLatin1String("/")); #endif QFileSystemModelPrivate::QFileSystemNode *parent = node(index); for (int i = 0; i < pathElements.count(); ++i) { QString element = pathElements.at(i); #ifdef Q_OS_WIN // On Windows, "filename " and "filename" are equivalent and // "filename . " and "filename" are equivalent // "filename......." and "filename" are equivalent Task #133928 // whereas "filename .txt" is still "filename .txt" // If after stripping the characters there is nothing left then we // just return the parent directory as it is assumed that the path // is referring to the parent while (element.endsWith(QLatin1Char('.')) || element.endsWith(QLatin1Char(' '))) element.chop(1); // Only filenames that can't possibly exist will be end up being empty if (element.isEmpty()) return parent; #endif bool alreadyExisted = parent->children.contains(element); // we couldn't find the path element, we create a new node since we // _know_ that the path is valid if (alreadyExisted) { if ((parent->children.count() == 0) || (parent->caseSensitive() && parent->children.value(element)->fileName != element) || (!parent->caseSensitive() && parent->children.value(element)->fileName.toLower() != element.toLower())) alreadyExisted = false; } QFileSystemModelPrivate::QFileSystemNode *node; if (!alreadyExisted) { // Someone might call ::index("file://cookie/monster/doesn't/like/veggies"), // a path that doesn't exists, I.E. don't blindly create directories. QFileInfo info(absolutePath); if (!info.exists()) return const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&root); QFileSystemModelPrivate *p = const_cast<QFileSystemModelPrivate*>(this); node = p->addNode(parent, element,info); #ifndef QT_NO_FILESYSTEMWATCHER node->populate(fileInfoGatherer.getInfo(info)); #endif } else { node = parent->children.value(element); } Q_ASSERT(node); if (!node->isVisible) { // It has been filtered out if (alreadyExisted && node->hasInformation() && !fetch) return const_cast<QFileSystemModelPrivate::QFileSystemNode*>(&root); QFileSystemModelPrivate *p = const_cast<QFileSystemModelPrivate*>(this); p->addVisibleFiles(parent, QStringList(element)); if (!p->bypassFilters.contains(node)) p->bypassFilters[node] = 1; QString dir = q->filePath(this->index(parent)); if (!node->hasInformation() && fetch) { Fetching f; f.dir = dir; f.file = element; f.node = node; p->toFetch.append(f); p->fetchingTimer.start(0, const_cast<QFileSystemModel*>(q)); } } parent = node; } return parent; } /*! \reimp */ void QFileSystemModel::timerEvent(QTimerEvent *event) { Q_D(QFileSystemModel); if (event->timerId() == d->fetchingTimer.timerId()) { d->fetchingTimer.stop(); #ifndef QT_NO_FILESYSTEMWATCHER for (int i = 0; i < d->toFetch.count(); ++i) { const QFileSystemModelPrivate::QFileSystemNode *node = d->toFetch.at(i).node; if (!node->hasInformation()) { d->fileInfoGatherer.fetchExtendedInformation(d->toFetch.at(i).dir, QStringList(d->toFetch.at(i).file)); } else { // qDebug() << "yah!, you saved a little gerbil soul"; } } #endif d->toFetch.clear(); } } /*! Returns \c true if the model item \a index represents a directory; otherwise returns \c false. */ bool QFileSystemModel::isDir(const QModelIndex &index) const { // This function is for public usage only because it could create a file info Q_D(const QFileSystemModel); if (!index.isValid()) return true; QFileSystemModelPrivate::QFileSystemNode *n = d->node(index); if (n->hasInformation()) return n->isDir(); return fileInfo(index).isDir(); } /*! Returns the size in bytes of \a index. If the file does not exist, 0 is returned. */ qint64 QFileSystemModel::size(const QModelIndex &index) const { Q_D(const QFileSystemModel); if (!index.isValid()) return 0; return d->node(index)->size(); } /*! Returns the type of file \a index such as "Directory" or "JPEG file". */ QString QFileSystemModel::type(const QModelIndex &index) const { Q_D(const QFileSystemModel); if (!index.isValid()) return QString(); return d->node(index)->type(); } /*! Returns the date and time when \a index was last modified. */ QDateTime QFileSystemModel::lastModified(const QModelIndex &index) const { Q_D(const QFileSystemModel); if (!index.isValid()) return QDateTime(); return d->node(index)->lastModified(); } /*! \reimp */ QModelIndex QFileSystemModel::parent(const QModelIndex &index) const { Q_D(const QFileSystemModel); if (!d->indexValid(index)) return QModelIndex(); QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(index); Q_ASSERT(indexNode != 0); QFileSystemModelPrivate::QFileSystemNode *parentNode = (indexNode ? indexNode->parent : 0); if (parentNode == 0 || parentNode == &d->root) return QModelIndex(); // get the parent's row QFileSystemModelPrivate::QFileSystemNode *grandParentNode = parentNode->parent; Q_ASSERT(grandParentNode->children.contains(parentNode->fileName)); int visualRow = d->translateVisibleLocation(grandParentNode, grandParentNode->visibleLocation(grandParentNode->children.value(parentNode->fileName)->fileName)); if (visualRow == -1) return QModelIndex(); return createIndex(visualRow, 0, parentNode); } /* \internal return the index for node */ QModelIndex QFileSystemModelPrivate::index(const QFileSystemModelPrivate::QFileSystemNode *node) const { Q_Q(const QFileSystemModel); QFileSystemModelPrivate::QFileSystemNode *parentNode = (node ? node->parent : 0); if (node == &root || !parentNode) return QModelIndex(); // get the parent's row Q_ASSERT(node); if (!node->isVisible) return QModelIndex(); int visualRow = translateVisibleLocation(parentNode, parentNode->visibleLocation(node->fileName)); return q->createIndex(visualRow, 0, const_cast<QFileSystemNode*>(node)); } /*! \reimp */ bool QFileSystemModel::hasChildren(const QModelIndex &parent) const { Q_D(const QFileSystemModel); if (parent.column() > 0) return false; if (!parent.isValid()) // drives return true; const QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(parent); Q_ASSERT(indexNode); return (indexNode->isDir()); } /*! \reimp */ bool QFileSystemModel::canFetchMore(const QModelIndex &parent) const { Q_D(const QFileSystemModel); const QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(parent); return (!indexNode->populatedChildren); } /*! \reimp */ void QFileSystemModel::fetchMore(const QModelIndex &parent) { Q_D(QFileSystemModel); if (!d->setRootPath) return; QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(parent); if (indexNode->populatedChildren) return; indexNode->populatedChildren = true; #ifndef QT_NO_FILESYSTEMWATCHER d->fileInfoGatherer.list(filePath(parent)); #endif } /*! \reimp */ int QFileSystemModel::rowCount(const QModelIndex &parent) const { Q_D(const QFileSystemModel); if (parent.column() > 0) return 0; if (!parent.isValid()) return d->root.visibleChildren.count(); const QFileSystemModelPrivate::QFileSystemNode *parentNode = d->node(parent); return parentNode->visibleChildren.count(); } /*! \reimp */ int QFileSystemModel::columnCount(const QModelIndex &parent) const { return (parent.column() > 0) ? 0 : 4; } /*! Returns the data stored under the given \a role for the item "My Computer". \sa Qt::ItemDataRole */ QVariant QFileSystemModel::myComputer(int role) const { Q_D(const QFileSystemModel); switch (role) { case Qt::DisplayRole: return d->myComputer(); #ifndef QT_NO_FILESYSTEMWATCHER case Qt::DecorationRole: return d->fileInfoGatherer.iconProvider()->icon(QFileIconProvider::Computer); #endif } return QVariant(); } /*! \reimp */ QVariant QFileSystemModel::data(const QModelIndex &index, int role) const { Q_D(const QFileSystemModel); if (!index.isValid() || index.model() != this) return QVariant(); switch (role) { case Qt::EditRole: case Qt::DisplayRole: switch (index.column()) { case 0: return d->displayName(index); case 1: return d->size(index); case 2: return d->type(index); case 3: return d->time(index); default: qWarning("data: invalid display value column %d", index.column()); break; } break; case FilePathRole: return filePath(index); case FileNameRole: return d->name(index); case Qt::DecorationRole: if (index.column() == 0) { QIcon icon = d->icon(index); #ifndef QT_NO_FILESYSTEMWATCHER if (icon.isNull()) { if (d->node(index)->isDir()) icon = d->fileInfoGatherer.iconProvider()->icon(QFileIconProvider::Folder); else icon = d->fileInfoGatherer.iconProvider()->icon(QFileIconProvider::File); } #endif // QT_NO_FILESYSTEMWATCHER return icon; } break; case Qt::TextAlignmentRole: if (index.column() == 1) return Qt::AlignRight; break; case FilePermissions: int p = permissions(index); return p; } return QVariant(); } /*! \internal */ QString QFileSystemModelPrivate::size(const QModelIndex &index) const { if (!index.isValid()) return QString(); const QFileSystemNode *n = node(index); if (n->isDir()) { #ifdef Q_OS_MAC return QLatin1String("--"); #else return QLatin1String(""); #endif // Windows - "" // OS X - "--" // Konqueror - "4 KB" // Nautilus - "9 items" (the number of children) } return size(n->size()); } QString QFileSystemModelPrivate::size(qint64 bytes) { // According to the Si standard KB is 1000 bytes, KiB is 1024 // but on windows sizes are calculated by dividing by 1024 so we do what they do. const qint64 kb = 1024; const qint64 mb = 1024 * kb; const qint64 gb = 1024 * mb; const qint64 tb = 1024 * gb; if (bytes >= tb) return QFileSystemModel::tr("%1 TB").arg(QLocale().toString(qreal(bytes) / tb, 'f', 3)); if (bytes >= gb) return QFileSystemModel::tr("%1 GB").arg(QLocale().toString(qreal(bytes) / gb, 'f', 2)); if (bytes >= mb) return QFileSystemModel::tr("%1 MB").arg(QLocale().toString(qreal(bytes) / mb, 'f', 1)); if (bytes >= kb) return QFileSystemModel::tr("%1 KB").arg(QLocale().toString(bytes / kb)); return QFileSystemModel::tr("%1 bytes").arg(QLocale().toString(bytes)); } /*! \internal */ QString QFileSystemModelPrivate::time(const QModelIndex &index) const { if (!index.isValid()) return QString(); #ifndef QT_NO_DATESTRING return node(index)->lastModified().toString(Qt::SystemLocaleDate); #else Q_UNUSED(index); return QString(); #endif } /* \internal */ QString QFileSystemModelPrivate::type(const QModelIndex &index) const { if (!index.isValid()) return QString(); return node(index)->type(); } /*! \internal */ QString QFileSystemModelPrivate::name(const QModelIndex &index) const { if (!index.isValid()) return QString(); QFileSystemNode *dirNode = node(index); if ( #ifndef QT_NO_FILESYSTEMWATCHER fileInfoGatherer.resolveSymlinks() && #endif !resolvedSymLinks.isEmpty() && dirNode->isSymLink(/* ignoreNtfsSymLinks = */ true)) { QString fullPath = QDir::fromNativeSeparators(filePath(index)); if (resolvedSymLinks.contains(fullPath)) return resolvedSymLinks[fullPath]; } return dirNode->fileName; } /*! \internal */ QString QFileSystemModelPrivate::displayName(const QModelIndex &index) const { #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) QFileSystemNode *dirNode = node(index); if (!dirNode->volumeName.isNull()) return dirNode->volumeName + QLatin1String(" (") + name(index) + QLatin1Char(')'); #endif return name(index); } /*! \internal */ QIcon QFileSystemModelPrivate::icon(const QModelIndex &index) const { if (!index.isValid()) return QIcon(); return node(index)->icon(); } /*! \reimp */ bool QFileSystemModel::setData(const QModelIndex &idx, const QVariant &value, int role) { Q_D(QFileSystemModel); if (!idx.isValid() || idx.column() != 0 || role != Qt::EditRole || (flags(idx) & Qt::ItemIsEditable) == 0) { return false; } QString newName = value.toString(); QString oldName = idx.data().toString(); if (newName == idx.data().toString()) return true; if (newName.isEmpty() || QDir::toNativeSeparators(newName).contains(QDir::separator()) || !QDir(filePath(parent(idx))).rename(oldName, newName)) { #ifndef QT_NO_MESSAGEBOX QMessageBox::information(0, QFileSystemModel::tr("Invalid filename"), QFileSystemModel::tr("<b>The name \"%1\" can not be used.</b><p>Try using another name, with fewer characters or no punctuations marks.") .arg(newName), QMessageBox::Ok); #endif // QT_NO_MESSAGEBOX return false; } else { /* *After re-naming something we don't want the selection to change* - can't remove rows and later insert - can't quickly remove and insert - index pointer can't change because treeview doesn't use persistant index's - if this get any more complicated think of changing it to just use layoutChanged */ QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(idx); QFileSystemModelPrivate::QFileSystemNode *parentNode = indexNode->parent; int visibleLocation = parentNode->visibleLocation(parentNode->children.value(indexNode->fileName)->fileName); d->addNode(parentNode, newName,indexNode->info->fileInfo()); parentNode->visibleChildren.removeAt(visibleLocation); QFileSystemModelPrivate::QFileSystemNode * oldValue = parentNode->children.value(oldName); parentNode->children[newName] = oldValue; QFileInfo info(d->rootDir, newName); oldValue->fileName = newName; oldValue->parent = parentNode; #ifndef QT_NO_FILESYSTEMWATCHER oldValue->populate(d->fileInfoGatherer.getInfo(info)); #endif oldValue->isVisible = true; parentNode->children.remove(oldName); parentNode->visibleChildren.insert(visibleLocation, newName); d->delayedSort(); emit fileRenamed(filePath(idx.parent()), oldName, newName); } return true; } /*! \reimp */ QVariant QFileSystemModel::headerData(int section, Qt::Orientation orientation, int role) const { switch (role) { case Qt::DecorationRole: if (section == 0) { // ### TODO oh man this is ugly and doesn't even work all the way! // it is still 2 pixels off QImage pixmap(16, 1, QImage::Format_Mono); pixmap.fill(0); pixmap.setAlphaChannel(pixmap.createAlphaMask()); return pixmap; } break; case Qt::TextAlignmentRole: return Qt::AlignLeft; } if (orientation != Qt::Horizontal || role != Qt::DisplayRole) return QAbstractItemModel::headerData(section, orientation, role); QString returnValue; switch (section) { case 0: returnValue = tr("Name"); break; case 1: returnValue = tr("Size"); break; case 2: returnValue = #ifdef Q_OS_MAC tr("Kind", "Match OS X Finder"); #else tr("Type", "All other platforms"); #endif break; // Windows - Type // OS X - Kind // Konqueror - File Type // Nautilus - Type case 3: returnValue = tr("Date Modified"); break; default: return QVariant(); } return returnValue; } /*! \reimp */ Qt::ItemFlags QFileSystemModel::flags(const QModelIndex &index) const { Q_D(const QFileSystemModel); Qt::ItemFlags flags = QAbstractItemModel::flags(index); if (!index.isValid()) return flags; QFileSystemModelPrivate::QFileSystemNode *indexNode = d->node(index); if (d->nameFilterDisables && !d->passNameFilters(indexNode)) { flags &= ~Qt::ItemIsEnabled; // ### TODO you shouldn't be able to set this as the current item, task 119433 return flags; } flags |= Qt::ItemIsDragEnabled; if (d->readOnly) return flags; if ((index.column() == 0) && indexNode->permissions() & QFile::WriteUser) { flags |= Qt::ItemIsEditable; if (indexNode->isDir()) flags |= Qt::ItemIsDropEnabled; else flags |= Qt::ItemNeverHasChildren; } return flags; } /*! \internal */ void QFileSystemModelPrivate::_q_performDelayedSort() { Q_Q(QFileSystemModel); q->sort(sortColumn, sortOrder); } static inline QChar getNextChar(const QString &s, int location) { return (location < s.length()) ? s.at(location) : QChar(); } /*! Natural number sort, skips spaces. Examples: 1, 2, 10, 55, 100 01.jpg, 2.jpg, 10.jpg Note on the algorithm: Only as many characters as necessary are looked at and at most they all are looked at once. Slower then QString::compare() (of course) */ int QFileSystemModelPrivate::naturalCompare(const QString &s1, const QString &s2, Qt::CaseSensitivity cs) { for (int l1 = 0, l2 = 0; l1 <= s1.count() && l2 <= s2.count(); ++l1, ++l2) { // skip spaces, tabs and 0's QChar c1 = getNextChar(s1, l1); while (c1.isSpace()) c1 = getNextChar(s1, ++l1); QChar c2 = getNextChar(s2, l2); while (c2.isSpace()) c2 = getNextChar(s2, ++l2); if (c1.isDigit() && c2.isDigit()) { while (c1.digitValue() == 0) c1 = getNextChar(s1, ++l1); while (c2.digitValue() == 0) c2 = getNextChar(s2, ++l2); int lookAheadLocation1 = l1; int lookAheadLocation2 = l2; int currentReturnValue = 0; // find the last digit, setting currentReturnValue as we go if it isn't equal for ( QChar lookAhead1 = c1, lookAhead2 = c2; (lookAheadLocation1 <= s1.length() && lookAheadLocation2 <= s2.length()); lookAhead1 = getNextChar(s1, ++lookAheadLocation1), lookAhead2 = getNextChar(s2, ++lookAheadLocation2) ) { bool is1ADigit = !lookAhead1.isNull() && lookAhead1.isDigit(); bool is2ADigit = !lookAhead2.isNull() && lookAhead2.isDigit(); if (!is1ADigit && !is2ADigit) break; if (!is1ADigit) return -1; if (!is2ADigit) return 1; if (currentReturnValue == 0) { if (lookAhead1 < lookAhead2) { currentReturnValue = -1; } else if (lookAhead1 > lookAhead2) { currentReturnValue = 1; } } } if (currentReturnValue != 0) return currentReturnValue; } if (cs == Qt::CaseInsensitive) { if (!c1.isLower()) c1 = c1.toLower(); if (!c2.isLower()) c2 = c2.toLower(); } int r = QString::localeAwareCompare(c1, c2); if (r < 0) return -1; if (r > 0) return 1; } // The two strings are the same (02 == 2) so fall back to the normal sort return QString::compare(s1, s2, cs); } /* \internal Helper functor used by sort() */ class QFileSystemModelSorter { public: inline QFileSystemModelSorter(int column) : sortColumn(column) {} bool compareNodes(const QFileSystemModelPrivate::QFileSystemNode *l, const QFileSystemModelPrivate::QFileSystemNode *r) const { switch (sortColumn) { case 0: { #ifndef Q_OS_MAC // place directories before files bool left = l->isDir(); bool right = r->isDir(); if (left ^ right) return left; #endif return QFileSystemModelPrivate::naturalCompare(l->fileName, r->fileName, Qt::CaseInsensitive) < 0; } case 1: { // Directories go first bool left = l->isDir(); bool right = r->isDir(); if (left ^ right) return left; qint64 sizeDifference = l->size() - r->size(); if (sizeDifference == 0) return QFileSystemModelPrivate::naturalCompare(l->fileName, r->fileName, Qt::CaseInsensitive) < 0; return sizeDifference < 0; } case 2: { int compare = QString::localeAwareCompare(l->type(), r->type()); if (compare == 0) return QFileSystemModelPrivate::naturalCompare(l->fileName, r->fileName, Qt::CaseInsensitive) < 0; return compare < 0; } case 3: { if (l->lastModified() == r->lastModified()) return QFileSystemModelPrivate::naturalCompare(l->fileName, r->fileName, Qt::CaseInsensitive) < 0; return l->lastModified() < r->lastModified(); } } Q_ASSERT(false); return false; } bool operator()(const QPair<QFileSystemModelPrivate::QFileSystemNode*, int> &l, const QPair<QFileSystemModelPrivate::QFileSystemNode*, int> &r) const { return compareNodes(l.first, r.first); } private: int sortColumn; }; /* \internal Sort all of the children of parent */ void QFileSystemModelPrivate::sortChildren(int column, const QModelIndex &parent) { Q_Q(QFileSystemModel); QFileSystemModelPrivate::QFileSystemNode *indexNode = node(parent); if (indexNode->children.count() == 0) return; QList<QPair<QFileSystemModelPrivate::QFileSystemNode*, int> > values; QHash<QString, QFileSystemNode *>::const_iterator iterator; int i = 0; for(iterator = indexNode->children.constBegin() ; iterator != indexNode->children.constEnd() ; ++iterator) { if (filtersAcceptsNode(iterator.value())) { values.append(QPair<QFileSystemModelPrivate::QFileSystemNode*, int>((iterator.value()), i)); } else { iterator.value()->isVisible = false; } i++; } QFileSystemModelSorter ms(column); std::sort(values.begin(), values.end(), ms); // First update the new visible list indexNode->visibleChildren.clear(); //No more dirty item we reset our internal dirty index indexNode->dirtyChildrenIndex = -1; for (int i = 0; i < values.count(); ++i) { indexNode->visibleChildren.append(values.at(i).first->fileName); values.at(i).first->isVisible = true; } if (!disableRecursiveSort) { for (int i = 0; i < q->rowCount(parent); ++i) { const QModelIndex childIndex = q->index(i, 0, parent); QFileSystemModelPrivate::QFileSystemNode *indexNode = node(childIndex); //Only do a recursive sort on visible nodes if (indexNode->isVisible) sortChildren(column, childIndex); } } } /*! \reimp */ void QFileSystemModel::sort(int column, Qt::SortOrder order) { Q_D(QFileSystemModel); if (d->sortOrder == order && d->sortColumn == column && !d->forceSort) return; emit layoutAboutToBeChanged(); QModelIndexList oldList = persistentIndexList(); QList<QPair<QFileSystemModelPrivate::QFileSystemNode*, int> > oldNodes; for (int i = 0; i < oldList.count(); ++i) { QPair<QFileSystemModelPrivate::QFileSystemNode*, int> pair(d->node(oldList.at(i)), oldList.at(i).column()); oldNodes.append(pair); } if (!(d->sortColumn == column && d->sortOrder != order && !d->forceSort)) { //we sort only from where we are, don't need to sort all the model d->sortChildren(column, index(rootPath())); d->sortColumn = column; d->forceSort = false; } d->sortOrder = order; QModelIndexList newList; for (int i = 0; i < oldNodes.count(); ++i) { QModelIndex idx = d->index(oldNodes.at(i).first); idx = idx.sibling(idx.row(), oldNodes.at(i).second); newList.append(idx); } changePersistentIndexList(oldList, newList); emit layoutChanged(); } /*! Returns a list of MIME types that can be used to describe a list of items in the model. */ QStringList QFileSystemModel::mimeTypes() const { return QStringList(QLatin1String("text/uri-list")); } /*! Returns an object that contains a serialized description of the specified \a indexes. The format used to describe the items corresponding to the indexes is obtained from the mimeTypes() function. If the list of indexes is empty, 0 is returned rather than a serialized empty list. */ QMimeData *QFileSystemModel::mimeData(const QModelIndexList &indexes) const { QList<QUrl> urls; QList<QModelIndex>::const_iterator it = indexes.begin(); for (; it != indexes.end(); ++it) if ((*it).column() == 0) urls << QUrl::fromLocalFile(filePath(*it)); QMimeData *data = new QMimeData(); data->setUrls(urls); return data; } /*! Handles the \a data supplied by a drag and drop operation that ended with the given \a action over the row in the model specified by the \a row and \a column and by the \a parent index. \sa supportedDropActions() */ bool QFileSystemModel::dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent) { Q_UNUSED(row); Q_UNUSED(column); if (!parent.isValid() || isReadOnly()) return false; bool success = true; QString to = filePath(parent) + QDir::separator(); QList<QUrl> urls = data->urls(); QList<QUrl>::const_iterator it = urls.constBegin(); switch (action) { case Qt::CopyAction: for (; it != urls.constEnd(); ++it) { QString path = (*it).toLocalFile(); success = QFile::copy(path, to + QFileInfo(path).fileName()) && success; } break; case Qt::LinkAction: for (; it != urls.constEnd(); ++it) { QString path = (*it).toLocalFile(); success = QFile::link(path, to + QFileInfo(path).fileName()) && success; } break; case Qt::MoveAction: for (; it != urls.constEnd(); ++it) { QString path = (*it).toLocalFile(); success = QFile::rename(path, to + QFileInfo(path).fileName()) && success; } break; default: return false; } return success; } /*! \reimp */ Qt::DropActions QFileSystemModel::supportedDropActions() const { return Qt::CopyAction | Qt::MoveAction | Qt::LinkAction; } /*! Returns the path of the item stored in the model under the \a index given. */ QString QFileSystemModel::filePath(const QModelIndex &index) const { Q_D(const QFileSystemModel); QString fullPath = d->filePath(index); QFileSystemModelPrivate::QFileSystemNode *dirNode = d->node(index); if (dirNode->isSymLink() #ifndef QT_NO_FILESYSTEMWATCHER && d->fileInfoGatherer.resolveSymlinks() #endif && d->resolvedSymLinks.contains(fullPath) && dirNode->isDir()) { QFileInfo resolvedInfo(fullPath); resolvedInfo = resolvedInfo.canonicalFilePath(); if (resolvedInfo.exists()) return resolvedInfo.filePath(); } return fullPath; } QString QFileSystemModelPrivate::filePath(const QModelIndex &index) const { Q_Q(const QFileSystemModel); Q_UNUSED(q); if (!index.isValid()) return QString(); Q_ASSERT(index.model() == q); QStringList path; QModelIndex idx = index; while (idx.isValid()) { QFileSystemModelPrivate::QFileSystemNode *dirNode = node(idx); if (dirNode) path.prepend(dirNode->fileName); idx = idx.parent(); } QString fullPath = QDir::fromNativeSeparators(path.join(QDir::separator())); #if !defined(Q_OS_WIN) || defined(Q_OS_WINCE) if ((fullPath.length() > 2) && fullPath[0] == QLatin1Char('/') && fullPath[1] == QLatin1Char('/')) fullPath = fullPath.mid(1); #endif #if defined(Q_OS_WIN) if (fullPath.length() == 2 && fullPath.endsWith(QLatin1Char(':'))) fullPath.append(QLatin1Char('/')); #endif return fullPath; } /*! Create a directory with the \a name in the \a parent model index. */ QModelIndex QFileSystemModel::mkdir(const QModelIndex &parent, const QString &name) { Q_D(QFileSystemModel); if (!parent.isValid()) return parent; QDir dir(filePath(parent)); if (!dir.mkdir(name)) return QModelIndex(); QFileSystemModelPrivate::QFileSystemNode *parentNode = d->node(parent); d->addNode(parentNode, name, QFileInfo()); Q_ASSERT(parentNode->children.contains(name)); QFileSystemModelPrivate::QFileSystemNode *node = parentNode->children[name]; #ifndef QT_NO_FILESYSTEMWATCHER node->populate(d->fileInfoGatherer.getInfo(QFileInfo(dir.absolutePath() + QDir::separator() + name))); #endif d->addVisibleFiles(parentNode, QStringList(name)); return d->index(node); } /*! Returns the complete OR-ed together combination of QFile::Permission for the \a index. */ QFile::Permissions QFileSystemModel::permissions(const QModelIndex &index) const { Q_D(const QFileSystemModel); return d->node(index)->permissions(); } /*! Sets the directory that is being watched by the model to \a newPath by installing a \l{QFileSystemWatcher}{file system watcher} on it. Any changes to files and directories within this directory will be reflected in the model. If the path is changed, the rootPathChanged() signal will be emitted. \note This function does not change the structure of the model or modify the data available to views. In other words, the "root" of the model is \e not changed to include only files and directories within the directory specified by \a newPath in the file system. */ QModelIndex QFileSystemModel::setRootPath(const QString &newPath) { Q_D(QFileSystemModel); #ifdef Q_OS_WIN #ifdef Q_OS_WIN32 QString longNewPath = qt_GetLongPathName(newPath); #else QString longNewPath = QDir::fromNativeSeparators(newPath); #endif #else QString longNewPath = newPath; #endif QDir newPathDir(longNewPath); //we remove .. and . from the given path if exist if (!newPath.isEmpty()) { longNewPath = QDir::cleanPath(longNewPath); newPathDir.setPath(longNewPath); } d->setRootPath = true; //user don't ask for the root path ("") but the conversion failed if (!newPath.isEmpty() && longNewPath.isEmpty()) return d->index(rootPath()); if (d->rootDir.path() == longNewPath) return d->index(rootPath()); bool showDrives = (longNewPath.isEmpty() || longNewPath == d->myComputer()); if (!showDrives && !newPathDir.exists()) return d->index(rootPath()); //We remove the watcher on the previous path if (!rootPath().isEmpty() && rootPath() != QLatin1String(".")) { //This remove the watcher for the old rootPath #ifndef QT_NO_FILESYSTEMWATCHER d->fileInfoGatherer.removePath(rootPath()); #endif //This line "marks" the node as dirty, so the next fetchMore //call on the path will ask the gatherer to install a watcher again //But it doesn't re-fetch everything d->node(rootPath())->populatedChildren = false; } // We have a new valid root path d->rootDir = newPathDir; QModelIndex newRootIndex; if (showDrives) { // otherwise dir will become '.' d->rootDir.setPath(QLatin1String("")); } else { newRootIndex = d->index(newPathDir.path()); } fetchMore(newRootIndex); emit rootPathChanged(longNewPath); d->forceSort = true; d->delayedSort(); return newRootIndex; } /*! The currently set root path \sa rootDirectory() */ QString QFileSystemModel::rootPath() const { Q_D(const QFileSystemModel); return d->rootDir.path(); } /*! The currently set directory \sa rootPath() */ QDir QFileSystemModel::rootDirectory() const { Q_D(const QFileSystemModel); QDir dir(d->rootDir); dir.setNameFilters(nameFilters()); dir.setFilter(filter()); return dir; } /*! Sets the \a provider of file icons for the directory model. */ void QFileSystemModel::setIconProvider(QFileIconProvider *provider) { Q_D(QFileSystemModel); #ifndef QT_NO_FILESYSTEMWATCHER d->fileInfoGatherer.setIconProvider(provider); #endif d->root.updateIcon(provider, QString()); } /*! Returns the file icon provider for this directory model. */ QFileIconProvider *QFileSystemModel::iconProvider() const { #ifndef QT_NO_FILESYSTEMWATCHER Q_D(const QFileSystemModel); return d->fileInfoGatherer.iconProvider(); #else return 0; #endif } /*! Sets the directory model's filter to that specified by \a filters. Note that the filter you set should always include the QDir::AllDirs enum value, otherwise QFileSystemModel won't be able to read the directory structure. \sa QDir::Filters */ void QFileSystemModel::setFilter(QDir::Filters filters) { Q_D(QFileSystemModel); if (d->filters == filters) return; d->filters = filters; // CaseSensitivity might have changed setNameFilters(nameFilters()); d->forceSort = true; d->delayedSort(); } /*! Returns the filter specified for the directory model. If a filter has not been set, the default filter is QDir::AllEntries | QDir::NoDotAndDotDot | QDir::AllDirs. \sa QDir::Filters */ QDir::Filters QFileSystemModel::filter() const { Q_D(const QFileSystemModel); return d->filters; } /*! \property QFileSystemModel::resolveSymlinks \brief Whether the directory model should resolve symbolic links This is only relevant on Windows. By default, this property is \c true. */ void QFileSystemModel::setResolveSymlinks(bool enable) { #ifndef QT_NO_FILESYSTEMWATCHER Q_D(QFileSystemModel); d->fileInfoGatherer.setResolveSymlinks(enable); #else Q_UNUSED(enable) #endif } bool QFileSystemModel::resolveSymlinks() const { #ifndef QT_NO_FILESYSTEMWATCHER Q_D(const QFileSystemModel); return d->fileInfoGatherer.resolveSymlinks(); #else return false; #endif } /*! \property QFileSystemModel::readOnly \brief Whether the directory model allows writing to the file system If this property is set to false, the directory model will allow renaming, copying and deleting of files and directories. This property is \c true by default */ void QFileSystemModel::setReadOnly(bool enable) { Q_D(QFileSystemModel); d->readOnly = enable; } bool QFileSystemModel::isReadOnly() const { Q_D(const QFileSystemModel); return d->readOnly; } /*! \property QFileSystemModel::nameFilterDisables \brief Whether files that don't pass the name filter are hidden or disabled This property is \c true by default */ void QFileSystemModel::setNameFilterDisables(bool enable) { Q_D(QFileSystemModel); if (d->nameFilterDisables == enable) return; d->nameFilterDisables = enable; d->forceSort = true; d->delayedSort(); } bool QFileSystemModel::nameFilterDisables() const { Q_D(const QFileSystemModel); return d->nameFilterDisables; } /*! Sets the name \a filters to apply against the existing files. */ void QFileSystemModel::setNameFilters(const QStringList &filters) { // Prep the regexp's ahead of time #ifndef QT_NO_REGEXP Q_D(QFileSystemModel); if (!d->bypassFilters.isEmpty()) { // update the bypass filter to only bypass the stuff that must be kept around d->bypassFilters.clear(); // We guarantee that rootPath will stick around QPersistentModelIndex root(index(rootPath())); QModelIndexList persistantList = persistentIndexList(); for (int i = 0; i < persistantList.count(); ++i) { QFileSystemModelPrivate::QFileSystemNode *node; node = d->node(persistantList.at(i)); while (node) { if (d->bypassFilters.contains(node)) break; if (node->isDir()) d->bypassFilters[node] = true; node = node->parent; } } } d->nameFilters.clear(); const Qt::CaseSensitivity caseSensitive = (filter() & QDir::CaseSensitive) ? Qt::CaseSensitive : Qt::CaseInsensitive; for (int i = 0; i < filters.size(); ++i) { d->nameFilters << QRegExp(filters.at(i), caseSensitive, QRegExp::Wildcard); } d->forceSort = true; d->delayedSort(); #endif } /*! Returns a list of filters applied to the names in the model. */ QStringList QFileSystemModel::nameFilters() const { Q_D(const QFileSystemModel); QStringList filters; #ifndef QT_NO_REGEXP for (int i = 0; i < d->nameFilters.size(); ++i) { filters << d->nameFilters.at(i).pattern(); } #endif return filters; } /*! \reimp */ bool QFileSystemModel::event(QEvent *event) { #ifndef QT_NO_FILESYSTEMWATCHER Q_D(QFileSystemModel); if (event->type() == QEvent::LanguageChange) { d->root.retranslateStrings(d->fileInfoGatherer.iconProvider(), QString()); return true; } #endif return QAbstractItemModel::event(event); } bool QFileSystemModel::rmdir(const QModelIndex &aindex) { QString path = filePath(aindex); #ifndef QT_NO_FILESYSTEMWATCHER QFileSystemModelPrivate * d = const_cast<QFileSystemModelPrivate*>(d_func()); d->fileInfoGatherer.removePath(path); #endif return QDir().rmdir(path); } /*! \internal Performed quick listing and see if any files have been added or removed, then fetch more information on visible files. */ void QFileSystemModelPrivate::_q_directoryChanged(const QString &directory, const QStringList &files) { QFileSystemModelPrivate::QFileSystemNode *parentNode = node(directory, false); if (parentNode->children.count() == 0) return; QStringList toRemove; QStringList newFiles = files; std::sort(newFiles.begin(), newFiles.end()); QHash<QString, QFileSystemNode*>::const_iterator i = parentNode->children.constBegin(); while (i != parentNode->children.constEnd()) { QStringList::iterator iterator = std::lower_bound(newFiles.begin(), newFiles.end(), i.value()->fileName); if ((iterator == newFiles.end()) || (i.value()->fileName < *iterator)) toRemove.append(i.value()->fileName); ++i; } for (int i = 0 ; i < toRemove.count() ; ++i ) removeNode(parentNode, toRemove[i]); } /*! \internal Adds a new file to the children of parentNode *WARNING* this will change the count of children */ QFileSystemModelPrivate::QFileSystemNode* QFileSystemModelPrivate::addNode(QFileSystemNode *parentNode, const QString &fileName, const QFileInfo& info) { // In the common case, itemLocation == count() so check there first QFileSystemModelPrivate::QFileSystemNode *node = new QFileSystemModelPrivate::QFileSystemNode(fileName, parentNode); #ifndef QT_NO_FILESYSTEMWATCHER node->populate(info); #else Q_UNUSED(info) #endif #if defined(Q_OS_WIN) && !defined(Q_OS_WINCE) && !defined(Q_OS_WINRT) //The parentNode is "" so we are listing the drives if (parentNode->fileName.isEmpty()) { wchar_t name[MAX_PATH + 1]; //GetVolumeInformation requires to add trailing backslash const QString nodeName = fileName + QLatin1String("\\"); BOOL success = ::GetVolumeInformation((wchar_t *)(nodeName.utf16()), name, MAX_PATH + 1, NULL, 0, NULL, NULL, 0); if (success && name[0]) node->volumeName = QString::fromWCharArray(name); } #endif parentNode->children.insert(fileName, node); return node; } /*! \internal File at parentNode->children(itemLocation) has been removed, remove from the lists and emit signals if necessary *WARNING* this will change the count of children and could change visibleChildren */ void QFileSystemModelPrivate::removeNode(QFileSystemModelPrivate::QFileSystemNode *parentNode, const QString& name) { Q_Q(QFileSystemModel); QModelIndex parent = index(parentNode); bool indexHidden = isHiddenByFilter(parentNode, parent); int vLocation = parentNode->visibleLocation(name); if (vLocation >= 0 && !indexHidden) q->beginRemoveRows(parent, translateVisibleLocation(parentNode, vLocation), translateVisibleLocation(parentNode, vLocation)); QFileSystemNode * node = parentNode->children.take(name); delete node; // cleanup sort files after removing rather then re-sorting which is O(n) if (vLocation >= 0) parentNode->visibleChildren.removeAt(vLocation); if (vLocation >= 0 && !indexHidden) q->endRemoveRows(); } /* \internal Helper functor used by addVisibleFiles() */ class QFileSystemModelVisibleFinder { public: inline QFileSystemModelVisibleFinder(QFileSystemModelPrivate::QFileSystemNode *node, QFileSystemModelSorter *sorter) : parentNode(node), sorter(sorter) {} bool operator()(const QString &, QString r) const { return sorter->compareNodes(parentNode->children.value(name), parentNode->children.value(r)); } QString name; private: QFileSystemModelPrivate::QFileSystemNode *parentNode; QFileSystemModelSorter *sorter; }; /*! \internal File at parentNode->children(itemLocation) was not visible before, but now should be and emit signals if necessary. *WARNING* this will change the visible count */ void QFileSystemModelPrivate::addVisibleFiles(QFileSystemNode *parentNode, const QStringList &newFiles) { Q_Q(QFileSystemModel); QModelIndex parent = index(parentNode); bool indexHidden = isHiddenByFilter(parentNode, parent); if (!indexHidden) { q->beginInsertRows(parent, parentNode->visibleChildren.count() , parentNode->visibleChildren.count() + newFiles.count() - 1); } if (parentNode->dirtyChildrenIndex == -1) parentNode->dirtyChildrenIndex = parentNode->visibleChildren.count(); for (int i = 0; i < newFiles.count(); ++i) { parentNode->visibleChildren.append(newFiles.at(i)); parentNode->children[newFiles.at(i)]->isVisible = true; } if (!indexHidden) q->endInsertRows(); } /*! \internal File was visible before, but now should NOT be *WARNING* this will change the visible count */ void QFileSystemModelPrivate::removeVisibleFile(QFileSystemNode *parentNode, int vLocation) { Q_Q(QFileSystemModel); if (vLocation == -1) return; QModelIndex parent = index(parentNode); bool indexHidden = isHiddenByFilter(parentNode, parent); if (!indexHidden) q->beginRemoveRows(parent, translateVisibleLocation(parentNode, vLocation), translateVisibleLocation(parentNode, vLocation)); parentNode->children[parentNode->visibleChildren.at(vLocation)]->isVisible = false; parentNode->visibleChildren.removeAt(vLocation); if (!indexHidden) q->endRemoveRows(); } /*! \internal The thread has received new information about files, update and emit dataChanged if it has actually changed. */ void QFileSystemModelPrivate::_q_fileSystemChanged(const QString &path, const QList<QPair<QString, QFileInfo> > &updates) { #ifndef QT_NO_FILESYSTEMWATCHER Q_Q(QFileSystemModel); QVector<QString> rowsToUpdate; QStringList newFiles; QFileSystemModelPrivate::QFileSystemNode *parentNode = node(path, false); QModelIndex parentIndex = index(parentNode); for (int i = 0; i < updates.count(); ++i) { QString fileName = updates.at(i).first; Q_ASSERT(!fileName.isEmpty()); QExtendedInformation info = fileInfoGatherer.getInfo(updates.at(i).second); bool previouslyHere = parentNode->children.contains(fileName); if (!previouslyHere) { addNode(parentNode, fileName, info.fileInfo()); } QFileSystemModelPrivate::QFileSystemNode * node = parentNode->children.value(fileName); bool isCaseSensitive = parentNode->caseSensitive(); if (isCaseSensitive) { if (node->fileName != fileName) continue; } else { if (QString::compare(node->fileName,fileName,Qt::CaseInsensitive) != 0) continue; } if (isCaseSensitive) { Q_ASSERT(node->fileName == fileName); } else { node->fileName = fileName; } if (info.size() == -1 && !info.isSymLink()) { removeNode(parentNode, fileName); continue; } if (*node != info ) { node->populate(info); bypassFilters.remove(node); // brand new information. if (filtersAcceptsNode(node)) { if (!node->isVisible) { newFiles.append(fileName); } else { rowsToUpdate.append(fileName); } } else { if (node->isVisible) { int visibleLocation = parentNode->visibleLocation(fileName); removeVisibleFile(parentNode, visibleLocation); } else { // The file is not visible, don't do anything } } } } // bundle up all of the changed signals into as few as possible. std::sort(rowsToUpdate.begin(), rowsToUpdate.end()); QString min; QString max; for (int i = 0; i < rowsToUpdate.count(); ++i) { QString value = rowsToUpdate.at(i); //##TODO is there a way to bundle signals with QString as the content of the list? /*if (min.isEmpty()) { min = value; if (i != rowsToUpdate.count() - 1) continue; } if (i != rowsToUpdate.count() - 1) { if ((value == min + 1 && max.isEmpty()) || value == max + 1) { max = value; continue; } }*/ max = value; min = value; int visibleMin = parentNode->visibleLocation(min); int visibleMax = parentNode->visibleLocation(max); if (visibleMin >= 0 && visibleMin < parentNode->visibleChildren.count() && parentNode->visibleChildren.at(visibleMin) == min && visibleMax >= 0) { QModelIndex bottom = q->index(translateVisibleLocation(parentNode, visibleMin), 0, parentIndex); QModelIndex top = q->index(translateVisibleLocation(parentNode, visibleMax), 3, parentIndex); emit q->dataChanged(bottom, top); } /*min = QString(); max = QString();*/ } if (newFiles.count() > 0) { addVisibleFiles(parentNode, newFiles); } if (newFiles.count() > 0 || (sortColumn != 0 && rowsToUpdate.count() > 0)) { forceSort = true; delayedSort(); } #else Q_UNUSED(path) Q_UNUSED(updates) #endif // !QT_NO_FILESYSTEMWATCHER } /*! \internal */ void QFileSystemModelPrivate::_q_resolvedName(const QString &fileName, const QString &resolvedName) { resolvedSymLinks[fileName] = resolvedName; } /*! \internal */ void QFileSystemModelPrivate::init() { Q_Q(QFileSystemModel); qRegisterMetaType<QList<QPair<QString,QFileInfo> > >(); #ifndef QT_NO_FILESYSTEMWATCHER q->connect(&fileInfoGatherer, SIGNAL(newListOfFiles(QString,QStringList)), q, SLOT(_q_directoryChanged(QString,QStringList))); q->connect(&fileInfoGatherer, SIGNAL(updates(QString,QList<QPair<QString,QFileInfo> >)), q, SLOT(_q_fileSystemChanged(QString,QList<QPair<QString,QFileInfo> >))); q->connect(&fileInfoGatherer, SIGNAL(nameResolved(QString,QString)), q, SLOT(_q_resolvedName(QString,QString))); q->connect(&fileInfoGatherer, SIGNAL(directoryLoaded(QString)), q, SIGNAL(directoryLoaded(QString))); #endif // !QT_NO_FILESYSTEMWATCHER q->connect(&delayedSortTimer, SIGNAL(timeout()), q, SLOT(_q_performDelayedSort()), Qt::QueuedConnection); roleNames.insertMulti(QFileSystemModel::FileIconRole, QByteArrayLiteral("fileIcon")); // == Qt::decoration roleNames.insert(QFileSystemModel::FilePathRole, QByteArrayLiteral("filePath")); roleNames.insert(QFileSystemModel::FileNameRole, QByteArrayLiteral("fileName")); roleNames.insert(QFileSystemModel::FilePermissions, QByteArrayLiteral("filePermissions")); } /*! \internal Returns \c false if node doesn't pass the filters otherwise true QDir::Modified is not supported QDir::Drives is not supported */ bool QFileSystemModelPrivate::filtersAcceptsNode(const QFileSystemNode *node) const { // always accept drives if (node->parent == &root || bypassFilters.contains(node)) return true; // If we don't know anything yet don't accept it if (!node->hasInformation()) return false; const bool filterPermissions = ((filters & QDir::PermissionMask) && (filters & QDir::PermissionMask) != QDir::PermissionMask); const bool hideDirs = !(filters & (QDir::Dirs | QDir::AllDirs)); const bool hideFiles = !(filters & QDir::Files); const bool hideReadable = !(!filterPermissions || (filters & QDir::Readable)); const bool hideWritable = !(!filterPermissions || (filters & QDir::Writable)); const bool hideExecutable = !(!filterPermissions || (filters & QDir::Executable)); const bool hideHidden = !(filters & QDir::Hidden); const bool hideSystem = !(filters & QDir::System); const bool hideSymlinks = (filters & QDir::NoSymLinks); const bool hideDot = (filters & QDir::NoDot); const bool hideDotDot = (filters & QDir::NoDotDot); // Note that we match the behavior of entryList and not QFileInfo on this. bool isDot = (node->fileName == QLatin1String(".")); bool isDotDot = (node->fileName == QLatin1String("..")); if ( (hideHidden && !(isDot || isDotDot) && node->isHidden()) || (hideSystem && node->isSystem()) || (hideDirs && node->isDir()) || (hideFiles && node->isFile()) || (hideSymlinks && node->isSymLink()) || (hideReadable && node->isReadable()) || (hideWritable && node->isWritable()) || (hideExecutable && node->isExecutable()) || (hideDot && isDot) || (hideDotDot && isDotDot)) return false; return nameFilterDisables || passNameFilters(node); } /* \internal Returns \c true if node passes the name filters and should be visible. */ bool QFileSystemModelPrivate::passNameFilters(const QFileSystemNode *node) const { #ifndef QT_NO_REGEXP if (nameFilters.isEmpty()) return true; // Check the name regularexpression filters if (!(node->isDir() && (filters & QDir::AllDirs))) { for (int i = 0; i < nameFilters.size(); ++i) { QRegExp copy = nameFilters.at(i); if (copy.exactMatch(node->fileName)) return true; } return false; } #endif return true; } QT_END_NAMESPACE #include "moc_qfilesystemmodel.cpp" #endif // QT_NO_FILESYSTEMMODEL
32.390966
169
0.641252
[ "object", "model" ]
baa7af166b57ac656ac8b1aba9d54ec8b3d40a69
19,415
cpp
C++
c++/server.cpp
fossabot/RelayNode
2a9190169c226590b223fd4e60b9da02f3081417
[ "MIT" ]
71
2015-05-29T02:26:36.000Z
2021-11-11T04:52:43.000Z
c++/server.cpp
dendisuhubdy/RelayNode
c50d81223104fcf00ca0413f87b9c0562a8a55f7
[ "MIT" ]
23
2015-06-03T10:16:19.000Z
2021-02-19T13:36:15.000Z
c++/server.cpp
dendisuhubdy/RelayNode
c50d81223104fcf00ca0413f87b9c0562a8a55f7
[ "MIT" ]
41
2015-03-14T23:16:05.000Z
2021-10-31T04:20:04.000Z
#include <map> #include <vector> #include <thread> #include <chrono> #include <mutex> #include <assert.h> #include <string.h> #include <unistd.h> #include <sys/time.h> #include <netinet/tcp.h> #include <netdb.h> #include <fcntl.h> #define BITCOIN_UA_LENGTH 23 #define BITCOIN_UA {'/', 'R', 'e', 'l', 'a', 'y', 'N', 'e', 't', 'w', 'o', 'r', 'k', 'S', 'e', 'r', 'v', 'e', 'r', ':', '4', '2', '/'} #include "crypto/sha2.h" #include "flaggedarrayset.h" #include "relayprocess.h" #include "utils.h" #include "p2pclient.h" #include "connection.h" #include "rpcclient.h" static const char* HOST_SPONSOR; static const std::map<std::string, int16_t> compressor_types = {{std::string("sponsor printer"), 1}, {std::string("spammy memeater"), 0}, {std::string("the blocksize"), 1}}; /*********************************************** **** Relay network client processing class **** ***********************************************/ class RelayNetworkClient : public Connection { private: std::atomic_int connected; bool sendSponsor = false; uint8_t tx_sent = 0; const std::function<size_t (RelayNetworkClient*, std::shared_ptr<std::vector<unsigned char> >&, const std::vector<unsigned char>&)> provide_block; const std::function<void (RelayNetworkClient*, std::shared_ptr<std::vector<unsigned char> >&)> provide_transaction; const std::function<void (RelayNetworkClient*, int)> connected_callback; RELAY_DECLARE_CLASS_VARS RelayNodeCompressor compressor; public: time_t lastDupConnect = 0; std::atomic<int16_t> compressor_type; RelayNetworkClient(int sockIn, std::string hostIn, const std::function<size_t (RelayNetworkClient*, std::shared_ptr<std::vector<unsigned char> >&, const std::vector<unsigned char>&)>& provide_block_in, const std::function<void (RelayNetworkClient*, std::shared_ptr<std::vector<unsigned char> >&)>& provide_transaction_in, const std::function<void (RelayNetworkClient*, int)>& connected_callback_in) : Connection(sockIn, hostIn, NULL), connected(0), provide_block(provide_block_in), provide_transaction(provide_transaction_in), connected_callback(connected_callback_in), RELAY_DECLARE_CONSTRUCTOR_EXTENDS, compressor(false), compressor_type(-1) // compressor is always replaced in VERSION_TYPE recv { construction_done(); } private: void send_sponsor(int token=0) { if (!sendSponsor || tx_sent != 0) return; relay_msg_header sponsor_header = { RELAY_MAGIC_BYTES, SPONSOR_TYPE, htonl(strlen(HOST_SPONSOR)) }; do_send_bytes((char*)&sponsor_header, sizeof(sponsor_header), token); do_send_bytes(HOST_SPONSOR, strlen(HOST_SPONSOR), token); } void net_process(const std::function<void(std::string)>& disconnect) { compressor.reset(); while (true) { relay_msg_header header; if (read_all((char*)&header, 4*3) != 4*3) return disconnect("failed to read message header"); if (header.magic != RELAY_MAGIC_BYTES) return disconnect("invalid magic bytes"); uint32_t message_size = ntohl(header.length); if (message_size > 1000000) return disconnect("got message too large"); if (header.type == VERSION_TYPE) { char data[message_size + 1]; if (read_all(data, message_size) < (int64_t)(message_size)) return disconnect("failed to read version message"); for (uint32_t i = 0; i < message_size; i++) if (data[i] > 'z' && data[i] < 'a' && data[i] != ' ') return disconnect("bogus version string"); data[message_size] = 0; std::string their_version(data); if (their_version != VERSION_STRING) { relay_msg_header version_header = { RELAY_MAGIC_BYTES, MAX_VERSION_TYPE, htonl(strlen(VERSION_STRING)) }; do_send_bytes((char*)&version_header, sizeof(version_header)); do_send_bytes(VERSION_STRING, strlen(VERSION_STRING)); } std::map<std::string, int16_t>::const_iterator it = compressor_types.find(their_version); if (it == compressor_types.end()) return disconnect("unknown version string"); compressor_type = it->second; if (their_version == "spammy memeater") compressor = RelayNodeCompressor(false); else compressor = RelayNodeCompressor(true); if (their_version != "the blocksize") sendSponsor = true; relay_msg_header version_header = { RELAY_MAGIC_BYTES, VERSION_TYPE, htonl(message_size) }; do_send_bytes((char*)&version_header, sizeof(version_header)); do_send_bytes(data, message_size); printf("%s Connected to relay node with protocol version %s\n", host.c_str(), data); int token = get_send_mutex(); connected = 2; do_throttle_outbound(); connected_callback(this, token); // Called with send_mutex! release_send_mutex(token); } else if (connected != 2) { return disconnect("got non-version before version"); } else if (header.type == MAX_VERSION_TYPE) { char data[message_size]; if (read_all(data, message_size) < (int64_t)(message_size)) return disconnect("failed to read max_version string"); if (strncmp(VERSION_STRING, data, std::min(sizeof(VERSION_STRING), size_t(message_size)))) printf("%s peer sent us a MAX_VERSION message\n", host.c_str()); else return disconnect("got MAX_VERSION of same version as us"); } else if (header.type == SPONSOR_TYPE) { char data[message_size]; if (read_all(data, message_size) < (int64_t)(message_size)) return disconnect("failed to read sponsor string"); } else if (header.type == BLOCK_TYPE) { std::chrono::system_clock::time_point read_start(std::chrono::system_clock::now()); std::function<ssize_t(char*, size_t)> do_read = [&](char* buf, size_t count) { return read_all(buf, count); }; auto res = compressor.decompress_relay_block(do_read, message_size, true); if (std::get<2>(res)) return disconnect(std::get<2>(res)); std::chrono::system_clock::time_point read_finish(std::chrono::system_clock::now()); const std::vector<unsigned char>& fullhash = *std::get<3>(res).get(); size_t bytes_sent = provide_block(this, std::get<1>(res), fullhash); std::chrono::system_clock::time_point send_queued(std::chrono::system_clock::now()); if (bytes_sent) { printf(HASH_FORMAT" BLOCK %lu %s UNTRUSTEDRELAY %u / %lu / %u TIMES: %lf %lf\n", HASH_PRINT(&fullhash[0]), epoch_millis_lu(read_finish), host.c_str(), (unsigned)std::get<0>(res), bytes_sent, (unsigned)std::get<1>(res)->size(), to_millis_double(read_finish - read_start), to_millis_double(send_queued - read_finish)); } } else if (header.type == END_BLOCK_TYPE) { } else if (header.type == TRANSACTION_TYPE) { if (!compressor.maybe_recv_tx_of_size(message_size, false)) return disconnect("got freely relayed transaction too large"); auto tx = std::make_shared<std::vector<unsigned char> > (message_size); if (read_all((char*)&(*tx)[0], message_size) < (int64_t)(message_size)) return disconnect("failed to read loose transaction data"); compressor.recv_tx(tx); provide_transaction(this, tx); } else if (header.type == OOB_TRANSACTION_TYPE) { if (message_size > 1000000) return disconnect("got oob transaction too large"); auto tx = std::make_shared<std::vector<unsigned char> > (message_size); if (read_all((char*)&(*tx)[0], message_size) < (int64_t)(message_size)) return disconnect("failed to read oob transaction data"); provide_transaction(this, tx); } else if (header.type == PING_TYPE) { char data[8]; if (message_size != 8 || read_all(data, 8) < 8) return disconnect("failed to read 8 byte ping message"); relay_msg_header pong_msg_header = { RELAY_MAGIC_BYTES, PONG_TYPE, htonl(8) }; int token = get_send_mutex(); do_send_bytes((char*)&pong_msg_header, sizeof(pong_msg_header), token); do_send_bytes(data, 8, token); release_send_mutex(token); } else return disconnect("got unknown message type"); } } public: void receive_transaction(const std::shared_ptr<std::vector<unsigned char> >& tx, int token=0) { if (connected != 2) return; do_send_bytes(tx, token); tx_sent++; if (!token) send_sponsor(token); } void receive_block(const std::shared_ptr<std::vector<unsigned char> >& block) { if (connected != 2) return; int token = get_send_mutex(); do_send_bytes(block, token); struct relay_msg_header header = { RELAY_MAGIC_BYTES, END_BLOCK_TYPE, 0 }; do_send_bytes((char*)&header, sizeof(header), token); release_send_mutex(token); } }; class P2PClient : public P2PRelayer { public: P2PClient(const char* serverHostIn, uint16_t serverPortIn, const std::function<void (std::vector<unsigned char>&, const std::chrono::system_clock::time_point&)>& provide_block_in, const std::function<void (std::shared_ptr<std::vector<unsigned char> >&)>& provide_transaction_in, const std::function<void (std::vector<unsigned char>&)>& provide_headers_in, bool check_block_msghash_in) : P2PRelayer(serverHostIn, serverPortIn, 60000, provide_block_in, provide_transaction_in, provide_headers_in, check_block_msghash_in) { construction_done(); } private: std::vector<unsigned char> generate_version() { struct bitcoin_version_with_header version_msg; version_msg.version.start.timestamp = htole64(time(0)); version_msg.version.start.user_agent_length = BITCOIN_UA_LENGTH; // Work around apparent gcc bug return std::vector<unsigned char>((unsigned char*)&version_msg, (unsigned char*)&version_msg + sizeof(version_msg)); } }; class RelayNetworkCompressor : public RelayNodeCompressor { public: RelayNetworkCompressor() : RelayNodeCompressor(false) {} RelayNetworkCompressor(bool useFlagsAndSmallerMax) : RelayNodeCompressor(useFlagsAndSmallerMax) {} void relay_node_connected(RelayNetworkClient* client, int token) { for_each_sent_tx([&] (const std::shared_ptr<std::vector<unsigned char> >& tx) { client->receive_transaction(tx_to_msg(tx, false, false), token); client->receive_transaction(tx, token); }); } }; #define COMPRESSOR_TYPES 2 static RelayNetworkCompressor compressors[COMPRESSOR_TYPES]; class CompressorInit { public: CompressorInit() { compressors[0] = RelayNetworkCompressor(false); compressors[1] = RelayNetworkCompressor(true); } }; static CompressorInit init; class MempoolClient : public OutboundPersistentConnection { private: std::function<void(std::vector<unsigned char>)> on_hash; public: MempoolClient(std::string serverHostIn, uint16_t serverPortIn, std::function<void(std::vector<unsigned char>)> on_hash_in) : OutboundPersistentConnection(serverHostIn, serverPortIn), on_hash(on_hash_in) { construction_done(); } void on_disconnect() {} void net_process(const std::function<void(std::string)>& disconnect) { while (true) { std::vector<unsigned char> hash(32); if (read_all((char*)&hash[0], 32, std::chrono::seconds(10)) != 32) return disconnect("Failed to read next hash"); on_hash(hash); } } void keep_alive_ping() { char byte = 0x42; maybe_do_send_bytes(&byte, 1); } }; int main(const int argc, const char** argv) { if (argc < 6) { printf("USAGE: %s trusted_bitcoind_host trusted_bitcoind_port mempool_host mempool_port \"Sponsor String\" (::ffff:whitelisted prefix string)*\n", argv[0]); return -1; } HOST_SPONSOR = argv[5]; int listen_fd; struct sockaddr_in6 addr; if ((listen_fd = socket(AF_INET6, SOCK_STREAM, 0)) < 0) { printf("Failed to create socket\n"); return -1; } memset(&addr, 0, sizeof(addr)); addr.sin6_family = AF_INET6; addr.sin6_addr = in6addr_any; addr.sin6_port = htons(8336); int reuse = 1; if (setsockopt(listen_fd, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) || bind(listen_fd, (struct sockaddr *) &addr, sizeof(addr)) < 0 || listen(listen_fd, 3) < 0) { printf("Failed to bind 8336: %s\n", strerror(errno)); return -1; } std::mutex map_mutex; std::map<std::string, RelayNetworkClient*> clientMap; P2PClient *trustedP2P, *trustedP2PRecv; // You'll notice in the below callbacks that we have to do some header adding/removing // This is because the things are setup for the relay <-> p2p case (both to optimize // the client and because that is the case we want to optimize for) std::mutex txn_mutex; vectormruset txnWaitingToBroadcast(MAX_FAS_TOTAL_SIZE); const std::function<std::pair<const char*, size_t> (const std::vector<unsigned char>&, const std::vector<unsigned char>&, bool)> do_relay = [&](const std::vector<unsigned char>& fullhash, const std::vector<unsigned char>& bytes, bool checkMerkle) { std::lock_guard<std::mutex> lock(map_mutex); size_t ret; for (uint16_t i = 0; i < COMPRESSOR_TYPES; i++) { auto tuple = compressors[i].maybe_compress_block(fullhash, bytes, checkMerkle); const char* insane = std::get<1>(tuple); if (!insane) { auto block = std::get<0>(tuple); for (const auto& client : clientMap) { if (!client.second->getDisconnectFlags() && client.second->compressor_type == i) client.second->receive_block(block); } if (i == 0) ret = block->size(); } else return std::make_pair(insane, (size_t)0); } return std::make_pair((const char*)0, ret); }; trustedP2P = new P2PClient(argv[1], std::stoul(argv[2]), [&](std::vector<unsigned char>& bytes, const std::chrono::system_clock::time_point& read_start) { }, [&](std::shared_ptr<std::vector<unsigned char> >& bytes) { }, [&](std::vector<unsigned char>& headers) { try { std::vector<unsigned char>::const_iterator it = headers.begin(); uint64_t count = read_varint(it, headers.end()); for (uint64_t i = 0; i < count; i++) { move_forward(it, 81, headers.end()); if (*(it - 1) != 0) return; std::vector<unsigned char> fullhash(32); getblockhash(fullhash, headers, it - 81 - headers.begin()); compressors[0].block_sent(fullhash); } printf("Added headers from trusted peers, seen %u blocks\n", compressors[0].blocks_sent()); } catch (read_exception) { } }, false); trustedP2PRecv = new P2PClient(argv[1], std::stoul(argv[2]), [&](std::vector<unsigned char>& bytes, const std::chrono::system_clock::time_point& read_start) { if (bytes.size() < sizeof(struct bitcoin_msg_header) + 80) return; std::chrono::system_clock::time_point send_start(std::chrono::system_clock::now()); std::vector<unsigned char> fullhash(32); getblockhash(fullhash, bytes, sizeof(struct bitcoin_msg_header)); std::pair<const char*, size_t> relay_res = do_relay(fullhash, bytes, false); if (relay_res.first) { printf(HASH_FORMAT" INSANE %s TRUSTEDP2P\n", HASH_PRINT(&fullhash[0]), relay_res.first); return; } std::chrono::system_clock::time_point send_end(std::chrono::system_clock::now()); printf(HASH_FORMAT" BLOCK %lu %s TRUSTEDP2P %lu / %lu / %lu TIMES: %lf %lf\n", HASH_PRINT(&fullhash[0]), epoch_millis_lu(send_start), argv[1], bytes.size(), relay_res.second, bytes.size(), to_millis_double(send_start - read_start), to_millis_double(send_end - send_start)); }, [&](std::shared_ptr<std::vector<unsigned char> >& bytes) { std::vector<unsigned char> hash(32); double_sha256(&(*bytes)[0], &hash[0], bytes->size()); { std::lock_guard<std::mutex> lock(txn_mutex); if (txnWaitingToBroadcast.find(hash) == txnWaitingToBroadcast.end()) return; } std::lock_guard<std::mutex> lock(map_mutex); for (uint16_t i = 0; i < COMPRESSOR_TYPES; i++) { auto tx = compressors[i].get_relay_transaction(bytes); if (tx.use_count()) { for (const auto& client : clientMap) { if (!client.second->getDisconnectFlags() && client.second->compressor_type == i) client.second->receive_transaction(tx); } } } }, [&](std::vector<unsigned char>& headers) { }, false); MempoolClient mempoolClient(argv[3], std::stoul(argv[4]), [&](std::vector<unsigned char> txn) { std::lock_guard<std::mutex> lock(map_mutex); if (!compressors[0].was_tx_sent(&txn[0])) { std::lock_guard<std::mutex> lock(txn_mutex); txnWaitingToBroadcast.insert(txn); trustedP2PRecv->request_transaction(txn); } }); std::function<size_t (RelayNetworkClient*, std::shared_ptr<std::vector<unsigned char> >&, const std::vector<unsigned char>&)> relayBlock = [&](RelayNetworkClient* from, std::shared_ptr<std::vector<unsigned char>> & bytes, const std::vector<unsigned char>& fullhash) { if (bytes->size() < sizeof(struct bitcoin_msg_header) + 80) return (size_t)0; trustedP2P->receive_block(*bytes); return bytes->size(); }; std::function<void (RelayNetworkClient*, std::shared_ptr<std::vector<unsigned char> >&)> relayTx = [&](RelayNetworkClient* from, std::shared_ptr<std::vector<unsigned char>> & bytes) { trustedP2P->receive_transaction(bytes); }; std::function<void (RelayNetworkClient*, int token)> connected = [&](RelayNetworkClient* client, int token) { assert(client->compressor_type >= 0 && client->compressor_type < COMPRESSOR_TYPES); compressors[client->compressor_type].relay_node_connected(client, token); }; std::thread([&](void) { while (true) { std::this_thread::sleep_for(std::chrono::seconds(10)); // Implicit new-connection rate-limit { std::lock_guard<std::mutex> lock(map_mutex); for (auto it = clientMap.begin(); it != clientMap.end();) { if (it->second->getDisconnectFlags() & DISCONNECT_COMPLETE) { fprintf(stderr, "%lld: Culled %s, have %lu relay clients\n", (long long) time(NULL), it->first.c_str(), clientMap.size() - 1); delete it->second; clientMap.erase(it++); } else it++; } } mempoolClient.keep_alive_ping(); } }).detach(); std::string droppostfix(".uptimerobot.com"); std::vector<std::string> whitelistprefix; for (int i = 6; i < argc; i++) whitelistprefix.push_back(argv[i]); socklen_t addr_size = sizeof(addr); while (true) { int new_fd; if ((new_fd = accept(listen_fd, (struct sockaddr *) &addr, &addr_size)) < 0) { printf("Failed to select (%d: %s)\n", new_fd, strerror(errno)); return -1; } std::string host = gethostname(&addr); std::lock_guard<std::mutex> lock(map_mutex); bool whitelist = false; for (const std::string& s : whitelistprefix) if (host.compare(0, s.length(), s) == 0) whitelist = true; if ((clientMap.count(host) && !whitelist) || (host.length() > droppostfix.length() && !host.compare(host.length() - droppostfix.length(), droppostfix.length(), droppostfix))) { if (clientMap.count(host)) { const auto& client = clientMap[host]; if (client->lastDupConnect < (time(NULL) - 60)) { client->lastDupConnect = time(NULL); fprintf(stderr, "%lld: Got duplicate connection from %s (original's disconnect status: %d)\n", (long long) time(NULL), host.c_str(), client->getDisconnectFlags()); } } close(new_fd); } else { if (whitelist) host += ":" + std::to_string(addr.sin6_port); assert(clientMap.count(host) == 0); clientMap[host] = new RelayNetworkClient(new_fd, host, relayBlock, relayTx, connected); fprintf(stderr, "%lld: New connection from %s, have %lu relay clients\n", (long long) time(NULL), host.c_str(), clientMap.size()); } } }
37.994129
173
0.682153
[ "vector" ]
baa9fb87b707c5d6eff7146a1f372f2b298af42e
1,780
hpp
C++
include/BoundingBox.hpp
basticirca/libpcc
307792d24ad75bed70872f0145b121377adae93f
[ "MIT" ]
2
2018-09-22T12:48:18.000Z
2019-04-02T08:55:44.000Z
include/BoundingBox.hpp
basticirca/libpcc
307792d24ad75bed70872f0145b121377adae93f
[ "MIT" ]
null
null
null
include/BoundingBox.hpp
basticirca/libpcc
307792d24ad75bed70872f0145b121377adae93f
[ "MIT" ]
3
2019-05-04T04:21:39.000Z
2020-12-01T00:59:13.000Z
#ifndef LIBPCC_BOUNDING_BOX_HPP #define LIBPCC_BOUNDING_BOX_HPP #include "Vec.hpp" #include "UncompressedVoxel.hpp" /** * Data transfer object encoding a 3D bounding box. */ struct BoundingBox { explicit BoundingBox(float x_min_t=.0f, float x_max_t=.0f, float y_min_t=.0f, float y_max_t=.0f, float z_min_t=.0f, float z_max_t=.0f) : min(x_min_t, y_min_t, z_min_t) , max(x_max_t, y_max_t, z_max_t) {} explicit BoundingBox(const Vec<float>& min_t, const Vec<float>& max_t) : min(min_t) , max(max_t) {} BoundingBox(BoundingBox const& bb) = default; ~BoundingBox() = default; /** * Returns true if given Vec<float> is contained inside * volume defined by this instance. false otherwise. */ bool contains(Vec<float> const& v) const { return v.x > min.x && v.x < max.x && v.y > min.y && v.y < max.y && v.z > min.z && v.z < max.z; } /** * Returns true if given const float[3] is contained inside * volume defined by this instance. false otherwise. */ bool contains(const float v[3]) const { return v[0] > min.x && v[0] < max.x && v[1] > min.y && v[1] < max.y && v[2] > min.z && v[2] < max.z; } /** * Returns true if given UncompressedVoxel is contained inside * volume defined by this instance. false otherwise. */ bool contains(const UncompressedVoxel& v) const { return contains(v.pos); } /** * Returns Vec<float> denoting length of x, y & z - axis * spun by this instance. */ Vec<float> const calcRange() const { return max - min; } Vec<float> min; Vec<float> max; }; #endif //LIBPCC_BOUNDING_BOX_HPP
25.797101
138
0.585393
[ "object", "3d" ]
baad81884dc3efbe46dd3bf4a40381dc7d16129f
27,085
cc
C++
third_party/harfbuzz/src/hb-directwrite.cc
dev-baiqiang/text
a7de699528d0609db24601d41a442e7ac00ff1a1
[ "MIT" ]
1
2021-08-12T00:29:31.000Z
2021-08-12T00:29:31.000Z
third_party/harfbuzz/src/hb-directwrite.cc
dev-baiqiang/text
a7de699528d0609db24601d41a442e7ac00ff1a1
[ "MIT" ]
null
null
null
third_party/harfbuzz/src/hb-directwrite.cc
dev-baiqiang/text
a7de699528d0609db24601d41a442e7ac00ff1a1
[ "MIT" ]
null
null
null
/* * Copyright © 2015-2018 Ebrahim Byagowi * * This is part of HarfBuzz, a text shaping library. * * Permission is hereby granted, without written agreement and without * license or royalty fees, to use, copy, modify, and distribute this * software and its documentation for any purpose, provided that the * above copyright notice and the following two paragraphs appear in * all copies of this software. * * IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES * ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN * IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH * DAMAGE. * * THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND * FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS * ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. */ #include "hb-private.hh" #define HB_SHAPER directwrite #include "hb-shaper-impl-private.hh" #include <DWrite_1.h> #include "hb-directwrite.h" HB_SHAPER_DATA_ENSURE_DEFINE (directwrite, face) HB_SHAPER_DATA_ENSURE_DEFINE (directwrite, font) /* * hb-directwrite uses new/delete syntatically but as we let users * to override malloc/free, we will redefine new/delete so users * won't need to do that by their own. */ void* operator new (size_t size) { return malloc (size); } void* operator new [] (size_t size) { return malloc (size); } void operator delete (void* pointer) { free (pointer); } void operator delete [] (void* pointer) { free (pointer); } /* * DirectWrite font stream helpers */ // This is a font loader which provides only one font (unlike its original design). // For a better implementation which was also source of this // and DWriteFontFileStream, have a look at to NativeFontResourceDWrite.cpp in Mozilla class DWriteFontFileLoader : public IDWriteFontFileLoader { private: IDWriteFontFileStream *mFontFileStream; public: DWriteFontFileLoader (IDWriteFontFileStream *fontFileStream) { mFontFileStream = fontFileStream; } // IUnknown interface IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject) { return S_OK; } IFACEMETHOD_ (ULONG, AddRef) () { return 1; } IFACEMETHOD_ (ULONG, Release) () { return 1; } // IDWriteFontFileLoader methods virtual HRESULT STDMETHODCALLTYPE CreateStreamFromKey (void const* fontFileReferenceKey, uint32_t fontFileReferenceKeySize, OUT IDWriteFontFileStream** fontFileStream) { *fontFileStream = mFontFileStream; return S_OK; } }; class DWriteFontFileStream : public IDWriteFontFileStream { private: uint8_t *mData; uint32_t mSize; public: DWriteFontFileStream (uint8_t *aData, uint32_t aSize) { mData = aData; mSize = aSize; } // IUnknown interface IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject) { return S_OK; } IFACEMETHOD_ (ULONG, AddRef) () { return 1; } IFACEMETHOD_ (ULONG, Release) () { return 1; } // IDWriteFontFileStream methods virtual HRESULT STDMETHODCALLTYPE ReadFileFragment (void const** fragmentStart, UINT64 fileOffset, UINT64 fragmentSize, OUT void** fragmentContext) { // We are required to do bounds checking. if (fileOffset + fragmentSize > mSize) return E_FAIL; // truncate the 64 bit fileOffset to size_t sized index into mData size_t index = static_cast<size_t> (fileOffset); // We should be alive for the duration of this. *fragmentStart = &mData[index]; *fragmentContext = nullptr; return S_OK; } virtual void STDMETHODCALLTYPE ReleaseFileFragment (void* fragmentContext) { } virtual HRESULT STDMETHODCALLTYPE GetFileSize (OUT UINT64* fileSize) { *fileSize = mSize; return S_OK; } virtual HRESULT STDMETHODCALLTYPE GetLastWriteTime (OUT UINT64* lastWriteTime) { return E_NOTIMPL; } }; /* * shaper face data */ struct hb_directwrite_face_data_t { IDWriteFactory *dwriteFactory; IDWriteFontFile *fontFile; IDWriteFontFileStream *fontFileStream; IDWriteFontFileLoader *fontFileLoader; IDWriteFontFace *fontFace; hb_blob_t *faceBlob; }; hb_directwrite_face_data_t * _hb_directwrite_shaper_face_data_create (hb_face_t *face) { hb_directwrite_face_data_t *data = new hb_directwrite_face_data_t; if (unlikely (!data)) return nullptr; // TODO: factory and fontFileLoader should be cached separately IDWriteFactory* dwriteFactory; DWriteCreateFactory ( DWRITE_FACTORY_TYPE_SHARED, __uuidof (IDWriteFactory), (IUnknown**) &dwriteFactory ); HRESULT hr; hb_blob_t *blob = hb_face_reference_blob (face); DWriteFontFileStream *fontFileStream = new DWriteFontFileStream ( (uint8_t *) hb_blob_get_data (blob, nullptr), hb_blob_get_length (blob)); DWriteFontFileLoader *fontFileLoader = new DWriteFontFileLoader (fontFileStream); dwriteFactory->RegisterFontFileLoader (fontFileLoader); IDWriteFontFile *fontFile; uint64_t fontFileKey = 0; hr = dwriteFactory->CreateCustomFontFileReference (&fontFileKey, sizeof (fontFileKey), fontFileLoader, &fontFile); #define FAIL(...) \ HB_STMT_START { \ DEBUG_MSG (DIRECTWRITE, nullptr, __VA_ARGS__); \ return nullptr; \ } HB_STMT_END; if (FAILED (hr)) FAIL ("Failed to load font file from data!"); BOOL isSupported; DWRITE_FONT_FILE_TYPE fileType; DWRITE_FONT_FACE_TYPE faceType; uint32_t numberOfFaces; hr = fontFile->Analyze (&isSupported, &fileType, &faceType, &numberOfFaces); if (FAILED (hr) || !isSupported) FAIL ("Font file is not supported."); #undef FAIL IDWriteFontFace *fontFace; dwriteFactory->CreateFontFace (faceType, 1, &fontFile, 0, DWRITE_FONT_SIMULATIONS_NONE, &fontFace); data->dwriteFactory = dwriteFactory; data->fontFile = fontFile; data->fontFileStream = fontFileStream; data->fontFileLoader = fontFileLoader; data->fontFace = fontFace; data->faceBlob = blob; return data; } void _hb_directwrite_shaper_face_data_destroy (hb_directwrite_face_data_t *data) { if (data->fontFace) data->fontFace->Release (); if (data->fontFile) data->fontFile->Release (); if (data->dwriteFactory) { if (data->fontFileLoader) data->dwriteFactory->UnregisterFontFileLoader (data->fontFileLoader); data->dwriteFactory->Release (); } if (data->fontFileLoader) delete data->fontFileLoader; if (data->fontFileStream) delete data->fontFileStream; if (data->faceBlob) hb_blob_destroy (data->faceBlob); if (data) delete data; } /* * shaper font data */ struct hb_directwrite_font_data_t { }; hb_directwrite_font_data_t * _hb_directwrite_shaper_font_data_create (hb_font_t *font) { if (unlikely (!hb_directwrite_shaper_face_data_ensure (font->face))) return nullptr; hb_directwrite_font_data_t *data = new hb_directwrite_font_data_t; if (unlikely (!data)) return nullptr; return data; } void _hb_directwrite_shaper_font_data_destroy (hb_directwrite_font_data_t *data) { delete data; } /* * shaper shape_plan data */ struct hb_directwrite_shape_plan_data_t {}; hb_directwrite_shape_plan_data_t * _hb_directwrite_shaper_shape_plan_data_create (hb_shape_plan_t *shape_plan HB_UNUSED, const hb_feature_t *user_features HB_UNUSED, unsigned int num_user_features HB_UNUSED, const int *coords HB_UNUSED, unsigned int num_coords HB_UNUSED) { return (hb_directwrite_shape_plan_data_t *) HB_SHAPER_DATA_SUCCEEDED; } void _hb_directwrite_shaper_shape_plan_data_destroy (hb_directwrite_shape_plan_data_t *data HB_UNUSED) { } // Most of TextAnalysis is originally written by Bas Schouten for Mozilla project // but now is relicensed to MIT for HarfBuzz use class TextAnalysis : public IDWriteTextAnalysisSource, public IDWriteTextAnalysisSink { public: IFACEMETHOD (QueryInterface) (IID const& iid, OUT void** ppObject) { return S_OK; } IFACEMETHOD_ (ULONG, AddRef) () { return 1; } IFACEMETHOD_ (ULONG, Release) () { return 1; } // A single contiguous run of characters containing the same analysis // results. struct Run { uint32_t mTextStart; // starting text position of this run uint32_t mTextLength; // number of contiguous code units covered uint32_t mGlyphStart; // starting glyph in the glyphs array uint32_t mGlyphCount; // number of glyphs associated with this run // text DWRITE_SCRIPT_ANALYSIS mScript; uint8_t mBidiLevel; bool mIsSideways; inline bool ContainsTextPosition (uint32_t aTextPosition) const { return aTextPosition >= mTextStart && aTextPosition < mTextStart + mTextLength; } Run *nextRun; }; public: TextAnalysis (const wchar_t* text, uint32_t textLength, const wchar_t* localeName, DWRITE_READING_DIRECTION readingDirection) : mText (text) , mTextLength (textLength) , mLocaleName (localeName) , mReadingDirection (readingDirection) , mCurrentRun (nullptr) { }; ~TextAnalysis () { // delete runs, except mRunHead which is part of the TextAnalysis object for (Run *run = mRunHead.nextRun; run;) { Run *origRun = run; run = run->nextRun; delete origRun; } } STDMETHODIMP GenerateResults (IDWriteTextAnalyzer* textAnalyzer, Run **runHead) { // Analyzes the text using the script analyzer and returns // the result as a series of runs. HRESULT hr = S_OK; // Initially start out with one result that covers the entire range. // This result will be subdivided by the analysis processes. mRunHead.mTextStart = 0; mRunHead.mTextLength = mTextLength; mRunHead.mBidiLevel = (mReadingDirection == DWRITE_READING_DIRECTION_RIGHT_TO_LEFT); mRunHead.nextRun = nullptr; mCurrentRun = &mRunHead; // Call each of the analyzers in sequence, recording their results. if (SUCCEEDED (hr = textAnalyzer->AnalyzeScript (this, 0, mTextLength, this))) *runHead = &mRunHead; return hr; } // IDWriteTextAnalysisSource implementation IFACEMETHODIMP GetTextAtPosition (uint32_t textPosition, OUT wchar_t const** textString, OUT uint32_t* textLength) { if (textPosition >= mTextLength) { // No text at this position, valid query though. *textString = nullptr; *textLength = 0; } else { *textString = mText + textPosition; *textLength = mTextLength - textPosition; } return S_OK; } IFACEMETHODIMP GetTextBeforePosition (uint32_t textPosition, OUT wchar_t const** textString, OUT uint32_t* textLength) { if (textPosition == 0 || textPosition > mTextLength) { // Either there is no text before here (== 0), or this // is an invalid position. The query is considered valid though. *textString = nullptr; *textLength = 0; } else { *textString = mText; *textLength = textPosition; } return S_OK; } IFACEMETHODIMP_ (DWRITE_READING_DIRECTION) GetParagraphReadingDirection () { return mReadingDirection; } IFACEMETHODIMP GetLocaleName (uint32_t textPosition, uint32_t* textLength, wchar_t const** localeName) { return S_OK; } IFACEMETHODIMP GetNumberSubstitution (uint32_t textPosition, OUT uint32_t* textLength, OUT IDWriteNumberSubstitution** numberSubstitution) { // We do not support number substitution. *numberSubstitution = nullptr; *textLength = mTextLength - textPosition; return S_OK; } // IDWriteTextAnalysisSink implementation IFACEMETHODIMP SetScriptAnalysis (uint32_t textPosition, uint32_t textLength, DWRITE_SCRIPT_ANALYSIS const* scriptAnalysis) { SetCurrentRun (textPosition); SplitCurrentRun (textPosition); while (textLength > 0) { Run *run = FetchNextRun (&textLength); run->mScript = *scriptAnalysis; } return S_OK; } IFACEMETHODIMP SetLineBreakpoints (uint32_t textPosition, uint32_t textLength, const DWRITE_LINE_BREAKPOINT* lineBreakpoints) { return S_OK; } IFACEMETHODIMP SetBidiLevel (uint32_t textPosition, uint32_t textLength, uint8_t explicitLevel, uint8_t resolvedLevel) { return S_OK; } IFACEMETHODIMP SetNumberSubstitution (uint32_t textPosition, uint32_t textLength, IDWriteNumberSubstitution* numberSubstitution) { return S_OK; } protected: Run *FetchNextRun (IN OUT uint32_t* textLength) { // Used by the sink setters, this returns a reference to the next run. // Position and length are adjusted to now point after the current run // being returned. Run *origRun = mCurrentRun; // Split the tail if needed (the length remaining is less than the // current run's size). if (*textLength < mCurrentRun->mTextLength) SplitCurrentRun (mCurrentRun->mTextStart + *textLength); else // Just advance the current run. mCurrentRun = mCurrentRun->nextRun; *textLength -= origRun->mTextLength; // Return a reference to the run that was just current. return origRun; } void SetCurrentRun (uint32_t textPosition) { // Move the current run to the given position. // Since the analyzers generally return results in a forward manner, // this will usually just return early. If not, find the // corresponding run for the text position. if (mCurrentRun && mCurrentRun->ContainsTextPosition (textPosition)) return; for (Run *run = &mRunHead; run; run = run->nextRun) if (run->ContainsTextPosition (textPosition)) { mCurrentRun = run; return; } assert (0); // We should always be able to find the text position in one of our runs } void SplitCurrentRun (uint32_t splitPosition) { if (!mCurrentRun) { assert (0); // SplitCurrentRun called without current run // Shouldn't be calling this when no current run is set! return; } // Split the current run. if (splitPosition <= mCurrentRun->mTextStart) { // No need to split, already the start of a run // or before it. Usually the first. return; } Run *newRun = new Run; *newRun = *mCurrentRun; // Insert the new run in our linked list. newRun->nextRun = mCurrentRun->nextRun; mCurrentRun->nextRun = newRun; // Adjust runs' text positions and lengths. uint32_t splitPoint = splitPosition - mCurrentRun->mTextStart; newRun->mTextStart += splitPoint; newRun->mTextLength -= splitPoint; mCurrentRun->mTextLength = splitPoint; mCurrentRun = newRun; } protected: // Input // (weak references are fine here, since this class is a transient // stack-based helper that doesn't need to copy data) uint32_t mTextLength; const wchar_t* mText; const wchar_t* mLocaleName; DWRITE_READING_DIRECTION mReadingDirection; // Current processing state. Run *mCurrentRun; // Output is a list of runs starting here Run mRunHead; }; static inline uint16_t hb_uint16_swap (const uint16_t v) { return (v >> 8) | (v << 8); } static inline uint32_t hb_uint32_swap (const uint32_t v) { return (hb_uint16_swap (v) << 16) | hb_uint16_swap (v >> 16); } /* * shaper */ static hb_bool_t _hb_directwrite_shape_full (hb_shape_plan_t *shape_plan, hb_font_t *font, hb_buffer_t *buffer, const hb_feature_t *features, unsigned int num_features, float lineWidth) { hb_face_t *face = font->face; hb_directwrite_face_data_t *face_data = HB_SHAPER_DATA_GET (face); hb_directwrite_font_data_t *font_data = HB_SHAPER_DATA_GET (font); IDWriteFactory *dwriteFactory = face_data->dwriteFactory; IDWriteFontFace *fontFace = face_data->fontFace; IDWriteTextAnalyzer* analyzer; dwriteFactory->CreateTextAnalyzer (&analyzer); unsigned int scratch_size; hb_buffer_t::scratch_buffer_t *scratch = buffer->get_scratch_buffer (&scratch_size); #define ALLOCATE_ARRAY(Type, name, len) \ Type *name = (Type *) scratch; \ { \ unsigned int _consumed = DIV_CEIL ((len) * sizeof (Type), sizeof (*scratch)); \ assert (_consumed <= scratch_size); \ scratch += _consumed; \ scratch_size -= _consumed; \ } #define utf16_index() var1.u32 ALLOCATE_ARRAY (wchar_t, textString, buffer->len * 2); unsigned int chars_len = 0; for (unsigned int i = 0; i < buffer->len; i++) { hb_codepoint_t c = buffer->info[i].codepoint; buffer->info[i].utf16_index () = chars_len; if (likely (c <= 0xFFFFu)) textString[chars_len++] = c; else if (unlikely (c > 0x10FFFFu)) textString[chars_len++] = 0xFFFDu; else { textString[chars_len++] = 0xD800u + ((c - 0x10000u) >> 10); textString[chars_len++] = 0xDC00u + ((c - 0x10000u) & ((1u << 10) - 1)); } } ALLOCATE_ARRAY (WORD, log_clusters, chars_len); /* Need log_clusters to assign features. */ chars_len = 0; for (unsigned int i = 0; i < buffer->len; i++) { hb_codepoint_t c = buffer->info[i].codepoint; unsigned int cluster = buffer->info[i].cluster; log_clusters[chars_len++] = cluster; if (hb_in_range (c, 0x10000u, 0x10FFFFu)) log_clusters[chars_len++] = cluster; /* Surrogates. */ } // TODO: Handle TEST_DISABLE_OPTIONAL_LIGATURES DWRITE_READING_DIRECTION readingDirection = buffer->props.direction ? DWRITE_READING_DIRECTION_RIGHT_TO_LEFT : DWRITE_READING_DIRECTION_LEFT_TO_RIGHT; /* * There's an internal 16-bit limit on some things inside the analyzer, * but we never attempt to shape a word longer than 64K characters * in a single gfxShapedWord, so we cannot exceed that limit. */ uint32_t textLength = buffer->len; TextAnalysis analysis (textString, textLength, nullptr, readingDirection); TextAnalysis::Run *runHead; HRESULT hr; hr = analysis.GenerateResults (analyzer, &runHead); #define FAIL(...) \ HB_STMT_START { \ DEBUG_MSG (DIRECTWRITE, nullptr, __VA_ARGS__); \ return false; \ } HB_STMT_END; if (FAILED (hr)) FAIL ("Analyzer failed to generate results."); uint32_t maxGlyphCount = 3 * textLength / 2 + 16; uint32_t glyphCount; bool isRightToLeft = HB_DIRECTION_IS_BACKWARD (buffer->props.direction); const wchar_t localeName[20] = {0}; if (buffer->props.language != nullptr) { mbstowcs ((wchar_t*) localeName, hb_language_to_string (buffer->props.language), 20); } // TODO: it does work but doesn't care about ranges DWRITE_TYPOGRAPHIC_FEATURES typographic_features; typographic_features.featureCount = num_features; if (num_features) { typographic_features.features = new DWRITE_FONT_FEATURE[num_features]; for (unsigned int i = 0; i < num_features; ++i) { typographic_features.features[i].nameTag = (DWRITE_FONT_FEATURE_TAG) hb_uint32_swap (features[i].tag); typographic_features.features[i].parameter = features[i].value; } } const DWRITE_TYPOGRAPHIC_FEATURES* dwFeatures = (const DWRITE_TYPOGRAPHIC_FEATURES*) &typographic_features; const uint32_t featureRangeLengths[] = { textLength }; // uint16_t* clusterMap = new uint16_t[textLength]; DWRITE_SHAPING_TEXT_PROPERTIES* textProperties = new DWRITE_SHAPING_TEXT_PROPERTIES[textLength]; retry_getglyphs: uint16_t* glyphIndices = new uint16_t[maxGlyphCount]; DWRITE_SHAPING_GLYPH_PROPERTIES* glyphProperties = new DWRITE_SHAPING_GLYPH_PROPERTIES[maxGlyphCount]; hr = analyzer->GetGlyphs (textString, textLength, fontFace, false, isRightToLeft, &runHead->mScript, localeName, nullptr, &dwFeatures, featureRangeLengths, 1, maxGlyphCount, clusterMap, textProperties, glyphIndices, glyphProperties, &glyphCount); if (unlikely (hr == HRESULT_FROM_WIN32 (ERROR_INSUFFICIENT_BUFFER))) { delete [] glyphIndices; delete [] glyphProperties; maxGlyphCount *= 2; goto retry_getglyphs; } if (FAILED (hr)) FAIL ("Analyzer failed to get glyphs."); float* glyphAdvances = new float[maxGlyphCount]; DWRITE_GLYPH_OFFSET* glyphOffsets = new DWRITE_GLYPH_OFFSET[maxGlyphCount]; /* The -2 in the following is to compensate for possible * alignment needed after the WORD array. sizeof (WORD) == 2. */ unsigned int glyphs_size = (scratch_size * sizeof (int) - 2) / (sizeof (WORD) + sizeof (DWRITE_SHAPING_GLYPH_PROPERTIES) + sizeof (int) + sizeof (DWRITE_GLYPH_OFFSET) + sizeof (uint32_t)); ALLOCATE_ARRAY (uint32_t, vis_clusters, glyphs_size); #undef ALLOCATE_ARRAY int fontEmSize = font->face->get_upem (); if (fontEmSize < 0) fontEmSize = -fontEmSize; if (fontEmSize < 0) fontEmSize = -fontEmSize; double x_mult = (double) font->x_scale / fontEmSize; double y_mult = (double) font->y_scale / fontEmSize; hr = analyzer->GetGlyphPlacements (textString, clusterMap, textProperties, textLength, glyphIndices, glyphProperties, glyphCount, fontFace, fontEmSize, false, isRightToLeft, &runHead->mScript, localeName, &dwFeatures, featureRangeLengths, 1, glyphAdvances, glyphOffsets); if (FAILED (hr)) FAIL ("Analyzer failed to get glyph placements."); IDWriteTextAnalyzer1* analyzer1; analyzer->QueryInterface (&analyzer1); if (analyzer1 && lineWidth) { DWRITE_JUSTIFICATION_OPPORTUNITY* justificationOpportunities = new DWRITE_JUSTIFICATION_OPPORTUNITY[maxGlyphCount]; hr = analyzer1->GetJustificationOpportunities (fontFace, fontEmSize, runHead->mScript, textLength, glyphCount, textString, clusterMap, glyphProperties, justificationOpportunities); if (FAILED (hr)) FAIL ("Analyzer failed to get justification opportunities."); float* justifiedGlyphAdvances = new float[maxGlyphCount]; DWRITE_GLYPH_OFFSET* justifiedGlyphOffsets = new DWRITE_GLYPH_OFFSET[glyphCount]; hr = analyzer1->JustifyGlyphAdvances (lineWidth, glyphCount, justificationOpportunities, glyphAdvances, glyphOffsets, justifiedGlyphAdvances, justifiedGlyphOffsets); if (FAILED (hr)) FAIL ("Analyzer failed to get justified glyph advances."); DWRITE_SCRIPT_PROPERTIES scriptProperties; hr = analyzer1->GetScriptProperties (runHead->mScript, &scriptProperties); if (FAILED (hr)) FAIL ("Analyzer failed to get script properties."); uint32_t justificationCharacter = scriptProperties.justificationCharacter; // if a script justificationCharacter is not space, it can have GetJustifiedGlyphs if (justificationCharacter != 32) { uint16_t* modifiedClusterMap = new uint16_t[textLength]; retry_getjustifiedglyphs: uint16_t* modifiedGlyphIndices = new uint16_t[maxGlyphCount]; float* modifiedGlyphAdvances = new float[maxGlyphCount]; DWRITE_GLYPH_OFFSET* modifiedGlyphOffsets = new DWRITE_GLYPH_OFFSET[maxGlyphCount]; uint32_t actualGlyphsCount; hr = analyzer1->GetJustifiedGlyphs (fontFace, fontEmSize, runHead->mScript, textLength, glyphCount, maxGlyphCount, clusterMap, glyphIndices, glyphAdvances, justifiedGlyphAdvances, justifiedGlyphOffsets, glyphProperties, &actualGlyphsCount, modifiedClusterMap, modifiedGlyphIndices, modifiedGlyphAdvances, modifiedGlyphOffsets); if (hr == HRESULT_FROM_WIN32 (ERROR_INSUFFICIENT_BUFFER)) { maxGlyphCount = actualGlyphsCount; delete [] modifiedGlyphIndices; delete [] modifiedGlyphAdvances; delete [] modifiedGlyphOffsets; maxGlyphCount = actualGlyphsCount; goto retry_getjustifiedglyphs; } if (FAILED (hr)) FAIL ("Analyzer failed to get justified glyphs."); delete [] clusterMap; delete [] glyphIndices; delete [] glyphAdvances; delete [] glyphOffsets; glyphCount = actualGlyphsCount; clusterMap = modifiedClusterMap; glyphIndices = modifiedGlyphIndices; glyphAdvances = modifiedGlyphAdvances; glyphOffsets = modifiedGlyphOffsets; delete [] justifiedGlyphAdvances; delete [] justifiedGlyphOffsets; } else { delete [] glyphAdvances; delete [] glyphOffsets; glyphAdvances = justifiedGlyphAdvances; glyphOffsets = justifiedGlyphOffsets; } delete [] justificationOpportunities; } /* Ok, we've got everything we need, now compose output buffer, * very, *very*, carefully! */ /* Calculate visual-clusters. That's what we ship. */ for (unsigned int i = 0; i < glyphCount; i++) vis_clusters[i] = -1; for (unsigned int i = 0; i < buffer->len; i++) { uint32_t *p = &vis_clusters[log_clusters[buffer->info[i].utf16_index ()]]; *p = MIN (*p, buffer->info[i].cluster); } for (unsigned int i = 1; i < glyphCount; i++) if (vis_clusters[i] == -1) vis_clusters[i] = vis_clusters[i - 1]; #undef utf16_index if (unlikely (!buffer->ensure (glyphCount))) FAIL ("Buffer in error"); #undef FAIL /* Set glyph infos */ buffer->len = 0; for (unsigned int i = 0; i < glyphCount; i++) { hb_glyph_info_t *info = &buffer->info[buffer->len++]; info->codepoint = glyphIndices[i]; info->cluster = vis_clusters[i]; /* The rest is crap. Let's store position info there for now. */ info->mask = glyphAdvances[i]; info->var1.i32 = glyphOffsets[i].advanceOffset; info->var2.i32 = glyphOffsets[i].ascenderOffset; } /* Set glyph positions */ buffer->clear_positions (); for (unsigned int i = 0; i < glyphCount; i++) { hb_glyph_info_t *info = &buffer->info[i]; hb_glyph_position_t *pos = &buffer->pos[i]; /* TODO vertical */ pos->x_advance = x_mult * (int32_t) info->mask; pos->x_offset = x_mult * (isRightToLeft ? -info->var1.i32 : info->var1.i32); pos->y_offset = y_mult * info->var2.i32; } if (isRightToLeft) hb_buffer_reverse (buffer); delete [] clusterMap; delete [] glyphIndices; delete [] textProperties; delete [] glyphProperties; delete [] glyphAdvances; delete [] glyphOffsets; if (num_features) delete [] typographic_features.features; /* Wow, done! */ return true; } hb_bool_t _hb_directwrite_shape (hb_shape_plan_t *shape_plan, hb_font_t *font, hb_buffer_t *buffer, const hb_feature_t *features, unsigned int num_features) { return _hb_directwrite_shape_full (shape_plan, font, buffer, features, num_features, 0); } /* * Public [experimental] API */ hb_bool_t hb_directwrite_shape_experimental_width (hb_font_t *font, hb_buffer_t *buffer, const hb_feature_t *features, unsigned int num_features, float width) { static const char *shapers = "directwrite"; hb_shape_plan_t *shape_plan = hb_shape_plan_create_cached (font->face, &buffer->props, features, num_features, &shapers); hb_bool_t res = _hb_directwrite_shape_full (shape_plan, font, buffer, features, num_features, width); buffer->unsafe_to_break_all (); return res; }
29.731065
97
0.708879
[ "object", "shape" ]
baae309329c017c7ec22627d5a58fc32aa055366
2,071
cpp
C++
libhttp/source/http-server-route.cpp
makefriend8/sdk
7bbf9f1e1403871b75bca4192639f4cecd28c475
[ "MIT" ]
289
2017-02-27T02:31:21.000Z
2022-03-29T16:34:12.000Z
libhttp/source/http-server-route.cpp
makefriend8/sdk
7bbf9f1e1403871b75bca4192639f4cecd28c475
[ "MIT" ]
23
2017-09-09T02:26:24.000Z
2021-12-08T09:01:17.000Z
libhttp/source/http-server-route.cpp
makefriend8/sdk
7bbf9f1e1403871b75bca4192639f4cecd28c475
[ "MIT" ]
209
2015-07-17T04:49:18.000Z
2022-03-31T08:11:49.000Z
#include <string> #include <vector> #include <algorithm> #include "http-route.h" #include "http-server-internal.h" #include "urlcodec.h" struct http_server_route_t { typedef std::pair<std::string, http_server_handler> http_route_t; std::vector<http_route_t> handlers; }; static http_server_route_t& http_server_get_route() { static http_server_route_t router; return router; } static bool http_route_cmp(const http_server_route_t::http_route_t& l, const http_server_route_t::http_route_t& r) { return l.first.length() < r.first.length(); } int http_server_addroute(const char* path, http_server_handler handler) { http_server_route_t& router = http_server_get_route(); router.handlers.push_back(std::make_pair(path, handler)); std::sort(router.handlers.begin(), router.handlers.end(), http_route_cmp); return 0; } int http_server_delroute(const char* path) { http_server_route_t& router = http_server_get_route(); std::vector<http_server_route_t::http_route_t>::iterator it; for (it = router.handlers.begin(); it != router.handlers.end(); ++it) { if (it->first == path) { router.handlers.erase(it); return 0; } } return -1; // not found } int http_server_route(void* http, http_session_t* session, const char* method, const char* path) { char reqpath[1024];//[PATH_MAX]; //struct uri_t* uri = uri_parse(path, (int)strlen(path)); url_decode(path, -1, reqpath, sizeof(reqpath)); //uri_free(uri); //UTF8Decode utf8(reqpath); // TODO: path resolve to fix /rootpath/../pathtosystem -> /pathtosystem //path_resolve(buffer, sizeof(buffer), utf8, CWD, strlen(CWD)); //path_realpath(buffer, live->path); http_server_route_t& router = http_server_get_route(); std::vector<http_server_route_t::http_route_t>::iterator it; for (it = router.handlers.begin(); it != router.handlers.end(); ++it) { if (0 == strncmp(it->first.c_str(), reqpath, it->first.length())) { return it->second(http, session, method, reqpath); } } http_server_set_status_code(session, 404, NULL); return http_server_send(session, "", 0, NULL, NULL); }
27.986486
114
0.728634
[ "vector" ]
baaf7c797065ba1bf955671f546454c19027ac92
9,691
cc
C++
source/common/router/header_parser.cc
rishabhkumar296/envoy
1b040ff0e029059c7aaa6816fccb2419c02675b1
[ "Apache-2.0" ]
27
2017-10-27T03:18:58.000Z
2019-02-07T21:22:20.000Z
source/common/router/header_parser.cc
rishabhkumar296/envoy
1b040ff0e029059c7aaa6816fccb2419c02675b1
[ "Apache-2.0" ]
14
2018-02-16T20:47:38.000Z
2019-01-19T23:03:01.000Z
source/common/router/header_parser.cc
rishabhkumar296/envoy
1b040ff0e029059c7aaa6816fccb2419c02675b1
[ "Apache-2.0" ]
7
2017-11-26T06:26:49.000Z
2019-03-26T03:09:00.000Z
#include "common/router/header_parser.h" #include <ctype.h> #include <memory> #include <string> #include "common/common/assert.h" #include "common/http/headers.h" #include "common/protobuf/utility.h" #include "absl/strings/str_cat.h" #include "absl/strings/str_replace.h" namespace Envoy { namespace Router { namespace { enum class ParserState { Literal, // processing literal data VariableName, // consuming a %VAR% name ExpectArray, // expect starting [ in %VAR([...])% ExpectString, // expect starting " in array of strings String, // consuming an array element string ExpectArrayDelimiterOrEnd, // expect array delimiter (,) or end of array (]) ExpectArgsEnd, // expect closing ) in %VAR(...)% ExpectVariableEnd // expect closing % in %VAR(...)% }; std::string unescape(absl::string_view sv) { return absl::StrReplaceAll(sv, {{"%%", "%"}}); } // Implements a state machine to parse custom headers. Each character of the custom header format // is either literal text (with % escaped as %%) or part of a %VAR% or %VAR(["args"])% expression. // The statement machine does minimal validation of the arguments (if any) and does not know the // names of valid variables. Interpretation of the variable name and arguments is delegated to // StreamInfoHeaderFormatter. HeaderFormatterPtr parseInternal(const envoy::api::v2::core::HeaderValueOption& header_value_option) { const std::string& key = header_value_option.header().key(); // PGV constraints provide this guarantee. ASSERT(!key.empty()); // We reject :path/:authority rewriting, there is already a well defined mechanism to // perform this in the RouteAction, and doing this via request_headers_to_add // will cause us to have to worry about interaction with other aspects of the // RouteAction, e.g. prefix rewriting. We also reject other :-prefixed // headers, since it seems dangerous and there doesn't appear a use case. if (key[0] == ':') { throw EnvoyException(":-prefixed headers may not be modified"); } const bool append = PROTOBUF_GET_WRAPPED_OR_DEFAULT(header_value_option, append, true); absl::string_view format(header_value_option.header().value()); if (format.empty()) { return std::make_unique<PlainHeaderFormatter>("", append); } std::vector<HeaderFormatterPtr> formatters; size_t pos = 0, start = 0; ParserState state = ParserState::Literal; do { const char ch = format[pos]; const bool has_next_ch = (pos + 1) < format.size(); switch (state) { case ParserState::Literal: // Searching for start of %VARIABLE% expression. if (ch != '%') { break; } if (!has_next_ch) { throw EnvoyException( fmt::format("Invalid header configuration. Un-escaped % at position {}", pos)); } if (format[pos + 1] == '%') { // Escaped %, skip next character. pos++; break; } // Un-escaped %: start of variable name. Create a formatter for preceding characters, if // any. state = ParserState::VariableName; if (pos > start) { absl::string_view literal = format.substr(start, pos - start); formatters.emplace_back(new PlainHeaderFormatter(unescape(literal), append)); } start = pos + 1; break; case ParserState::VariableName: // Consume "VAR" from "%VAR%" or "%VAR(...)%" if (ch == '%') { // Found complete variable name, add formatter. formatters.emplace_back( new StreamInfoHeaderFormatter(format.substr(start, pos - start), append)); start = pos + 1; state = ParserState::Literal; break; } if (ch == '(') { // Variable with arguments, search for start of arg array. state = ParserState::ExpectArray; } break; case ParserState::ExpectArray: // Skip over whitespace searching for the start of JSON array args. if (ch == '[') { // Search for first argument string state = ParserState::ExpectString; } else if (!isspace(ch)) { // Consume it as a string argument. state = ParserState::String; } break; case ParserState::ExpectArrayDelimiterOrEnd: // Skip over whitespace searching for a comma or close bracket. if (ch == ',') { state = ParserState::ExpectString; } else if (ch == ']') { state = ParserState::ExpectArgsEnd; } else if (!isspace(ch)) { throw EnvoyException(fmt::format( "Invalid header configuration. Expecting ',', ']', or whitespace after '{}', but " "found '{}'", absl::StrCat(format.substr(start, pos - start)), ch)); } break; case ParserState::ExpectString: // Skip over whitespace looking for the starting quote of a JSON string. if (ch == '"') { state = ParserState::String; } else if (!isspace(ch)) { throw EnvoyException(fmt::format( "Invalid header configuration. Expecting '\"' or whitespace after '{}', but found '{}'", absl::StrCat(format.substr(start, pos - start)), ch)); } break; case ParserState::String: // Consume a JSON string (ignoring backslash-escaped chars). if (ch == '\\') { if (!has_next_ch) { throw EnvoyException(fmt::format( "Invalid header configuration. Un-terminated backslash in JSON string after '{}'", absl::StrCat(format.substr(start, pos - start)))); } // Skip escaped char. pos++; } else if (ch == ')') { state = ParserState::ExpectVariableEnd; } else if (ch == '"') { state = ParserState::ExpectArrayDelimiterOrEnd; } break; case ParserState::ExpectArgsEnd: // Search for the closing paren of a %VAR(...)% expression. if (ch == ')') { state = ParserState::ExpectVariableEnd; } else if (!isspace(ch)) { throw EnvoyException(fmt::format( "Invalid header configuration. Expecting ')' or whitespace after '{}', but found '{}'", absl::StrCat(format.substr(start, pos - start)), ch)); } break; case ParserState::ExpectVariableEnd: // Search for closing % of a %VAR(...)% expression if (ch == '%') { formatters.emplace_back( new StreamInfoHeaderFormatter(format.substr(start, pos - start), append)); start = pos + 1; state = ParserState::Literal; break; } if (!isspace(ch)) { throw EnvoyException(fmt::format( "Invalid header configuration. Expecting '%' or whitespace after '{}', but found '{}'", absl::StrCat(format.substr(start, pos - start)), ch)); } break; default: NOT_REACHED_GCOVR_EXCL_LINE; } } while (++pos < format.size()); if (state != ParserState::Literal) { // Parsing terminated mid-variable. throw EnvoyException( fmt::format("Invalid header configuration. Un-terminated variable expression '{}'", absl::StrCat(format.substr(start, pos - start)))); } if (pos > start) { // Trailing constant data. absl::string_view literal = format.substr(start, pos - start); formatters.emplace_back(new PlainHeaderFormatter(unescape(literal), append)); } ASSERT(formatters.size() > 0); if (formatters.size() == 1) { return std::move(formatters[0]); } return std::make_unique<CompoundHeaderFormatter>(std::move(formatters), append); } } // namespace HeaderParserPtr HeaderParser::configure( const Protobuf::RepeatedPtrField<envoy::api::v2::core::HeaderValueOption>& headers_to_add) { HeaderParserPtr header_parser(new HeaderParser()); for (const auto& header_value_option : headers_to_add) { HeaderFormatterPtr header_formatter = parseInternal(header_value_option); header_parser->headers_to_add_.emplace_back( Http::LowerCaseString(header_value_option.header().key()), std::move(header_formatter)); } return header_parser; } HeaderParserPtr HeaderParser::configure( const Protobuf::RepeatedPtrField<envoy::api::v2::core::HeaderValueOption>& headers_to_add, const Protobuf::RepeatedPtrField<ProtobufTypes::String>& headers_to_remove) { HeaderParserPtr header_parser = configure(headers_to_add); for (const auto& header : headers_to_remove) { // We reject :-prefix (e.g. :path) removal here. This is dangerous, since other aspects of // request finalization assume their existence and they are needed for well-formedness in most // cases. if (header[0] == ':' || Http::LowerCaseString(header).get() == "host") { throw EnvoyException(":-prefixed or host headers may not be removed"); } header_parser->headers_to_remove_.emplace_back(header); } return header_parser; } void HeaderParser::evaluateHeaders(Http::HeaderMap& headers, const StreamInfo::StreamInfo& stream_info) const { // Removing headers in the headers_to_remove_ list first makes // remove-before-add the default behavior as expected by users. for (const auto& header : headers_to_remove_) { headers.remove(header); } for (const auto& formatter : headers_to_add_) { const std::string value = formatter.second->format(stream_info); if (!value.empty()) { if (formatter.second->append()) { headers.addReferenceKey(formatter.first, value); } else { headers.setReferenceKey(formatter.first, value); } } } } } // namespace Router } // namespace Envoy
34.98556
100
0.635332
[ "vector" ]
bab05939b06cd87ab3de4b4eb77d0beaed87eb54
29,870
cpp
C++
modules/ti.UI/win32/win32_user_window.cpp
rlwesq/titanium
b7d072150dc14f4a2a17f92299ff663c83162454
[ "Apache-2.0" ]
1
2016-05-09T09:08:36.000Z
2016-05-09T09:08:36.000Z
modules/ti.UI/win32/win32_user_window.cpp
rlwesq/titanium
b7d072150dc14f4a2a17f92299ff663c83162454
[ "Apache-2.0" ]
null
null
null
modules/ti.UI/win32/win32_user_window.cpp
rlwesq/titanium
b7d072150dc14f4a2a17f92299ff663c83162454
[ "Apache-2.0" ]
null
null
null
/** * Appcelerator Titanium - licensed under the Apache Public License 2 * SEE LICENSE in the root folder for details on the license. * Copyright (c) 2008 Appcelerator, Inc. All Rights Reserved. */ #define _WINSOCKAPI_ #include <kroll/base.h> #include <winsock2.h> #include "win32_user_window.h" #include "webkit_frame_load_delegate.h" #include "webkit_ui_delegate.h" #include "webkit_policy_delegate.h" //#include "webkit_javascript_listener.h" #include "win32_tray_item.h" #include "string_util.h" #include "../url/app_url.h" #include "../url/ti_url.h" #include <cmath> #include <shellapi.h> #include <comutil.h> #include <commdlg.h> #include <shlobj.h> #define STUB() printf("Method is still a stub, %s:%i\n", __FILE__, __LINE__) #define SetFlag(x,flag,b) ((b) ? x |= flag : x &= ~flag) #define UnsetFlag(x,flag) (x &= ~flag)= using namespace ti; // slightly off white, there's probably a better way to do this COLORREF transparencyColor = RGB(0xF9, 0xF9, 0xF9); static void* SetWindowUserData(HWND hwnd, void* user_data) { return reinterpret_cast<void*> (SetWindowLongPtr(hwnd, GWLP_USERDATA, reinterpret_cast<LONG_PTR> (user_data))); } static void* GetWindowUserData(HWND hwnd) { return reinterpret_cast<void*> (GetWindowLongPtr(hwnd, GWLP_USERDATA)); } /*static*/ Win32UserWindow* Win32UserWindow::FromWindow(HWND hWnd) { return reinterpret_cast<Win32UserWindow*> (GetWindowUserData(hWnd)); } const TCHAR *windowClassName = "Win32UserWindow"; /*static*/ void Win32UserWindow::RegisterWindowClass(HINSTANCE hInstance) { static bool class_initialized = false; if (!class_initialized) { //LoadString(hInstance, IDC_TIUSERWINDOW, windowClassName, 100); WNDCLASSEX wcex; wcex.cbSize = sizeof(WNDCLASSEX); wcex.style = CS_HREDRAW | CS_VREDRAW; wcex.lpfnWndProc = Win32UserWindow::WndProc; wcex.cbClsExtra = 0; wcex.cbWndExtra = 0; wcex.hInstance = hInstance; wcex.hIcon = 0; wcex.hIconSm = 0; wcex.hCursor = LoadCursor(hInstance, IDC_ARROW); //wcex.hbrBackground = (HBRUSH)(COLOR_BACKGROUND+1); wcex.hbrBackground = CreateSolidBrush(transparencyColor); wcex.lpszMenuName = ""; wcex.lpszClassName = windowClassName; ATOM result = RegisterClassEx(&wcex); if (result == NULL) { std::cout << "Error Registering Window Class: " << GetLastError() << std::endl; } class_initialized = true; } } void Win32UserWindow::AddMessageHandler(const ValueList& args, SharedValue result) { if (args.size() < 2 || !args.at(0)->IsNumber() || !args.at(1)->IsMethod()) return; long messageCode = (long) args.at(0)->ToDouble(); SharedBoundMethod callback = args.at(1)->ToMethod(); messageHandlers[messageCode] = callback; } /*static*/ LRESULT CALLBACK Win32UserWindow::WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { Win32UserWindow *window = Win32UserWindow::FromWindow(hWnd); if (window && (window->messageHandlers.size() > 0) && (window->messageHandlers.find(message) != window->messageHandlers.end())) { SharedBoundMethod handler = window->messageHandlers[message]; ValueList args; handler->Call(args); return 0; } switch (message) { case WM_DESTROY: return DefWindowProc(hWnd, message, wParam, lParam); case WM_CLOSE: window->Close(); window->FireEvent(CLOSED); return DefWindowProc(hWnd, message, wParam, lParam); case WM_GETMINMAXINFO: { if(window) { MINMAXINFO *mmi = (MINMAXINFO*) lParam; mmi->ptMaxTrackSize.x = window->GetMaxWidth(); mmi->ptMaxTrackSize.y = window->GetMaxHeight(); mmi->ptMinTrackSize.x = window->GetMinWidth(); mmi->ptMinTrackSize.y = window->GetMinHeight(); } } break; case WM_SIZE: if (!window->web_view) break; window->ResizeSubViews(); if (wParam == SIZE_MAXIMIZED) { window->FireEvent(MAXIMIZED); } else if (wParam == SIZE_MINIMIZED) { window->FireEvent(MINIMIZED); } else if (wParam == SIZE_RESTORED) { window->FireEvent(RESIZED); } break; case WM_SETFOCUS: window->FireEvent(FOCUSED); return DefWindowProc(hWnd, message, wParam, lParam); case WM_KILLFOCUS: window->FireEvent(UNFOCUSED); return DefWindowProc(hWnd, message, wParam, lParam); case WM_MOVE: window->FireEvent(MOVED); return DefWindowProc(hWnd, message, wParam, lParam); case WM_SHOWWINDOW: window->FireEvent(((BOOL)wParam) ? SHOWN : HIDDEN); return DefWindowProc(hWnd, message, wParam, lParam); case TI_TRAY_CLICKED: { UINT uMouseMsg = (UINT) lParam; if(uMouseMsg == WM_LBUTTONDOWN) { Win32TrayItem::InvokeLeftClickCallback(hWnd, message, wParam, lParam); } else if (uMouseMsg == WM_RBUTTONDOWN) { Win32TrayItem::ShowTrayMenu(hWnd, message, wParam, lParam); } } break; default: LRESULT handled = Win32MenuItemImpl::handleMenuClick(hWnd, message, wParam, lParam); if(! handled) { return DefWindowProc(hWnd, message, wParam, lParam); } } return 0; } Win32UserWindow::Win32UserWindow(SharedUIBinding binding, WindowConfig* config, SharedUserWindow& parent) : UserWindow(binding, config, parent), script_evaluator(binding->GetHost()), menuBarHandle(NULL), menuInUse(NULL), menu(NULL), contextMenuHandle(NULL), initial_icon(NULL), web_inspector(NULL) { static bool initialized = false; win32_host = static_cast<kroll::Win32Host*>(binding->GetHost()); if (!initialized) { INITCOMMONCONTROLSEX InitCtrlEx; InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX); InitCtrlEx.dwICC = 0x00004000; //ICC_STANDARD_CLASSES; InitCommonControlsEx(&InitCtrlEx); curl_register_local_handler(&Titanium_app_url_handler); curl_register_local_handler(&Titanium_ti_url_handler); addScriptEvaluator(&script_evaluator); } Win32UserWindow::RegisterWindowClass(win32_host->GetInstanceHandle()); window_handle = CreateWindowEx(WS_EX_LAYERED, windowClassName, config->GetTitle().c_str(), WS_CLIPCHILDREN, CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, NULL, NULL, win32_host->GetInstanceHandle(), NULL); if (window_handle == NULL) { std::cout << "Error Creating Window: " << GetLastError() << std::endl; } std::cout << "window_handle = " << (int) window_handle << std::endl; // make our HWND available to 3rd party devs without needing our headers SharedValue windowHandle = Value::NewVoidPtr((void*) window_handle); this->Set("windowHandle", windowHandle); this->SetMethod("addMessageHandler", &Win32UserWindow::AddMessageHandler); SetWindowUserData(window_handle, this); this->ReloadTiWindowConfig(); this->SetupDecorations(false); Bounds b; b.x = config->GetX(); b.y = config->GetY(); b.width = config->GetWidth(); b.height = config->GetHeight(); SetBounds(b); //web_view = WebView::createInstance(); HRESULT hr = CoCreateInstance(CLSID_WebView, 0, CLSCTX_ALL, IID_IWebView, (void**) &web_view); if (FAILED(hr)) { std::cerr << "Error Creating WebView: "; if (hr == REGDB_E_CLASSNOTREG) std::cerr << "REGDB_E_CLASSNOTREG" << std::endl; else if (hr == CLASS_E_NOAGGREGATION) std::cerr << "CLASS_E_NOAGGREGATION" << std::endl; else if (hr == E_NOINTERFACE) std::cerr << "E_NOINTERFACE" << std::endl; else if (hr == E_UNEXPECTED) std::cerr << "E_UNEXPECTED" << std::endl; else if (hr == E_OUTOFMEMORY) std::cerr << "E_OUTOFMEMORY" << std::endl; else if (hr == E_INVALIDARG) std::cerr << "E_INVALIDARG" << std::endl; else fprintf(stderr, "Unknown Error? %x\n", hr); } // set the custom user agent for Titanium double version = host->GetGlobalObject()->Get("version")->ToDouble(); char userAgent[128]; sprintf(userAgent, "%s/%0.2f", PRODUCT_NAME, version); _bstr_t ua(userAgent); web_view->setApplicationNameForUserAgent(ua.copy()); // place our user agent string in the global so we can later use it SharedBoundObject global = host->GetGlobalObject(); _bstr_t uaurl("http://titaniumapp.com"); BSTR uaresp; web_view->userAgentForURL(uaurl.copy(), &uaresp); std::string ua_str = _bstr_t(uaresp); global->Set("userAgent", Value::NewString(ua_str.c_str())); std::cout << "create frame load delegate " << std::endl; frameLoadDelegate = new Win32WebKitFrameLoadDelegate(this); uiDelegate = new Win32WebKitUIDelegate(this); policyDelegate = new Win32WebKitPolicyDelegate(this); std::cout << "set delegates, set host window, webview=" << (int) web_view << std::endl; hr = web_view->setFrameLoadDelegate(frameLoadDelegate); hr = web_view->setUIDelegate(uiDelegate); hr = web_view->setPolicyDelegate(policyDelegate); hr = web_view->setHostWindow((OLE_HANDLE) window_handle); std::cout << "init with frame" << std::endl; RECT client_rect; GetClientRect(window_handle, &client_rect); hr = web_view->initWithFrame(client_rect, 0, 0); AppConfig *appConfig = AppConfig::Instance(); std::string appid = appConfig->GetAppID(); IWebPreferences *prefs = NULL; hr = CoCreateInstance(CLSID_WebPreferences, 0, CLSCTX_ALL, IID_IWebPreferences, (void**) &prefs); if (FAILED(hr) || prefs == NULL) { std::cerr << "Couldn't create the preferences object" << std::endl; } else { _bstr_t pi(appid.c_str()); prefs->initWithIdentifier(pi.copy(), &prefs); prefs->setCacheModel(WebCacheModelDocumentBrowser); prefs->setPlugInsEnabled(true); prefs->setJavaEnabled(true); prefs->setJavaScriptEnabled(true); prefs->setDOMPasteAllowed(true); IWebPreferencesPrivate* privatePrefs = NULL; hr = prefs->QueryInterface(IID_IWebPreferencesPrivate, (void**) &privatePrefs); if (FAILED(hr)) { std::cerr << "Failed to get private preferences" << std::endl; } else { privatePrefs->setDeveloperExtrasEnabled(host->IsDebugMode()); //privatePrefs->setDeveloperExtrasEnabled(host->IsDebugMode()); privatePrefs->setDatabasesEnabled(true); privatePrefs->setLocalStorageEnabled(true); privatePrefs->setOfflineWebApplicationCacheEnabled(true); _bstr_t db_path( FileUtils::GetApplicationDataDirectory(appid).c_str()); privatePrefs->setLocalStorageDatabasePath(db_path.copy()); privatePrefs->Release(); } web_view->setPreferences(prefs); prefs->Release(); } // allow app:// and ti:// to run with local permissions (cross-domain ajax,etc) _bstr_t app_proto("app"); web_view->registerURLSchemeAsLocal(app_proto.copy()); _bstr_t ti_proto("ti"); web_view->registerURLSchemeAsLocal(ti_proto.copy()); IWebViewPrivate *web_view_private; hr = web_view->QueryInterface(IID_IWebViewPrivate, (void**) &web_view_private); hr = web_view_private->viewWindow((OLE_HANDLE*) &view_window_handle); hr = web_view_private->inspector(&web_inspector); if (FAILED(hr) || web_inspector == NULL) { std::cerr << "Couldn't retrieve the web inspector object" << std::endl; } web_view_private->Release(); _bstr_t inspector_url("ti://com.titaniumapp/runtime/inspector/inspector.html"); _bstr_t localized_strings_url("ti://com.titaniumapp/runtime/inspector/localizedStrings.js"); web_inspector->setInspectorURL(inspector_url.copy()); web_inspector->setLocalizedStringsURL(localized_strings_url.copy()); hr = web_view->mainFrame(&web_frame); //web_view->setShouldCloseWithWindow(TRUE); std::cout << "resize subviews" << std::endl; ResizeSubViews(); // ensure we have valid restore values restore_bounds = GetBounds(); restore_styles = GetWindowLong(window_handle, GWL_STYLE); if (this->config->IsFullScreen()) { this->SetFullScreen(true); } if (this->config->IsTopMost() && this->config->IsVisible()) { this->SetTopMost(true); } // set this flag to indicate that when the frame is loaded // we want to show the window - we do this to prevent white screen // while the URL is being fetched this->requires_display = true; // set initial window icon to icon associated with exe file char exePath[MAX_PATH]; GetModuleFileNameA(GetModuleHandle(NULL), exePath, MAX_PATH); initial_icon = ExtractIcon(win32_host->GetInstanceHandle(), exePath, 0); if (initial_icon) { SendMessageA(window_handle, (UINT) WM_SETICON, ICON_BIG, (LPARAM) initial_icon); } } Win32UserWindow::~Win32UserWindow() { if (web_view) web_view->Release(); if (web_frame) web_frame->Release(); } std::string Win32UserWindow::GetTransparencyColor() { char hexColor[7]; sprintf(hexColor, "%2x%2x%2x", (int) GetRValue(transparencyColor), (int) GetGValue(transparencyColor), (int) GetBValue( transparencyColor)); std::string color(hexColor); return color; } void Win32UserWindow::ResizeSubViews() { RECT rcClient; GetClientRect(window_handle, &rcClient); MoveWindow(view_window_handle, 0, 0, rcClient.right, rcClient.bottom, TRUE); } HWND Win32UserWindow::GetWindowHandle() { return this->window_handle; } void Win32UserWindow::Hide() { ShowWindow(window_handle, SW_HIDE); } void Win32UserWindow::Show() { ShowWindow(window_handle, SW_SHOW); } void Win32UserWindow::Focus() { SetFocus(window_handle); } void Win32UserWindow::Unfocus() { //TODO: not sure exactly how to cause kill focus } void Win32UserWindow::Open() { std::cout << "Opening window_handle=" << (int) window_handle << ", view_window_handle=" << (int) view_window_handle << std::endl; UpdateWindow(window_handle); UpdateWindow(view_window_handle); ResizeSubViews(); UserWindow::Open(); SetURL(this->config->GetURL()); if (!this->requires_display) { ShowWindow(window_handle, SW_SHOW); ShowWindow(view_window_handle, SW_SHOW); } FireEvent(OPENED); } void Win32UserWindow::Close() { DestroyWindow(window_handle); UserWindow::Close(); } double Win32UserWindow::GetX() { return GetBounds().x; } void Win32UserWindow::SetX(double x) { this->config->SetX(x); this->SetupPosition(); } double Win32UserWindow::GetY() { return GetBounds().y; } void Win32UserWindow::SetY(double y) { this->config->SetY(y); this->SetupPosition(); } double Win32UserWindow::GetWidth() { return GetBounds().width; } void Win32UserWindow::SetWidth(double width) { this->config->SetWidth(width); this->SetupSize(); } double Win32UserWindow::GetHeight() { return GetBounds().height; } void Win32UserWindow::SetHeight(double height) { this->config->SetHeight(height); this->SetupSize(); } double Win32UserWindow::GetMaxWidth() { return this->config->GetMaxWidth(); } void Win32UserWindow::SetMaxWidth(double width) { this->config->SetMaxWidth(width); } double Win32UserWindow::GetMinWidth() { return this->config->GetMinWidth(); } void Win32UserWindow::SetMinWidth(double width) { this->config->SetMinWidth(width); } double Win32UserWindow::GetMaxHeight() { return this->config->GetMaxHeight(); } void Win32UserWindow::SetMaxHeight(double height) { this->config->SetMaxHeight(height); } double Win32UserWindow::GetMinHeight() { return this->config->GetMinHeight(); } void Win32UserWindow::SetMinHeight(double height) { this->config->SetMinHeight(height); } Bounds Win32UserWindow::GetBounds() { Bounds bounds; RECT rect; GetWindowRect(window_handle, &rect); bounds.x = rect.left; bounds.y = rect.top; bounds.width = rect.right - rect.left; bounds.height = rect.bottom - rect.top; return bounds; } void Win32UserWindow::SetBounds(Bounds bounds) { HWND desktop = GetDesktopWindow(); RECT desktopRect; GetWindowRect(desktop, &desktopRect); if (bounds.x == UserWindow::CENTERED) { bounds.x = (desktopRect.right - bounds.width) / 2; } if (bounds.y == UserWindow::CENTERED) { bounds.y = (desktopRect.bottom - bounds.height) / 2; } UINT flags = SWP_SHOWWINDOW | SWP_NOZORDER; if (!this->config->IsVisible()) { flags = SWP_HIDEWINDOW; } SetWindowPos(window_handle, NULL, bounds.x, bounds.y, bounds.width, bounds.height, flags); } void Win32UserWindow::SetTitle(std::string& title) { this->config->SetTitle(std::string(title)); SetWindowText(window_handle, title.c_str()); } void Win32UserWindow::SetURL(std::string& url_) { std::string url = url_; this->config->SetURL(url); url = AppURLNormalizeURL(url, AppConfig::Instance()->GetAppID()); std::cout << "SetURL: " << url << std::endl; IWebMutableURLRequest* request = 0; std::wstring method =L"GET" ; if (url.length() > 0 && (PathFileExists(url.c_str()) || PathIsUNC(url.c_str()))) { TCHAR fileURL[INTERNET_MAX_URL_LENGTH]; DWORD fileURLLength = sizeof(fileURL)/sizeof(fileURL[0]); if (SUCCEEDED(UrlCreateFromPath(url.c_str(), fileURL, &fileURLLength, 0))) url = fileURL; } std::wstring wurl = UTF8ToWide(url); std::cout << "CoCreateInstance " << std::endl; HRESULT hr = CoCreateInstance(CLSID_WebMutableURLRequest, 0, CLSCTX_ALL, IID_IWebMutableURLRequest, (void**)&request); if (FAILED(hr)) goto exit; std::cout << "initWithURL: " << url << std::endl; hr = request->initWithURL(SysAllocString(wurl.c_str()), WebURLRequestUseProtocolCachePolicy, 60); if (FAILED(hr)) goto exit; std::cout << "set HTTP method" << std::endl; hr = request->setHTTPMethod(SysAllocString(method.c_str())); if (FAILED(hr)) goto exit; std::cout << "load request" << std::endl; hr = web_frame->loadRequest(request); if (FAILED(hr)) goto exit; std::cout << "set focus" << std::endl; SetFocus(view_window_handle); exit: if (request) request->Release(); } #define SetFlag(x,flag,b) ((b) ? x |= flag : x &= ~flag) #define UnsetFlag(x,flag) (x &= ~flag)= #define SetGWLFlag(wnd,flag,b) long window_style = GetWindowLong(wnd, GWL_STYLE);\ SetFlag(window_style, flag, b);\ SetWindowLong(wnd, GWL_STYLE, window_style); void Win32UserWindow::SetResizable(bool resizable) { this->config->SetResizable(resizable); SetGWLFlag(window_handle, WS_OVERLAPPEDWINDOW, this->config->IsUsingChrome() && !resizable); } void Win32UserWindow::SetMaximizable(bool maximizable) { this->config->SetMaximizable(maximizable); this->SetupDecorations(); } void Win32UserWindow::SetMinimizable(bool minimizable) { this->config->SetMinimizable(minimizable); this->SetupDecorations(); } void Win32UserWindow::SetCloseable(bool closeable) { this->config->SetCloseable(closeable); this->SetupDecorations(); } bool Win32UserWindow::IsVisible() { return IsWindowVisible(window_handle); } void Win32UserWindow::SetVisible(bool visible) { this->config->SetVisible(visible); ShowWindow(window_handle, visible ? SW_SHOW : SW_HIDE); } void Win32UserWindow::SetTransparency(double transparency) { this->config->SetTransparency(transparency); SetLayeredWindowAttributes(window_handle, 0, (BYTE) floor(transparency * 255), LWA_ALPHA); } void Win32UserWindow::SetFullScreen(bool fullscreen) { config->SetFullScreen(fullscreen); if (fullscreen) { restore_bounds = GetBounds(); restore_styles = GetWindowLong(window_handle, GWL_STYLE); HMONITOR hmon = MonitorFromWindow(this->window_handle, MONITOR_DEFAULTTONEAREST); MONITORINFO mi; mi.cbSize = sizeof(MONITORINFO); if (GetMonitorInfo(hmon, &mi)) { SetWindowLong(window_handle, GWL_STYLE, 0); SetWindowPos(window_handle, NULL, 0, 0, mi.rcMonitor.right - mi.rcMonitor.left, mi.rcMonitor.bottom - mi.rcMonitor.top, SWP_SHOWWINDOW); } FireEvent(FULLSCREENED); } else { SetWindowLong(window_handle, GWL_STYLE, restore_styles); SetBounds(restore_bounds); FireEvent(UNFULLSCREENED); } } void Win32UserWindow::SetMenu(SharedPtr<MenuItem> value) { SharedPtr<Win32MenuItemImpl> menu = value.cast<Win32MenuItemImpl> (); this->menu = menu; this->SetupMenu(); } SharedPtr<MenuItem> Win32UserWindow::GetMenu() { return this->menu; } void Win32UserWindow::SetContextMenu(SharedPtr<MenuItem> menu) { SharedPtr<Win32MenuItemImpl> menu_new = menu.cast<Win32MenuItemImpl> (); // if it's the same menu, don't do anything if ((menu_new.isNull() && this->contextMenu.isNull()) || (menu_new == this->contextMenu)) { return; } // remove old menu if needed if (!this->contextMenu.isNull()) { this->contextMenu->ClearRealization(contextMenuHandle); this->contextMenuHandle = NULL; } this->contextMenu = menu_new; if (!this->contextMenu.isNull()) { this->contextMenuHandle = this->contextMenu->GetMenu(); } } SharedPtr<MenuItem> Win32UserWindow::GetContextMenu() { return this->contextMenu; } void Win32UserWindow::SetIcon(SharedString icon_path) { this->icon_path = icon_path; this->SetupIcon(); } void Win32UserWindow::SetupIcon() { SharedString icon_path = this->icon_path; if (icon_path.isNull() && !UIModule::GetIcon().isNull()) icon_path = UIModule::GetIcon(); if (icon_path.isNull()) { // need to remove the icon SendMessageA(window_handle, (UINT) WM_SETICON, ICON_BIG, (LPARAM) initial_icon); } else { std::string ext = icon_path->substr(icon_path->length() - 4, 4); if (ext == ".ico") { HANDLE icon = LoadImageA(win32_host->GetInstanceHandle(), icon_path->c_str(), IMAGE_ICON, 32, 32, LR_LOADFROMFILE); SendMessageA(window_handle, (UINT) WM_SETICON, ICON_BIG, (LPARAM) icon); } } } SharedString Win32UserWindow::GetIcon() { return icon_path; } void Win32UserWindow::SetUsingChrome(bool chrome) { this->config->SetUsingChrome(chrome); this->SetupDecorations(); } void Win32UserWindow::SetupDecorations(bool showHide) { long windowStyle = GetWindowLong(this->window_handle, GWL_STYLE); SetFlag(windowStyle, WS_OVERLAPPED, config->IsUsingChrome()); SetFlag(windowStyle, WS_CAPTION, config->IsUsingChrome()); SetFlag(windowStyle, WS_SYSMENU, config->IsUsingChrome() && config->IsCloseable()); SetFlag(windowStyle, WS_BORDER, config->IsUsingChrome()); SetFlag(windowStyle, WS_MAXIMIZEBOX, config->IsMaximizable()); SetFlag(windowStyle, WS_MINIMIZEBOX, config->IsMinimizable()); SetWindowLong(this->window_handle, GWL_STYLE, windowStyle); if (showHide && config->IsVisible()) { ShowWindow(window_handle, SW_HIDE); ShowWindow(window_handle, SW_SHOW); } } void Win32UserWindow::AppMenuChanged() { if (this->menu.isNull()) { this->SetupMenu(); } } void Win32UserWindow::AppIconChanged() { if (this->icon_path.isNull()) { this->SetupIcon(); } } void Win32UserWindow::RemoveMenu() { // Check if we are already using a menu // and the window is initialized. if (this->window_handle != NULL && !this->menuInUse.isNull()) { this->menuInUse->ClearRealization(this->menuBarHandle); ::SetMenu(this->window_handle, NULL); } this->menuInUse = NULL; } void Win32UserWindow::SetupMenu() { SharedPtr<Win32MenuItemImpl> menu = this->menu; SharedPtr<MenuItem> appMenu = UIModule::GetMenu(); // No window menu, try to use the application menu. if (menu.isNull() && !appMenu.isNull()) { menu = appMenu.cast<Win32MenuItemImpl> (); } // Only do this if the menu is actually changing. if (menu == this->menuInUse) return; this->RemoveMenu(); if (!menu.isNull() && this->window_handle) { this->menuBarHandle = menu->GetMenuBar(); ::SetMenu(this->window_handle, menuBarHandle); DrawMenuBar(this->window_handle); } this->menuInUse = menu; } void Win32UserWindow::ReloadTiWindowConfig() { //host->webview()->GetMainFrame()->SetAllowsScrolling(tiWindowConfig->isUsingScrollbars()); //SetWindowText(hWnd, UTF8ToWide(tiWindowConfig->getTitle()).c_str()); long windowStyle = GetWindowLong(this->window_handle, GWL_STYLE); SetFlag(windowStyle, WS_MINIMIZEBOX, config->IsMinimizable()); SetFlag(windowStyle, WS_MAXIMIZEBOX, config->IsMaximizable()); SetFlag(windowStyle, WS_OVERLAPPEDWINDOW, config->IsUsingChrome() && config->IsResizable()); SetFlag(windowStyle, WS_CAPTION, config->IsUsingChrome()); SetWindowLong(this->window_handle, GWL_STYLE, windowStyle); //UINT flags = SWP_NOZORDER | SWP_FRAMECHANGED; //SetLayeredWindowAttributes(hWnd, 0, (BYTE)0, LWA_ALPHA); if (config->GetTransparency() < 1.0) { SetLayeredWindowAttributes(this->window_handle, 0, (BYTE) floor( config->GetTransparency() * 255), LWA_ALPHA); } SetLayeredWindowAttributes(this->window_handle, transparencyColor, 0, LWA_COLORKEY); } // called by frame load delegate to let the window know it's loaded void Win32UserWindow::FrameLoaded() { if (this->requires_display && this->config->IsVisible()) { this->requires_display = false; ShowWindow(window_handle, SW_SHOW); } } bool Win32UserWindow::IsTopMost() { return this->config->IsTopMost(); } void Win32UserWindow::SetTopMost(bool topmost) { this->config->SetTopMost(topmost); if (topmost) { SetWindowPos(window_handle, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); } else { SetWindowPos(window_handle, HWND_NOTOPMOST, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE); } } void Win32UserWindow::SetupPosition() { Bounds b = GetBounds(); b.x = this->config->GetX(); b.y = this->config->GetY(); this->SetBounds(b); } void Win32UserWindow::SetupSize() { Bounds b = GetBounds(); b.width = this->config->GetWidth(); b.height = this->config->GetHeight(); this->SetBounds(b); } void Win32UserWindow::ShowWebInspector() { if (this->web_inspector) { BOOL debug; this->web_inspector->isDebuggingJavaScript(&debug); if (!debug) { web_inspector->toggleDebuggingJavaScript(); } this->web_inspector->show(); } } void Win32UserWindow::OpenFiles(SharedBoundMethod callback, bool multiple, bool files, bool directories, std::string& path, std::string& file, std::vector<std::string>& types) { SharedBoundList results; if (directories) { results = SelectDirectory(multiple, path, file); } else { results = SelectFile(callback, multiple, path, file, types); } ValueList args; args.push_back(Value::NewList(results)); callback->Call(args); } SharedBoundList Win32UserWindow::SelectFile(SharedBoundMethod callback, bool multiple, std::string& path, std::string& file, std::vector< std::string>& types) { //std::string filterName = props->GetString("typesDescription", "Filtered Files"); std::string filterName = "Filtered Files"; std::string filter; if (types.size() > 0) { //"All\0*.*\0Test\0*.TXT\0"; filter.append(filterName); filter.push_back('\0'); for (int i = 0; i < types.size(); i++) { std::string type = types.at(i); //multiple filters: "*.TXT;*.DOC;*.BAK" size_t found = type.find("*."); if (found != 0) { filter.append("*."); } filter.append(type); filter.append(";"); } filter.push_back('\0'); } OPENFILENAME ofn; char filen[8192]; ZeroMemory(&filen, sizeof(filen)); if (file.size() == 0) { filen[0] = '\0'; } else { strcpy(filen, file.c_str()); } // init OPENFILE ZeroMemory(&ofn, sizeof(ofn)); ofn.lStructSize = sizeof(ofn); ofn.hwndOwner = this->window_handle; ofn.lpstrFile = filen; ofn.nMaxFile = sizeof(filen); ofn.lpstrFilter = (filter.length() == 0 ? NULL : filter.c_str()); ofn.nFilterIndex = 1; ofn.lpstrFileTitle = NULL; ofn.nMaxFileTitle = 0; ofn.lpstrInitialDir = (path.length() == 0 ? NULL : path.c_str()); ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_EXPLORER; if (multiple) ofn.Flags |= OFN_ALLOWMULTISELECT; SharedBoundList results = new StaticBoundList(); // display the open dialog box BOOL result = GetOpenFileName(&ofn); if (result) { // if the user selected multiple files, ofn.lpstrFile is a NULL-separated list of filenames // if the user only selected one file, ofn.lpstrFile is a normal string std::vector<std::string> tokens; ParseStringNullSeparated(ofn.lpstrFile, tokens); if (tokens.size() == 1) { results->Append(Value::NewString(tokens.at(0))); } else if (tokens.size() > 1) { std::string directory(tokens.at(0)); for (int i = 1; i < tokens.size(); i++) { std::string n; n.append(directory.c_str()); n.append("\\"); n.append(tokens.at(i).c_str()); results->Append(Value::NewString(n)); } } } else { DWORD error = CommDlgExtendedError(); printf("Error when opening files: %d\n", error); switch(error) { case CDERR_DIALOGFAILURE: printf("CDERR_DIALOGFAILURE\n"); break; case CDERR_FINDRESFAILURE: printf("CDERR_FINDRESFAILURE\n"); break; case CDERR_NOHINSTANCE: printf("CDERR_NOHINSTANCE\n"); break; case CDERR_INITIALIZATION: printf("CDERR_INITIALIZATION\n"); break; case CDERR_NOHOOK: printf("CDERR_NOHOOK\n"); break; case CDERR_LOCKRESFAILURE: printf("CDERR_LOCKRESFAILURE\n"); break; case CDERR_NOTEMPLATE: printf("CDERR_NOTEMPLATE\n"); break; case CDERR_LOADRESFAILURE: printf("CDERR_LOADRESFAILURE\n"); break; case CDERR_STRUCTSIZE: printf("CDERR_STRUCTSIZE\n"); break; case CDERR_LOADSTRFAILURE: printf("CDERR_LOADSTRFAILURE\n"); break; case FNERR_BUFFERTOOSMALL: printf("FNERR_BUFFERTOOSMALL\n"); break; case CDERR_MEMALLOCFAILURE: printf("CDERR_MEMALLOCFAILURE\n"); break; case FNERR_INVALIDFILENAME: printf("FNERR_INVALIDFILENAME\n"); break; case CDERR_MEMLOCKFAILURE: printf("CDERR_MEMLOCKFAILURE\n"); break; case FNERR_SUBCLASSFAILURE: printf("FNERR_SUBCLASSFAILURE\n"); break; } } return results; } SharedBoundList Win32UserWindow::SelectDirectory(bool multiple, std::string& path, std::string& file) { SharedBoundList results = new StaticBoundList(); BROWSEINFO bi = { 0 }; //std::string title("Select a directory"); //bi.lpszTitle = title.c_str(); bi.hwndOwner = this->window_handle; LPITEMIDLIST pidl = SHBrowseForFolder(&bi); if (pidl != 0) { // get folder name TCHAR in_path[MAX_PATH]; if (SHGetPathFromIDList(pidl, in_path)) { results->Append(Value::NewString(std::string(in_path))); } } return results; } void Win32UserWindow::ParseStringNullSeparated(const char *s, std::vector< std::string> &tokens) { std::string token; // input string is expected to be composed of single-NULL-separated tokens, and double-NULL terminated int i = 0; while (true) { char c; c = s[i++]; if (c == '\0') { // finished reading a token, save it in tokens vectory tokens.push_back(token); token.clear(); c = s[i]; // don't increment index because next token loop needs to read this char again // if next char is NULL, then break out of the while loop if (c == '\0') { break; // out of while loop } else { continue; // read next token } } token.push_back(c); } }
28.366572
128
0.71838
[ "object", "vector" ]
bab061a1fd98bc05c91389aea114b10c5a14180b
15,211
cpp
C++
tools/tests/functional/algorithmic_tests/low_level_api/index.cpp
intel/qpl
cdc8442f7a5e7a6ff6eea39c69665e0c5034d85d
[ "MIT" ]
11
2022-02-25T08:20:23.000Z
2022-03-25T08:36:19.000Z
tools/tests/functional/algorithmic_tests/low_level_api/index.cpp
intel/qpl
cdc8442f7a5e7a6ff6eea39c69665e0c5034d85d
[ "MIT" ]
null
null
null
tools/tests/functional/algorithmic_tests/low_level_api/index.cpp
intel/qpl
cdc8442f7a5e7a6ff6eea39c69665e0c5034d85d
[ "MIT" ]
null
null
null
/******************************************************************************* * Copyright (C) 2022 Intel Corporation * * SPDX-License-Identifier: MIT ******************************************************************************/ /* * Intel® Query Processing Library (Intel® QPL) * Tests */ #include <map> #include "../../../common/operation_test.hpp" #include "../../../common/test_cases.hpp" #include "ta_ll_common.hpp" #include "source_provider.hpp" namespace qpl::test { enum CompressionMode { SINGLE_BUF_FIXED, SINGLE_BUF_DYNAMIC, MULT_BUF_FIXED, MULT_BUF_DYNAMIC }; enum BlockUsage { SINGLE_BLOCK, MULTIPLE_BLOCKS }; struct IndexTestCase { BlockUsage block_usage; CompressionMode compression_mode; qpl_mini_block_size mini_block_size; uint32_t chunk_size; bool gzip_mode; std::string file_name; }; std::ostream &operator<<(std::ostream &os, const IndexTestCase &test_case) { std::string block_usage; std::string compression_mode; std::string header = (test_case.gzip_mode) ? "Gzip" : "No header"; if (SINGLE_BLOCK == test_case.block_usage) { block_usage = "Single block"; } else if (MULTIPLE_BLOCKS == test_case.block_usage) { block_usage = "Multiple blocks"; } if (SINGLE_BUF_FIXED == test_case.compression_mode) { compression_mode = "Single buffer fixed"; } else if (SINGLE_BUF_DYNAMIC == test_case.compression_mode) { compression_mode = "Single buffer dynamic"; } else if (MULT_BUF_FIXED == test_case.compression_mode) { compression_mode = "Multiple buffer fixed"; } else if (MULT_BUF_DYNAMIC == test_case.compression_mode) { compression_mode = "Multiple buffer dynamic"; } os << "Header type: " << header << "\n"; os << "Block usage: " << block_usage << "\n"; os << "Compression mode: " << compression_mode << "\n"; os << "Chunk size: " << test_case.chunk_size << "\n"; os << "File : " << test_case.file_name << "\n"; return os; } class IndexTest : public JobFixtureWithTestCases<IndexTestCase> { public: static void SetUpTestSuite() { } static uint32_t UpdateCRC(uint32_t seed, uint8_t byte) { uint64_t rem; uint32_t cvt = ~seed; rem = cvt; const uint32_t polynomial = 0xEDB88320; // IEEE standard rem = rem ^ byte; for (uint32_t i = 0; i < 8u; i++) { rem = (rem & 0x1ULL) ? (rem >> 1) ^ polynomial : (rem >> 1); } return (uint32_t) ~rem; } static uint32_t NumberOfIndexValues(uint32_t buffer_size, uint32_t mini_block_size, uint32_t block_size) { uint32_t result; result = (buffer_size + mini_block_size - 1) / mini_block_size; if (block_size == 0) { result += 2; } else { result += 2 * ((buffer_size + block_size - 1) / block_size); } return result + 1; } testing::AssertionResult GetMiniblock(uint32_t required_number_of_mblocks, uint32_t mblocks_per_block, std::vector<uint8_t> &block_buffer) { qpl_job *inflate_job_ptr; uint32_t job_size; qpl_status status; status = qpl_get_job_size(GetExecutionPath(), &job_size); if (status != QPL_STS_OK) { return testing::AssertionFailure() << "Couldn't get job size"; } auto job_buffer = std::make_unique<uint8_t[]>(job_size); inflate_job_ptr = reinterpret_cast<qpl_job *>(job_buffer.get()); qpl_init_job(GetExecutionPath(), inflate_job_ptr); inflate_job_ptr->op = qpl_op_decompress; uint32_t block_number; uint32_t block_header; uint32_t bit_start; uint32_t bit_end; uint32_t mini_blocks_in_block; uint64_t header_index_start; uint64_t header_index_finish; if (SINGLE_BLOCK == current_test_case.block_usage) { // Current compression is SINGLE_BLOCK block_number = 0; // For single block compression the block number is always 0 mini_blocks_in_block = required_number_of_mblocks; } else { block_number = required_number_of_mblocks / mblocks_per_block; mini_blocks_in_block = required_number_of_mblocks % mblocks_per_block; } block_header = block_number * (mblocks_per_block + 2); header_index_start = index_array[block_header]; header_index_finish = index_array[block_header + 1]; bit_start = (uint32_t) header_index_start; bit_end = (uint32_t) header_index_finish; uint8_t *start = destination.data() + bit_start / 8; // FIRST | NO_BUFFERING means that Intel QPL should only read block header inflate_job_ptr->flags = QPL_FLAG_FIRST | QPL_FLAG_NO_BUFFERING; inflate_job_ptr->ignore_start_bits = bit_start & 7; inflate_job_ptr->ignore_end_bits = 7 & (0 - bit_end); inflate_job_ptr->available_in = ((bit_end + 7) / 8) - (bit_start / 8); inflate_job_ptr->next_out_ptr = block_buffer.data(); inflate_job_ptr->available_out = (uint32_t) block_buffer.size(); inflate_job_ptr->next_in_ptr = start; qpl_status decompression_status = run_job_api(inflate_job_ptr); if (decompression_status != QPL_STS_OK) { return testing::AssertionFailure() << "Restoring mini-block qpl_inflate failed with status " << decompression_status; } inflate_job_ptr->flags = QPL_FLAG_NO_BUFFERING | QPL_FLAG_RND_ACCESS; uint32_t mblock_start_index = (1 + block_number * (mblocks_per_block + 2) + mini_blocks_in_block); bit_start = (uint32_t) (index_array[mblock_start_index]); bit_end = (uint32_t) (index_array[mblock_start_index + 1]); inflate_job_ptr->next_in_ptr = destination.data() + bit_start / 8; inflate_job_ptr->ignore_start_bits = bit_start & 7; inflate_job_ptr->ignore_end_bits = 7 & (0 - bit_end); inflate_job_ptr->available_in = ((bit_end + 7) / 8) - (bit_start / 8); inflate_job_ptr->crc = (uint32_t) ((index_array[mblock_start_index]) >> 32); inflate_job_ptr->next_out_ptr = block_buffer.data(); inflate_job_ptr->available_out = (uint32_t) block_buffer.size(); auto required_crc = (uint32_t) ((index_array[mblock_start_index + 1]) >> 32); decompression_status = run_job_api(inflate_job_ptr); if (decompression_status != QPL_STS_OK) { return testing::AssertionFailure() << "Mini-block decompression failure, status " << decompression_status; } if (required_crc != inflate_job_ptr->crc) { return testing::AssertionFailure() << "Mini-block CRC is wrong, req " << required_crc << " got " << inflate_job_ptr->crc; } return testing::AssertionSuccess(); } std::vector<uint64_t> index_array; std::vector<uint64_t> crc_array; IndexTestCase current_test_case; static std::map<std::string, std::vector<uint8_t>> calgary_sources; void SetUpBeforeIteration() override { current_test_case = GetTestCase(); auto dataset = util::TestEnvironment::GetInstance().GetAlgorithmicDataset(); std::vector<uint8_t> source_ptr = dataset[current_test_case.file_name]; destination.resize(source_ptr.size() * 2); job_ptr->next_in_ptr = source_ptr.data(); job_ptr->available_in = static_cast<uint32_t>(source_ptr.size()); job_ptr->next_out_ptr = destination.data(); job_ptr->available_out = static_cast<uint32_t>(destination.size()); job_ptr->op = qpl_op_compress; job_ptr->mini_block_size = current_test_case.mini_block_size; uint32_t required_indexes = NumberOfIndexValues(job_ptr->available_in, (1u << (job_ptr->mini_block_size + 8u)), (current_test_case.chunk_size == 0) ? job_ptr->available_in : current_test_case.chunk_size); index_array.resize(required_indexes * 20); crc_array.resize(required_indexes * 20); job_ptr->idx_array = (uint64_t *) index_array.data(); job_ptr->idx_max_size = static_cast<uint32_t>(index_array.size()); } void InitializeTestCases() override { uint32_t block_usage = SINGLE_BLOCK; // All single block test cases for (uint32_t mini_block_size = qpl_mblk_size_512; mini_block_size <= qpl_mblk_size_32k; mini_block_size++) { for (uint32_t compression_mode = SINGLE_BUF_FIXED; compression_mode <= SINGLE_BUF_DYNAMIC; compression_mode++) { for (uint32_t gzip_mode = 0; gzip_mode < 2; gzip_mode++) { for (auto &dataset: util::TestEnvironment::GetInstance().GetAlgorithmicDataset().get_data()) { IndexTestCase test_case; test_case.block_usage = (BlockUsage) block_usage; test_case.chunk_size = 0; test_case.mini_block_size = (qpl_mini_block_size) mini_block_size; test_case.compression_mode = (CompressionMode) compression_mode; test_case.gzip_mode = (gzip_mode) != 0; test_case.file_name = dataset.first; AddNewTestCase(test_case); } } } } block_usage = MULTIPLE_BLOCKS; uint32_t mini_block_size = qpl_mblk_size_512; // All multiple blocks test cases for (uint32_t chunk_size : {512u, 1024u, 1024u * 32u}) { for (uint32_t compression_mode = MULT_BUF_FIXED; compression_mode <= MULT_BUF_DYNAMIC; compression_mode++) { for (uint32_t gzip_mode = 0; gzip_mode < 2; gzip_mode++) { for (auto &dataset: util::TestEnvironment::GetInstance().GetAlgorithmicDataset().get_data()) { IndexTestCase test_case; test_case.block_usage = (BlockUsage) block_usage; test_case.chunk_size = chunk_size; test_case.mini_block_size = (qpl_mini_block_size) mini_block_size; test_case.compression_mode = (CompressionMode) compression_mode; test_case.gzip_mode = (gzip_mode) != 0; test_case.file_name = dataset.first; AddNewTestCase(test_case); } } } } } }; QPL_LOW_LEVEL_API_ALGORITHMIC_TEST_TC(deflate_index_extended, PerformOperation, IndexTest) { auto dataset = util::TestEnvironment::GetInstance().GetAlgorithmicDataset(); std::vector<uint8_t> source = dataset[current_test_case.file_name]; uint32_t input_size = static_cast<uint32_t>(source.size()); uint32_t bytes_remain = input_size; uint32_t chunk_size = 0; uint32_t mini_block_size_bytes = (1u << (job_ptr->mini_block_size + 8u)); job_ptr->next_in_ptr = source.data(); job_ptr->available_in = input_size; job_ptr->level = qpl_default_level; job_ptr->flags = QPL_FLAG_FIRST; while (bytes_remain > 0) { switch (current_test_case.compression_mode) { case SINGLE_BUF_FIXED: chunk_size = bytes_remain; break; case SINGLE_BUF_DYNAMIC: job_ptr->flags |= QPL_FLAG_DYNAMIC_HUFFMAN; chunk_size = bytes_remain; break; case MULT_BUF_FIXED: chunk_size = current_test_case.chunk_size; job_ptr->flags |= QPL_FLAG_START_NEW_BLOCK; break; case MULT_BUF_DYNAMIC: chunk_size = current_test_case.chunk_size; job_ptr->flags |= QPL_FLAG_START_NEW_BLOCK; job_ptr->flags |= QPL_FLAG_DYNAMIC_HUFFMAN; break; } if (current_test_case.gzip_mode == 1) { job_ptr->flags |= QPL_FLAG_GZIP_MODE; } if (chunk_size >= bytes_remain) { chunk_size = bytes_remain; job_ptr->flags |= QPL_FLAG_LAST; } job_ptr->available_in = chunk_size; auto result = run_job_api(job_ptr); ASSERT_EQ(QPL_STS_OK, result); bytes_remain -= chunk_size; job_ptr->flags &= ~QPL_FLAG_FIRST; } auto source_it = source.begin(); uint32_t crc_value = 0; uint32_t crc_next; for (crc_next = 0; crc_next <= input_size / mini_block_size_bytes; crc_next++) { for (uint32_t next_byte = 0; next_byte < mini_block_size_bytes; next_byte++) { if (source_it >= source.end()) { // End of input buffer break; } uint32_t dist = std::distance(source_it, source.end()); crc_value = UpdateCRC(crc_value, *source_it++); } crc_array[crc_next] = crc_value; } uint32_t current_number_index = NumberOfIndexValues(input_size, mini_block_size_bytes, (current_test_case.chunk_size == 0) ? job_ptr->available_in : current_test_case.chunk_size); EXPECT_EQ(current_number_index, job_ptr->idx_num_written); uint64_t previous_crc = 0; crc_next = 0; for (uint32_t crc_number = 0; crc_number < job_ptr->idx_num_written; crc_number++) { uint64_t qpl_crc = (index_array[crc_number] >> 32) & 0xFFFFFFFF; if (qpl_crc == previous_crc) { continue; } ASSERT_EQ(qpl_crc, crc_array[crc_next]); previous_crc = crc_array[crc_next++]; } uint32_t block_size = (current_test_case.chunk_size == 0) ? input_size : current_test_case.chunk_size; uint32_t number_of_mini_blocks = (input_size + mini_block_size_bytes - 1) / mini_block_size_bytes; uint32_t mini_blocks_per_block = block_size / mini_block_size_bytes; for (uint32_t current_mini_block = 0; current_mini_block < number_of_mini_blocks; current_mini_block++) { uint32_t next_mini_block = current_mini_block; std::vector<uint8_t> restored_mini_block; restored_mini_block.resize(mini_block_size_bytes * 2); ASSERT_TRUE(GetMiniblock(next_mini_block, mini_blocks_per_block, restored_mini_block)); } } }
38.606599
117
0.590034
[ "vector" ]
bab1f6b3b81fd731625073aa4bbfe5efde3fd6e8
1,336
hpp
C++
include/instance/mob.hpp
filol/Mini-Pokemon-Like
724343c40293661e15255c656f8ec515dfc238a3
[ "MIT" ]
null
null
null
include/instance/mob.hpp
filol/Mini-Pokemon-Like
724343c40293661e15255c656f8ec515dfc238a3
[ "MIT" ]
null
null
null
include/instance/mob.hpp
filol/Mini-Pokemon-Like
724343c40293661e15255c656f8ec515dfc238a3
[ "MIT" ]
null
null
null
/* File: mob.hpp * Author: François Dexemple */ #ifndef MOB_HPP #define MOB_HPP #include <SFML/Graphics.hpp> #include "Concordia_Game/components/animatedentity.hpp" #include "Concordia_Game/components/controlableentity.hpp" #include "Concordia_Game/components/spritedentity.hpp" #include "Concordia_Game/concrete/timehandler.hpp" #include "instance/facingposition.hpp" #include <time.h> #include <stdio.h> #include <stdlib.h> /* * Herited Object from AnimatedEntity(herited from SpritedEntity) and ControlableEntity * */ class Mob : public AnimatedEntity,public ControlableEntity { private: sf::Vector2f movement; sf::Vector2f control; TimeHandler animationTimeHandler; FacingPosition lastFacingPosition; float x ; float y ; float goalX; float goalY; bool goLeft; bool facingUp ; bool facingDown; bool facingLeft ; bool facingRight ; public: //Constructor Mob(sf::Texture const &texture, int spriteX, int spriteY, int spriteW, int spriteH, int animationInitialXPosition, int animationFinalXPosition, int animationInitialYPosition, int animationFinalYPosition, int animationFramesPerSeconds); Mob(); // void controlEntity(sf::Keyboard::Key key, bool release); // void moveCharacter(); void animate(); void AI(); int myrandom(int a, int b); }; #endif
22.266667
115
0.741018
[ "object" ]
3bf8cc13b04ef5771cf1dc4e48ad22547519c6b9
6,455
hpp
C++
rclcpp/include/rclcpp/utilities.hpp
tj10200/rclcpp
1be4d2d91491509a692ae46bafc6968cb9b94bb8
[ "Apache-2.0" ]
null
null
null
rclcpp/include/rclcpp/utilities.hpp
tj10200/rclcpp
1be4d2d91491509a692ae46bafc6968cb9b94bb8
[ "Apache-2.0" ]
null
null
null
rclcpp/include/rclcpp/utilities.hpp
tj10200/rclcpp
1be4d2d91491509a692ae46bafc6968cb9b94bb8
[ "Apache-2.0" ]
null
null
null
// Copyright 2014 Open Source Robotics Foundation, Inc. // // 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. #ifndef RCLCPP__UTILITIES_HPP_ #define RCLCPP__UTILITIES_HPP_ #include <chrono> #include <functional> #include <limits> #include <vector> #include "rclcpp/visibility_control.hpp" #include "rcl/guard_condition.h" #include "rcl/wait.h" #include "rmw/macros.h" #include "rmw/rmw.h" #ifdef ANDROID #include <string> #include <sstream> namespace std { template<typename T> std::string to_string(T value) { std::ostringstream os; os << value; return os.str(); } } #endif namespace rclcpp { /// Initialize communications via the rmw implementation and set up a global signal handler. /** * \param[in] argc Number of arguments. * \param[in] argv Argument vector. Will eventually be used for passing options to rclcpp. */ RCLCPP_PUBLIC void init(int argc, char const * const argv[]); /// Initialize communications via the rmw implementation and set up a global signal handler. /** * Additionally removes ROS-specific arguments from the argument vector. * \param[in] argc Number of arguments. * \param[in] argv Argument vector. * \returns Members of the argument vector that are not ROS arguments. */ RCLCPP_PUBLIC std::vector<std::string> init_and_remove_ros_arguments(int argc, char const * const argv[]); /// Remove ROS-specific arguments from argument vector. /** * Some arguments may not have been intended as ROS arguments. * This function populates a the aruments in a vector. * Since the first argument is always assumed to be a process name, the vector * will always contain the process name. * * \param[in] argc Number of arguments. * \param[in] argv Argument vector. * \returns Members of the argument vector that are not ROS arguments. */ RCLCPP_PUBLIC std::vector<std::string> remove_ros_arguments(int argc, char const * const argv[]); /// Check rclcpp's status. /** \return True if SIGINT hasn't fired yet, false otherwise. */ RCLCPP_PUBLIC bool ok(); /// Notify the signal handler and rmw that rclcpp is shutting down. RCLCPP_PUBLIC void shutdown(); /// Register a function to be called when shutdown is called. /** Calling the callbacks is the last thing shutdown() does. */ RCLCPP_PUBLIC void on_shutdown(std::function<void(void)> callback); /// Get a handle to the rmw guard condition that manages the signal handler. /** * The first time that this function is called for a given wait set a new guard * condition will be created and returned; thereafter the same guard condition * will be returned for the same wait set. This mechanism is designed to ensure * that the same guard condition is not reused across wait sets (e.g., when * using multiple executors in the same process). Will throw an exception if * initialization of the guard condition fails. * \param wait_set Pointer to the rcl_wait_set_t that will be using the * resulting guard condition. * \return Pointer to the guard condition. */ RCLCPP_PUBLIC rcl_guard_condition_t * get_sigint_guard_condition(rcl_wait_set_t * wait_set); /// Release the previously allocated guard condition that manages the signal handler. /** * If you previously called get_sigint_guard_condition() for a given wait set * to get a sigint guard condition, then you should call release_sigint_guard_condition() * when you're done, to free that condition. Will throw an exception if * get_sigint_guard_condition() wasn't previously called for the given wait set. * \param wait_set Pointer to the rcl_wait_set_t that was using the * resulting guard condition. */ RCLCPP_PUBLIC void release_sigint_guard_condition(rcl_wait_set_t * wait_set); /// Use the global condition variable to block for the specified amount of time. /** * \param[in] nanoseconds A std::chrono::duration representing how long to sleep for. * \return True if the condition variable did not timeout. */ RCLCPP_PUBLIC bool sleep_for(const std::chrono::nanoseconds & nanoseconds); /// Safely check if addition will overflow. /** * The type of the operands, T, should have defined * std::numeric_limits<T>::max(), `>`, `<` and `-` operators. * * \param[in] x is the first addend. * \param[in] y is the second addend. * \tparam T is type of the operands. * \return True if the x + y sum is greater than T::max value. */ template<typename T> bool add_will_overflow(const T x, const T y) { return (y > 0) && (x > (std::numeric_limits<T>::max() - y)); } /// Safely check if addition will underflow. /** * The type of the operands, T, should have defined * std::numeric_limits<T>::min(), `>`, `<` and `-` operators. * * \param[in] x is the first addend. * \param[in] y is the second addend. * \tparam T is type of the operands. * \return True if the x + y sum is less than T::min value. */ template<typename T> bool add_will_underflow(const T x, const T y) { return (y < 0) && (x < (std::numeric_limits<T>::min() - y)); } /// Safely check if subtraction will overflow. /** * The type of the operands, T, should have defined * std::numeric_limits<T>::max(), `>`, `<` and `+` operators. * * \param[in] x is the minuend. * \param[in] y is the subtrahend. * \tparam T is type of the operands. * \return True if the difference `x - y` sum is grater than T::max value. */ template<typename T> bool sub_will_overflow(const T x, const T y) { return (y < 0) && (x > (std::numeric_limits<T>::max() + y)); } /// Safely check if subtraction will underflow. /** * The type of the operands, T, should have defined * std::numeric_limits<T>::min(), `>`, `<` and `+` operators. * * \param[in] x is the minuend. * \param[in] y is the subtrahend. * \tparam T is type of the operands. * \return True if the difference `x - y` sum is less than T::min value. */ template<typename T> bool sub_will_underflow(const T x, const T y) { return (y > 0) && (x < (std::numeric_limits<T>::min() + y)); } } // namespace rclcpp #endif // RCLCPP__UTILITIES_HPP_
30.738095
92
0.721766
[ "vector" ]
3bfb7b0eaa0049f40df677fe148a08dc94a3792b
13,193
cc
C++
src/alpakatest/plugin-Test2/alpaka/alpakaAlgo2.cc
alexstrel/pixeltrack-standalone
0b625eef0ef0b5c0f018d9b466457c5575b3442c
[ "Apache-2.0" ]
9
2021-03-02T08:40:18.000Z
2022-01-24T14:31:40.000Z
src/alpakatest/plugin-Test2/alpaka/alpakaAlgo2.cc
alexstrel/pixeltrack-standalone
0b625eef0ef0b5c0f018d9b466457c5575b3442c
[ "Apache-2.0" ]
158
2020-03-22T19:46:40.000Z
2022-03-24T09:51:35.000Z
src/alpakatest/plugin-Test2/alpaka/alpakaAlgo2.cc
alexstrel/pixeltrack-standalone
0b625eef0ef0b5c0f018d9b466457c5575b3442c
[ "Apache-2.0" ]
26
2020-03-20T15:18:41.000Z
2022-03-14T16:58:07.000Z
#include "alpakaAlgo2.h" #include "AlpakaCore/alpakaWorkDivHelper.h" namespace { constexpr unsigned int NUM_VALUES = 1000; struct vectorAdd { template <typename T_Acc, typename T_Data> ALPAKA_FN_ACC void operator()(T_Acc const& acc, const T_Data* __restrict__ a, const T_Data* __restrict__ b, T_Data* __restrict__ c, unsigned int numElements) const { // Global element index in 1D grid. // NB: On GPU, i = threadIndexGlobal = firstElementIdxGlobal = endElementIdxGlobal. cms::alpakatools::for_each_element_in_thread_1D_index_in_grid( acc, numElements, [&](uint32_t i) { c[i] = a[i] + b[i]; }); } }; struct vectorProd { template <typename T_Acc, typename T_Data> ALPAKA_FN_ACC void operator()(T_Acc const& acc, const T_Data* __restrict__ a, const T_Data* __restrict__ b, T_Data* __restrict__ c, unsigned int numElements) const { // Global element index in 2D grid. // NB: On GPU, threadIndexGlobal = firstElementIdxGlobal = endElementIdxGlobal. const auto& [firstElementIdxGlobal, endElementIdxGlobal] = cms::alpakatools::element_index_range_in_grid_truncated(acc, Vec2::all(numElements)); for (uint32_t col = firstElementIdxGlobal[0u]; col < endElementIdxGlobal[0u]; ++col) { for (uint32_t row = firstElementIdxGlobal[1u]; row < endElementIdxGlobal[1u]; ++row) { c[row + numElements * col] = a[row] * b[col]; } } } }; struct matrixMul { template <typename T_Acc, typename T_Data> ALPAKA_FN_ACC void operator()(T_Acc const& acc, const T_Data* __restrict__ a, const T_Data* __restrict__ b, T_Data* __restrict__ c, unsigned int numElements) const { // Global element index in 2D grid. // NB: On GPU, threadIndexGlobal = firstElementIdxGlobal = endElementIdxGlobal. const auto& [firstElementIdxGlobal, endElementIdxGlobal] = cms::alpakatools::element_index_range_in_grid_truncated(acc, Vec2::all(numElements)); for (uint32_t col = firstElementIdxGlobal[0u]; col < endElementIdxGlobal[0u]; ++col) { for (uint32_t row = firstElementIdxGlobal[1u]; row < endElementIdxGlobal[1u]; ++row) { T_Data tmp = 0; for (unsigned int i = 0; i < numElements; ++i) { tmp += a[row + numElements * i] * b[i + numElements * col]; } c[row + numElements * col] = tmp; } } } }; struct matrixMulVector { template <typename T_Acc, typename T_Data> ALPAKA_FN_ACC void operator()(T_Acc const& acc, const T_Data* __restrict__ a, const T_Data* __restrict__ b, T_Data* __restrict__ c, unsigned int numElements) const { // Global element index in 1D grid. // NB: On GPU, threadIndexGlobal = firstElementIdxGlobal = endElementIdxGlobal. cms::alpakatools::for_each_element_in_thread_1D_index_in_grid(acc, numElements, [&](uint32_t row) { T_Data tmp = 0; for (unsigned int i = 0; i < numElements; ++i) { tmp += a[row * numElements + i] * b[i]; } c[row] = tmp; }); } }; /* DEBUG ONLY Obviously not optimized (and contains printf anyway), incorporated to verify results. */ namespace debug { constexpr float TOLERANCE_RATIO = 0.01; struct verifyVectorAdd { template <typename T_Acc, typename T_Data> ALPAKA_FN_ACC void operator()(const T_Acc& acc, const T_Data* result, unsigned int numElements) const { // Global element index in 1D grid. // NB: On GPU, i = threadIndexGlobal = firstElementIdxGlobal = endElementIdxGlobal. cms::alpakatools::for_each_element_in_thread_1D_index_in_grid(acc, numElements, [&](uint32_t i) { // theoreticalResult = i+i^2 = i*(i+1) if (result[i] != i * (i + 1)) { printf("Wrong vectorAdd results, i = %u, c[i] = %f.\n", i, result[i]); } }); } }; struct verifyVectorProd { template <typename T_Acc, typename T_Data> ALPAKA_FN_ACC void operator()(const T_Acc& acc, const T_Data* result, unsigned int numElements) const { const auto& threadIdxGlobal(alpaka::getIdx<alpaka::Grid, alpaka::Threads>(acc)); const uint32_t threadIdxGlobalX(threadIdxGlobal[0u]); const uint32_t threadIdxGlobalY(threadIdxGlobal[1u]); if (threadIdxGlobalX == 0 && threadIdxGlobalY == 0) { for (unsigned int row = 0; row < numElements; ++row) { for (unsigned int col = 0; col < numElements; ++col) { const T_Data theoreticalResult = static_cast<T_Data>(row) * col * col; const T_Data diff = result[row + numElements * col] - theoreticalResult; const T_Data tolerance = theoreticalResult * TOLERANCE_RATIO; if (diff > tolerance || diff < -tolerance) { printf("Wrong vectorProd results, row = %u, col = %u, c[row,col] = %f.\n", row, col, result[row * numElements + col]); } } } } } }; struct verifyMatrixMul { template <typename T_Acc, typename T_Data> ALPAKA_FN_ACC void operator()(const T_Acc& acc, const T_Data* result, unsigned int numElements) const { const auto& threadIdxGlobal(alpaka::getIdx<alpaka::Grid, alpaka::Threads>(acc)); const uint32_t threadIdxGlobalX(threadIdxGlobal[0u]); const uint32_t threadIdxGlobalY(threadIdxGlobal[1u]); if (threadIdxGlobalX == 0 && threadIdxGlobalY == 0) { const T_Data partialtheoreticalResult = static_cast<T_Data>(numElements - 1) * (numElements - 1) * numElements * numElements / 4; for (unsigned int row = 0; row < numElements; ++row) { for (unsigned int col = 0; col < numElements; ++col) { // theoreticalResult = row * col * (col+1) * Sum(k=1 to numElements-1, k^3) const T_Data theoreticalResult = static_cast<T_Data>(row) * col * (col + 1) * partialtheoreticalResult; const T_Data diff = result[row + numElements * col] - theoreticalResult; const T_Data tolerance = theoreticalResult * TOLERANCE_RATIO; if (diff > tolerance || diff < -tolerance) { printf( "Wrong matrix multiplication results, row = %u, col = %u, c[row,col] = %f, theoreticalResult = " "%f.\n", row, col, result[row * numElements + col], theoreticalResult); } } } } } }; struct verifyMatrixMulVector { template <typename T_Acc, typename T_Data> ALPAKA_FN_ACC void operator()(const T_Acc& acc, const T_Data* result, unsigned int numElements) const { const uint32_t threadIdxGlobal(alpaka::getIdx<alpaka::Grid, alpaka::Threads>(acc)[0u]); if (threadIdxGlobal == 0) { const unsigned long int N = numElements - 1; const unsigned long int N2 = N * N; const unsigned long int N3 = N2 * N; const unsigned long int N4 = N2 * N2; const unsigned long int N5 = N4 * N; const T_Data partialtheoreticalResult = static_cast<T_Data>(N2) * (N + 1) * (N + 1) / 4 * ((6 * N5 + 15 * N4 + 10 * N3 - N) / 30 + (N + 1) * (N + 1) * N2 / 2 + N * (N + 1) / 2); for (unsigned int i = 0; i < numElements; ++i) { // theoreticalResult = N^2*(N+1)^2/4 * i * Sum(k=1 to N, k^2*(k+1)^2) const T_Data theoreticalResult = i * partialtheoreticalResult; const T_Data diff = result[i] - theoreticalResult; const T_Data tolerance = theoreticalResult * TOLERANCE_RATIO; if (diff > tolerance || diff < -tolerance) { printf("Wrong matrix-vector multiplication results, i = %u, c[i] = %f, theoreticalResult = %f.\n", i, result[i], theoreticalResult); } } } } }; } // namespace debug } // namespace namespace ALPAKA_ACCELERATOR_NAMESPACE { AlpakaAccBuf2<float> alpakaAlgo2() { const DevHost host(alpaka::getDevByIdx<PltfHost>(0u)); const DevAcc2 device(alpaka::getDevByIdx<PltfAcc2>(0u)); const Vec1 size(NUM_VALUES); Queue queue(device); // Host data auto h_a_buf = alpaka::allocBuf<float, Idx>(host, size); auto h_b_buf = alpaka::allocBuf<float, Idx>(host, size); auto h_a = alpaka::getPtrNative(h_a_buf); auto h_b = alpaka::getPtrNative(h_b_buf); for (auto i = 0U; i < NUM_VALUES; i++) { h_a[i] = i; h_b[i] = i * i; } // Device data auto d_a_buf = alpaka::allocBuf<float, Idx>(device, size); auto d_b_buf = alpaka::allocBuf<float, Idx>(device, size); alpaka::memcpy(queue, d_a_buf, h_a_buf, size); alpaka::memcpy(queue, d_b_buf, h_b_buf, size); auto d_c_buf = alpaka::allocBuf<float, Idx>(device, size); // Prepare 1D workDiv const Vec1& blocksPerGrid1(Vec1::all((NUM_VALUES + 32 - 1) / 32)); const Vec1& threadsPerBlockOrElementsPerThread1(Vec1(32u)); const WorkDiv1& workDiv1 = cms::alpakatools::make_workdiv(blocksPerGrid1, threadsPerBlockOrElementsPerThread1); // VECTOR ADDITION alpaka::enqueue(queue, alpaka::createTaskKernel<Acc1>(workDiv1, vectorAdd(), alpaka::getPtrNative(d_a_buf), alpaka::getPtrNative(d_b_buf), alpaka::getPtrNative(d_c_buf), NUM_VALUES)); // Prepare 2D workDiv const unsigned int blocksPerGridSide = (NUM_VALUES <= 32 ? 1 : std::ceil(NUM_VALUES / 32.)); const Vec2& blocksPerGrid2(Vec2::all(blocksPerGridSide)); const unsigned int threadsPerBlockOrElementsPerThreadSide = (NUM_VALUES < 32 ? NUM_VALUES : 32u); const Vec2& threadsPerBlockOrElementsPerThread2(Vec2::all(threadsPerBlockOrElementsPerThreadSide)); const WorkDiv2& workDiv2 = cms::alpakatools::make_workdiv(blocksPerGrid2, threadsPerBlockOrElementsPerThread2); // Device data const Vec2 sizeSquare(NUM_VALUES, NUM_VALUES); auto d_ma_buf = alpaka::allocBuf<float, Idx>(device, sizeSquare); auto d_mb_buf = alpaka::allocBuf<float, Idx>(device, sizeSquare); auto d_mc_buf = alpaka::allocBuf<float, Idx>(device, sizeSquare); // VECTOR MULTIPLICATION alpaka::enqueue(queue, alpaka::createTaskKernel<Acc2>(workDiv2, vectorProd(), alpaka::getPtrNative(d_a_buf), alpaka::getPtrNative(d_b_buf), alpaka::getPtrNative(d_ma_buf), NUM_VALUES)); alpaka::enqueue(queue, alpaka::createTaskKernel<Acc2>(workDiv2, vectorProd(), alpaka::getPtrNative(d_a_buf), alpaka::getPtrNative(d_c_buf), alpaka::getPtrNative(d_mb_buf), NUM_VALUES)); // MATRIX MULTIPLICATION alpaka::enqueue(queue, alpaka::createTaskKernel<Acc2>(workDiv2, matrixMul(), alpaka::getPtrNative(d_ma_buf), alpaka::getPtrNative(d_mb_buf), alpaka::getPtrNative(d_mc_buf), NUM_VALUES)); // MATRIX - VECTOR MULTIPLICATION alpaka::enqueue(queue, alpaka::createTaskKernel<Acc1>(workDiv1, matrixMulVector(), alpaka::getPtrNative(d_mc_buf), alpaka::getPtrNative(d_b_buf), alpaka::getPtrNative(d_c_buf), NUM_VALUES)); alpaka::wait(queue); return d_mc_buf; } } // namespace ALPAKA_ACCELERATOR_NAMESPACE
45.650519
117
0.544152
[ "vector" ]
3bfc0b89dd1351eebf7344b971e53cefaeb032b7
14,054
cc
C++
io/writer_test.cc
chronos-tachyon/mojo
8d268932dd927a24a2b5de167d63869484e1433a
[ "MIT" ]
3
2017-04-24T07:00:59.000Z
2020-04-13T04:53:06.000Z
io/writer_test.cc
chronos-tachyon/mojo
8d268932dd927a24a2b5de167d63869484e1433a
[ "MIT" ]
1
2017-01-10T04:23:55.000Z
2017-01-10T04:23:55.000Z
io/writer_test.cc
chronos-tachyon/mojo
8d268932dd927a24a2b5de167d63869484e1433a
[ "MIT" ]
1
2020-04-13T04:53:07.000Z
2020-04-13T04:53:07.000Z
// Copyright © 2016 by Donald King <chronos@chronos-tachyon.net> // Available under the MIT License. See LICENSE for details. #include "gtest/gtest.h" #include <fcntl.h> #include <fcntl.h> #include <time.h> #include <unistd.h> #include <unistd.h> #include <condition_variable> #include <mutex> #include <thread> #include "base/cleanup.h" #include "base/logging.h" #include "base/result_testing.h" #include "io/reader.h" #include "io/writer.h" static constexpr char kHex[] = "0123456789abcdef"; static std::string show(const std::vector<char>& vec, std::size_t idx) { std::string out; out.push_back('['); std::size_t i = 0; if (idx >= 5) { out.append("... "); i = idx - 3; } std::size_t j = vec.size(); bool abbrev_end = false; if (vec.size() - idx >= 5) { abbrev_end = true; j = idx + 3; } while (i < j) { unsigned char ch = vec[i]; out.push_back(kHex[(ch >> 4) & 0xfU]); out.push_back(kHex[ch & 0xfU]); out.push_back(' '); ++i; } if (abbrev_end) { out.append("..."); } out.push_back(']'); return out; } static testing::AssertionResult equalvec(const char* aexpr, const char* bexpr, const std::vector<char>& a, const std::vector<char>& b) { if (a.size() != b.size()) { return testing::AssertionFailure() << "lengths differ\n" << "expected: " << aexpr << " (" << a.size() << " bytes)\n" << " actual: " << bexpr << " (" << b.size() << " bytes)"; } for (std::size_t i = 0, n = a.size(); i < n; ++i) { if (a[i] != b[i]) { return testing::AssertionFailure() << "vectors differ\n" << "expected: " << aexpr << " " << show(a, i) << "\n" << " actual: " << bexpr << " " << show(b, i); } } return testing::AssertionSuccess(); } // StringWriter {{{ TEST(StringWriter, Write) { io::Writer w; event::Task task; std::string out; w = io::stringwriter(&out); std::size_t n = 42; w.write(&task, &n, "abc", 3); EXPECT_OK(task.result()); EXPECT_EQ(3U, n); EXPECT_EQ("abc", out); task.reset(); w.write(&task, &n, "defg", 4); EXPECT_OK(task.result()); EXPECT_EQ(4U, n); EXPECT_EQ("abcdefg", out); } TEST(StringWriter, ReadFrom) { io::Reader r; io::Writer w; std::string out; event::Task task; std::size_t copied = 42; r = io::bufferreader("abcdefg", 7); w = io::stringwriter(&out); w.read_from(&task, &copied, 16, r); event::wait(event::system_manager(), &task); EXPECT_NOT_IMPLEMENTED(task.result()); EXPECT_EQ(0U, copied); } TEST(StringWriter, Close) { event::Task task; std::string out; io::Writer w = io::stringwriter(&out); EXPECT_OK(w.close()); EXPECT_FAILED_PRECONDITION(w.close()); } // }}} // BufferWriter {{{ TEST(BufferWriter, Write) { io::Writer w; event::Task task; char buf[16]; std::size_t len = 9001; std::size_t n = 42; w = io::bufferwriter(buf, sizeof(buf), &len); EXPECT_EQ(0U, len); w.write(&task, &n, "abc", 3); EXPECT_OK(task.result()); EXPECT_EQ(3U, n); EXPECT_EQ(3U, len); EXPECT_EQ("abc", std::string(buf, len)); task.reset(); w.write(&task, &n, "defg", 4); EXPECT_OK(task.result()); EXPECT_EQ(4U, n); EXPECT_EQ(7U, len); EXPECT_EQ("abcdefg", std::string(buf, len)); } TEST(BufferWriter, ReadFrom) { io::Reader r; io::Writer w; event::Task task; char buf[16]; std::size_t len = 0; std::size_t copied = 42; r = io::bufferreader("abcdefg", 7); w = io::bufferwriter(buf, sizeof(buf), &len); w.read_from(&task, &copied, sizeof(buf), r); EXPECT_OK(task.result()); EXPECT_EQ(7U, copied); EXPECT_EQ(7U, len); EXPECT_EQ("abcdefg", std::string(buf, len)); r = io::bufferreader("abcdefg", 7); w = io::bufferwriter(buf, sizeof(buf), &len); task.reset(); w.read_from(&task, &copied, 4, r); EXPECT_OK(task.result()); EXPECT_EQ(4U, copied); EXPECT_EQ(4U, len); EXPECT_EQ("abcd", std::string(buf, len)); } TEST(BufferWriter, Close) { event::Task task; std::size_t len = 0; io::Writer w = io::bufferwriter(nullptr, 0, &len); EXPECT_OK(w.close()); EXPECT_FAILED_PRECONDITION(w.close()); } // }}} // IgnoreCloseWriter {{{ TEST(IgnoreCloseWriter, Close) { int n = 0; auto wfn = [](event::Task* task, std::size_t* copied, const char* ptr, std::size_t len, const base::Options& opts) { *copied = 0; if (task->start()) task->finish(base::Result::not_implemented()); }; auto cfn = [&n](event::Task* task, const base::Options& opts) { ++n; if (task->start()) task->finish_ok(); }; io::Writer w; w = io::writer(wfn, cfn); EXPECT_OK(w.close()); EXPECT_EQ(1, n); EXPECT_OK(w.close()); EXPECT_EQ(2, n); w = io::ignore_close(w); EXPECT_OK(w.close()); EXPECT_EQ(2, n); } // }}} // DiscardWriter {{{ TEST(DiscardWriter, Write) { std::size_t total = 42; io::Writer w = io::discardwriter(&total); EXPECT_EQ(0U, total); event::Manager m = event::system_manager(); event::Task task; std::size_t n = 42; w.write(&task, &n, "abcdefgh", 8); event::wait(m, &task); EXPECT_OK(task.result()); EXPECT_EQ(8U, n); EXPECT_EQ(8U, total); task.reset(); w.write(&task, &n, "ijkl", 4); event::wait(m, &task); EXPECT_OK(task.result()); EXPECT_EQ(4U, n); EXPECT_EQ(12U, total); w = io::discardwriter(); total = 0; task.reset(); w.write(&task, &n, "abcdefgh", 8); event::wait(m, &task); EXPECT_OK(task.result()); EXPECT_EQ(8U, n); EXPECT_EQ(0U, total); task.reset(); w.write(&task, &n, "ijkl", 4); event::wait(m, &task); EXPECT_OK(task.result()); EXPECT_EQ(4U, n); EXPECT_EQ(0U, total); } // }}} // FullWriter {{{ TEST(FullWriter, Write) { io::Writer w = io::fullwriter(); event::Manager m = event::system_manager(); event::Task task; std::size_t n = 42; w.write(&task, &n, "", 0); event::wait(m, &task); EXPECT_OK(task.result()); EXPECT_EQ(0U, n); task.reset(); w.write(&task, &n, "a", 1); event::wait(m, &task); EXPECT_RESOURCE_EXHAUSTED(task.result()); EXPECT_EQ(ENOSPC, task.result().errno_value()); EXPECT_EQ(0U, n); } // }}} // FDWriter {{{ static void FDWriterTest(event::ManagerOptions mo) { base::Pipe pipe; ASSERT_OK(base::make_pipe(&pipe)); { auto pair = pipe.write->acquire_fd(); ::fcntl(pair.first, F_SETPIPE_SZ, 4096); } LOG(INFO) << "made pipes"; event::Manager m; ASSERT_OK(event::new_manager(&m, mo)); ASSERT_TRUE(m); base::Options o; o.get<io::Options>().manager = m; LOG(INFO) << "made manager"; struct sigaction sa; ::bzero(&sa, sizeof(sa)); sa.sa_handler = SIG_IGN; ::sigaction(SIGPIPE, &sa, nullptr); std::string expected; std::vector<char> buf; char ch = 'A'; buf.assign(1024, ch); std::size_t wrote = 0; while (true) { auto pair = pipe.write->acquire_fd(); ssize_t n = ::write(pair.first, buf.data(), buf.size()); if (n < 0) { int err_no = errno; if (err_no == EINTR) continue; if (err_no == EPIPE || err_no == EAGAIN || err_no == EWOULDBLOCK) break; auto result = base::Result::from_errno(err_no, "write(2)"); EXPECT_OK(result); break; } wrote += n; expected.append(buf.data(), n); buf.assign(1024, ++ch); } EXPECT_GE(wrote, 1024U); LOG(INFO) << "filled pipe with " << expected.size() << " bytes"; std::mutex mu; std::condition_variable cv; bool ready = false; bool done = false; std::string out; std::thread t([&pipe, &mu, &cv, &ready, &done, &out] { std::unique_lock<std::mutex> lock(mu); while (!ready) cv.wait(lock); LOG(INFO) << "read thread running"; std::vector<char> buf; buf.resize(256); while (true) { auto pair = pipe.read->acquire_fd(); int n = ::read(pair.first, buf.data(), buf.size()); int err_no = errno; pair.second.unlock(); if (n < 0) { if (err_no == EINTR) continue; if (err_no == EAGAIN || err_no == EWOULDBLOCK) { using MS = std::chrono::milliseconds; std::this_thread::sleep_for(MS(1)); continue; } auto result = base::Result::from_errno(err_no, "read(2)"); EXPECT_OK(result); break; } LOG(INFO) << "read " << n << " bytes"; if (n == 0) break; out.append(buf.data(), n); } done = true; cv.notify_all(); }); auto cleanup1 = base::cleanup([&t] { t.join(); }); LOG(INFO) << "spawned thread"; io::Writer w; event::Task task; std::size_t n; w = io::fdwriter(pipe.write); LOG(INFO) << "created fdwriter"; buf.assign(1024, ++ch); w.write(&task, &n, buf.data(), buf.size(), o); LOG(INFO) << "started write"; std::unique_lock<std::mutex> lock(mu); ready = true; cv.notify_all(); lock.unlock(); LOG(INFO) << "unblocked reads"; event::wait(m, &task); expected.append(buf.data(), n); EXPECT_OK(task.result()); EXPECT_EQ(1024U, n); LOG(INFO) << "wrote additional data"; EXPECT_OK(w.close(o)); LOG(INFO) << "closed pipe"; lock.lock(); while (!done) cv.wait(lock); EXPECT_EQ(expected, out); base::log_flush(); } TEST(FDWriter, AsyncWrite) { event::ManagerOptions mo; mo.set_async_mode(); FDWriterTest(std::move(mo)); } TEST(FDWriter, ThreadedWrite) { event::ManagerOptions mo; mo.set_minimal_threaded_mode(); FDWriterTest(std::move(mo)); } // }}} // BufferedWriter {{{ void TestBufferedWriter(const event::ManagerOptions& mo, const char* what) { event::Manager m; ASSERT_OK(event::new_manager(&m, mo)); base::Options o; o.get<io::Options>().manager = m; std::string path; base::FD fd; ASSERT_OK(base::make_tempfile(&path, &fd, "mojo_io_writer_TestBufferedWriter_XXXXXXXX")); auto cleanup = base::cleanup([&path] { ::unlink(path.c_str()); }); LOG(INFO) << "[TestBufferedWriter:" << what << ":begin]"; io::Writer w = io::bufferedwriter(io::fdwriter(fd)); w.write_u8(0x00U, o); w.write_u8(0x7fU, o); w.write_u8(0x80U, o); w.write_u8(0xffU, o); w.write_u16(0x0000U, base::kBigEndian, o); w.write_u16(0x7fffU, base::kBigEndian, o); w.write_u16(0x8000U, base::kBigEndian, o); w.write_u16(0xffffU, base::kBigEndian, o); w.write_u32(0x00000000U, base::kBigEndian, o); w.write_u32(0x7fffffffU, base::kBigEndian, o); w.write_u32(0x80000000U, base::kBigEndian, o); w.write_u32(0xffffffffU, base::kBigEndian, o); w.write_u64(0x0000000000000000ULL, base::kBigEndian, o); w.write_u64(0x7fffffffffffffffULL, base::kBigEndian, o); w.write_u64(0x8000000000000000ULL, base::kBigEndian, o); w.write_u64(0xffffffffffffffffULL, base::kBigEndian, o); w.write_s8(0x01, o); w.write_s8(0x7f, o); w.write_s8(-0x7f, o); w.write_s8(-0x01, o); w.write_s16(0x0001, base::kBigEndian, o); w.write_s16(0x7fff, base::kBigEndian, o); w.write_s16(-0x7fff, base::kBigEndian, o); w.write_s16(-0x0001, base::kBigEndian, o); w.write_s32(0x00000001, base::kBigEndian, o); w.write_s32(0x7fffffff, base::kBigEndian, o); w.write_s32(-0x7fffffff, base::kBigEndian, o); w.write_s32(-0x00000001, base::kBigEndian, o); w.write_s64(0x0000000000000001LL, base::kBigEndian, o); w.write_s64(0x7fffffffffffffffLL, base::kBigEndian, o); w.write_s64(-0x7fffffffffffffffLL, base::kBigEndian, o); w.write_s64(-0x0000000000000001LL, base::kBigEndian, o); w.write_uvarint(0, o); w.write_uvarint(1, o); w.write_uvarint(127, o); w.write_uvarint(128, o); w.write_uvarint(300, o); w.write_uvarint(16383, o); w.write_uvarint(65535, o); w.write_uvarint(0xffffffffffffffffULL, o); w.write_svarint(0, o); w.write_svarint(1, o); w.write_svarint(127, o); w.write_svarint(128, o); w.write_svarint(300, o); w.write_svarint(-1, o); w.write_svarint_zigzag(0, o); w.write_svarint_zigzag(1, o); w.write_svarint_zigzag(2, o); w.write_svarint_zigzag(150, o); w.write_svarint_zigzag(-1, o); w.write_svarint_zigzag(-2, o); w.write_svarint_zigzag(-150, o); w.flush(o); std::vector<char> data; EXPECT_OK(base::seek(nullptr, fd, 0, SEEK_SET)); EXPECT_OK(base::read_all(&data, fd, path.c_str())); constexpr unsigned char kExpected[] = { 0x00, 0x7f, 0x80, 0xff, 0x00, 0x00, 0x7f, 0xff, 0x80, 0x00, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x7f, 0x81, 0xff, 0x00, 0x01, 0x7f, 0xff, 0x80, 0x01, 0xff, 0xff, 0x00, 0x00, 0x00, 0x01, 0x7f, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x01, 0x7f, 0x80, 0x01, 0xac, 0x02, 0xff, 0x7f, 0xff, 0xff, 0x03, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x01, 0x7f, 0x80, 0x01, 0xac, 0x02, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x01, 0x00, 0x02, 0x04, 0xac, 0x02, 0x01, 0x03, 0xab, 0x02, }; const char* p = reinterpret_cast<const char*>(&kExpected); std::vector<char> expected(p, p + sizeof(kExpected)); EXPECT_PRED_FORMAT2(equalvec, expected, data); LOG(INFO) << "[TestBufferedWriter:" << what << ":end]"; EXPECT_OK(fd->close()); m.shutdown(); cleanup.run(); base::log_flush(); } TEST(BufferedWriter, Async) { event::ManagerOptions mo; mo.set_async_mode(); TestBufferedWriter(mo, "async"); } TEST(BufferedWriter, Threaded) { event::ManagerOptions mo; mo.set_threaded_mode(); mo.set_num_pollers(2); mo.dispatcher().set_num_workers(2); TestBufferedWriter(mo, "threaded"); } // }}} static void init() __attribute__((constructor)); static void init() { base::log_stderr_set_level(VLOG_LEVEL(6)); }
25.552727
79
0.614274
[ "vector" ]
3bfcc8d291c8abfb2a8319b0db622314209efd92
5,493
cxx
C++
Testing/Code/Review/itkDirectFourierReconstructionImageToImageFilterTest.cxx
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
1
2018-04-15T13:32:43.000Z
2018-04-15T13:32:43.000Z
Testing/Code/Review/itkDirectFourierReconstructionImageToImageFilterTest.cxx
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
null
null
null
Testing/Code/Review/itkDirectFourierReconstructionImageToImageFilterTest.cxx
kiranhs/ITKv4FEM-Kiran
0e4ab3b61b5fc4c736f04a73dd19e41390f20152
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Insight Segmentation & Registration Toolkit Module: itkDirectFourierReconstructionImageToImageFilterTest.cxx Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) Insight Software Consortium. All rights reserved. See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #if defined(_MSC_VER) #pragma warning ( disable : 4786 ) #endif #include "itkImage.h" #include "itkImageFileReader.h" #include "itkRecursiveGaussianImageFilter.h" #include "itkRescaleIntensityImageFilter.h" #include "itkRegionOfInterestImageFilter.h" #include "itkImageFileWriter.h" #include "itkCommand.h" #include "itkDirectFourierReconstructionImageToImageFilter.h" typedef double InternalPixelType; typedef short int OutputPixelType; typedef itk::Image< OutputPixelType, 3 > OutputImageType; typedef itk::DirectFourierReconstructionImageToImageFilter< InternalPixelType, InternalPixelType > ReconstructionFilterType; typedef ReconstructionFilterType::OutputImageType InternalImageType; typedef itk::RecursiveGaussianImageFilter< InternalImageType, InternalImageType > SmootherType; typedef itk::RescaleIntensityImageFilter< InternalImageType, OutputImageType > RescalerType; typedef itk::RegionOfInterestImageFilter< OutputImageType, OutputImageType > ROIFilterType; typedef itk::ImageFileReader< InternalImageType > ReaderType; typedef itk::ImageFileWriter< OutputImageType > WriterType; class CommandProgressUpdate : public itk::Command { public: typedef CommandProgressUpdate Self; typedef itk::Command Superclass; typedef itk::SmartPointer< Self > Pointer; itkNewMacro( Self ); protected: CommandProgressUpdate() {}; // purposely not implemented typedef const ReconstructionFilterType * ReconstructionFilterPointer; void Execute(itk::Object * caller, const itk::EventObject & event ) { Execute( ( const itk::Object * )caller, event); } void Execute( const itk::Object * caller, const itk::EventObject & event ) { ReconstructionFilterPointer reconstructor = dynamic_cast< ReconstructionFilterPointer >( caller ); if ( ! itk::ProgressEvent().CheckEvent( &event ) ) { return; } std::cout << (int)( 100 * reconstructor->GetProgress() ) << "%" << std::endl; } }; int itkDirectFourierReconstructionImageToImageFilterTest (int argc, char * argv[] ) { if ( argc != 18) { std::cerr << "Wrong number of input arguments" << std::endl; std::cerr << "Usage : " << std::endl << "\t"; std::cerr << argv[0] << " input output r_dir z_dir alpha_dir nz ng fc nb alpha_range x y z sx sy sz sigma" << std::endl; return 1; } ReaderType::Pointer reader = ReaderType::New(); reader->SetFileName( argv[1] ); SmootherType::Pointer smoother = SmootherType::New(); smoother->SetInput( reader->GetOutput() ); smoother->SetSigma( atof( argv[17] ) ); smoother->SetDirection( atoi( argv[3] ) ); ReconstructionFilterType::Pointer reconstruct = ReconstructionFilterType::New(); if ( atof( argv[17] ) == 0 ) { reconstruct->SetInput( reader->GetOutput() ); } else { reconstruct->SetInput( smoother->GetOutput() ); } reconstruct->SetRDirection( atoi( argv[3] ) ); reconstruct->SetZDirection( atoi( argv[4] ) ); reconstruct->SetAlphaDirection( atoi( argv[5] ) ); reconstruct->SetZeroPadding( atoi( argv[6] ) ); reconstruct->SetOverSampling( atoi( argv[7] ) ); reconstruct->SetCutoff( atof( argv[8] ) ); reconstruct->SetRadialSplineOrder( atoi( argv[9] ) ); reconstruct->SetAlphaRange( atoi( argv[10] ) ); CommandProgressUpdate::Pointer observer = CommandProgressUpdate::New(); reconstruct->AddObserver( itk::ProgressEvent(), observer ); RescalerType::Pointer rescaler = RescalerType::New(); rescaler->SetInput( reconstruct->GetOutput() ); rescaler->SetOutputMinimum( itk::NumericTraits< OutputPixelType >::min() ); rescaler->SetOutputMaximum( itk::NumericTraits< OutputPixelType >::max() ); ROIFilterType::Pointer ROIFilter = ROIFilterType::New(); ROIFilter->SetInput( rescaler->GetOutput() ); ROIFilterType::IndexType start; ROIFilterType::SizeType size; start[0] = atoi( argv[11] ); start[1] = atoi( argv[12] ); start[2] = atoi( argv[13] ); size[0] = atoi( argv[14] ); size[1] = atoi( argv[15] ); size[2] = atoi( argv[16] ); ROIFilterType::RegionType requestedRegion; requestedRegion.SetIndex( start ); requestedRegion.SetSize( size ); ROIFilter->SetRegionOfInterest( requestedRegion ); WriterType::Pointer writer = WriterType::New(); writer->SetFileName( argv[2] ); writer->UseCompressionOn( ); writer->SetInput( ROIFilter->GetOutput() ); try { writer->Update(); } catch ( itk::ExceptionObject err ) { std::cerr << "An error occurred somewhere:" << std::endl; std::cerr << err << std::endl; return 2; } std::cout << "Done" << std::endl; std::cout << reconstruct << std::endl; return 0; } // main
30.348066
124
0.672492
[ "object" ]
3bfed936cc3b1629057d7769d6a7fe65b5fd46ff
12,971
cpp
C++
tests/gtests/api/test_memory_desc_ops.cpp
JackAKirk/oneDNN
432c3f0c1c265a0fa96aa46c256d150ea670eb5a
[ "Apache-2.0" ]
1,327
2018-01-25T21:23:47.000Z
2020-04-03T09:39:30.000Z
tests/gtests/api/test_memory_desc_ops.cpp
JackAKirk/oneDNN
432c3f0c1c265a0fa96aa46c256d150ea670eb5a
[ "Apache-2.0" ]
583
2020-04-04T02:37:25.000Z
2022-03-31T00:12:03.000Z
tests/gtests/api/test_memory_desc_ops.cpp
JackAKirk/oneDNN
432c3f0c1c265a0fa96aa46c256d150ea670eb5a
[ "Apache-2.0" ]
365
2018-01-29T16:12:36.000Z
2020-04-03T08:32:27.000Z
/******************************************************************************* * Copyright 2020 Intel Corporation * * 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 <cstring> #include <memory> #include <vector> #include "dnnl_test_common.hpp" #include "gtest/gtest.h" #include "oneapi/dnnl/dnnl.hpp" #define DEBUG_TEST_MEMORY_DESC_OPS_CPP 0 namespace dnnl { namespace memory_desc_ops { namespace debug { #if DEBUG_TEST_MEMORY_DESC_OPS_CPP template <typename T> void print_vec(const char *str, const T *vec, int size) { printf("%s", str); for (int d = 0; d < size; ++d) printf("%d ", (int)vec[d]); printf("\n"); } void print_md(const char *str, const dnnl_memory_desc_t &md) { const auto &o_bd = md.format_desc.blocking; printf("%s\n", str); print_vec("\tdims : ", md.dims, md.ndims); print_vec("\tpdims: ", md.padded_dims, md.ndims); print_vec("\toffs : ", md.padded_offsets, md.ndims); print_vec("\tstrs : ", o_bd.strides, md.ndims); printf("\t\tnblks : %d\n", o_bd.inner_nblks); print_vec("\t\tidxs : ", o_bd.inner_idxs, o_bd.inner_nblks); print_vec("\t\tblks : ", o_bd.inner_blks, o_bd.inner_nblks); } #else // DEBUG_TEST_MEMORY_DESC_OPS_CPP template <typename T> void print_vec(const char *, const T *, int) {} void print_md(const char *, const dnnl_memory_desc_t &) {} #endif // DEBUG_TEST_MEMORY_DESC_OPS_CPP void print_md(const char *str, const memory::desc &md) { print_md(str, md.data); } } // namespace debug // A proxy to memory::desc with fixed data type (f32) struct memory_desc_proxy_t { memory::desc md; memory_desc_proxy_t() = default; memory_desc_proxy_t(const memory::desc &md) : md(md) {} memory_desc_proxy_t(const memory::dims &dims, memory::format_tag tag) : md(dims, memory::data_type::f32, tag) {} memory_desc_proxy_t(const memory::dims &dims, const memory::dims &strides) : md(dims, memory::data_type::f32, strides) {} memory_desc_proxy_t(const memory::dims &dims, const memory::dims &strides, const memory::dims &padded_dims) : md(dims, memory::data_type::f32, strides) { for (int d = 0; d < md.data.ndims; ++d) md.data.padded_dims[d] = padded_dims[d]; } memory_desc_proxy_t(const memory::dims &dims, memory::format_kind fmt_kind) : md(dims, memory::data_type::f32, memory::format_tag::any) { md.data.format_kind = static_cast<dnnl_format_kind_t>(fmt_kind); } }; enum test_direction_t { BI_DIRECTION = 0 /* default */, UNI_DIRECTION = 1 }; namespace properties { using fmt = dnnl::memory::format_tag; TEST(memory_desc_properties_test, TestMemoryDescSize) { auto md1_simple = memory_desc_proxy_t {{1, 1, 1, 1}, {1, 1, 1, 1}}.md; auto md1_strided = memory_desc_proxy_t {{1, 1, 1, 1}, {8, 4, 2, 1}}.md; auto md2_blocked = memory_desc_proxy_t {{1, 4, 1, 1}, fmt::nChw8c}.md; ASSERT_EQ(md1_simple, md1_strided); ASSERT_NE(md2_blocked, md1_simple); ASSERT_NE(md2_blocked, md1_strided); ASSERT_EQ(md1_simple.get_size(), 1 * sizeof(float)); ASSERT_EQ(md1_strided.get_size(), 1 * sizeof(float)); ASSERT_EQ(md2_blocked.get_size(), 8 * sizeof(float)); } } // namespace properties namespace reshape { struct params_t { memory_desc_proxy_t in; memory_desc_proxy_t out; test_direction_t test_direction; dnnl_status_t expected_status; }; class reshape_test_t : public ::testing::TestWithParam<params_t> { protected: void Test(const memory::desc &in_md, const memory::desc &out_md) { memory::desc get_out_md = in_md.reshape(out_md.dims()); debug::print_md("in_md", in_md); debug::print_md("out_md", get_out_md); debug::print_md("expect_out_md", out_md); ASSERT_EQ(get_out_md, out_md); } }; TEST_P(reshape_test_t, TestsReshape) { params_t p = ::testing::TestWithParam<decltype(p)>::GetParam(); catch_expected_failures([=]() { Test(p.in.md, p.out.md); }, p.expected_status != dnnl_success, p.expected_status); if (p.test_direction == UNI_DIRECTION) return; catch_expected_failures([=]() { Test(p.out.md, p.in.md); }, p.expected_status != dnnl_success, p.expected_status); } using fmt = dnnl::memory::format_tag; // clang-format off auto cases_expect_to_fail = ::testing::Values( // volume mismatch params_t {{{2, 2, 1, 1}, fmt::abcd}, {{2, 2, 2, 1, 1}, fmt::abcde}, BI_DIRECTION, dnnl_invalid_arguments}, // volume mismatch params_t {{{2, 1}, {1, 1}}, {{2, 1, 2}, {2, 2, 1}}, BI_DIRECTION, dnnl_invalid_arguments}, // volume mismatch params_t {{{6, 2}, fmt::ab}, {{6}, fmt::a}, BI_DIRECTION, dnnl_invalid_arguments}, // joining axes are not contiguous in memory (`cdab` would be oK) params_t {{{2, 3, 0, 2}, fmt::cdba}, {{6, 0, 2}, fmt::bca}, UNI_DIRECTION, dnnl_invalid_arguments}, // joining axes are not contiguous in memory params_t {{{6, 2}, fmt::ba}, {{12}, fmt::a}, UNI_DIRECTION, dnnl_invalid_arguments}, // joining axes are not contiguous in memory (strides {2, 1} would be oK) params_t {{{6, 2}, {3, 1}}, {{12}, fmt::a}, UNI_DIRECTION, dnnl_invalid_arguments}, // removing an axis of size `1` that has padding is not allowed params_t {{{6, 1, 2}, {4, 2, 1}, {6, 2, 2}}, {{6, 2}, fmt::any}, UNI_DIRECTION, dnnl_invalid_arguments}, // joining axes where one has padding is not allowed params_t {{{6, 2, 2}, {6, 2, 1}, {6, 3, 2}}, {{6, 4}, fmt::any}, UNI_DIRECTION, dnnl_invalid_arguments}, // splitting an axis that has padding is not allowed params_t {{{6}, {1}, {12}}, {{2, 3}, fmt::any}, UNI_DIRECTION, dnnl_invalid_arguments}, // joining axes are not contiguous (partially, due to the blocking) params_t {{{2, 8, 3, 4}, fmt::aBcd8b}, {{2, 8 * 3 * 4}, fmt::ab}, UNI_DIRECTION, dnnl_invalid_arguments}, // nothing can be done with zero memory desc params_t {{}, {}, UNI_DIRECTION, dnnl_invalid_arguments}, // invalid format kind params_t {{{2, 2, 1, 1}, memory::format_kind::wino}, {{2, 2}, fmt::any}, UNI_DIRECTION, dnnl_invalid_arguments}, // invalid format kind params_t {{{2, 2, 1, 1}, memory::format_kind::undef}, {{2, 2}, fmt::any}, UNI_DIRECTION, dnnl_invalid_arguments}, // run-time dims are not supported params_t {{{DNNL_RUNTIME_DIM_VAL}, {1}}, {{DNNL_RUNTIME_DIM_VAL}, {1}}, UNI_DIRECTION, dnnl_invalid_arguments} ); auto cases_zero_dim = ::testing::Values( params_t {{{2, 0, 2}, fmt::abc}, {{2, 0, 2, 1}, fmt::abcd}}, params_t {{{2, 0, 2}, fmt::abc}, {{2, 0, 1, 2, 1}, fmt::abcde}}, params_t {{{2, 1, 0, 2}, fmt::abcd}, {{2, 0, 2, 1}, fmt::abcd}}, params_t {{{31, 1, 0, 2}, fmt::Abcd16a}, {{1, 31, 0, 2, 1}, fmt::aBcde16b}}, params_t {{{2, 3, 0, 2}, {6, 2, 2, 1}}, {{6, 0, 2}, {2, 2, 1}}} ); auto cases_generic = ::testing::Values( // add and/or remove axes of size `1` params_t {{{2, 1}, {2, 2}}, {{2}, {2}}}, params_t {{{2, 1}, {2, 2}}, {{2, 1, 1}, {2, 2, 1}}}, params_t {{{2, 1}, {2, 2}}, {{2, 1, 1}, {2, 1, 2}}}, params_t {{{2, 1}, {2, 2}}, {{2, 1, 1}, {2, 2, 2}}}, params_t {{{2, 2}, fmt::ab}, {{2, 2, 1}, fmt::abc}}, params_t {{{2, 1}, fmt::ab}, {{1, 2, 1, 1}, fmt::abcd}}, params_t {{{1, 2, 1}, fmt::abc}, {{2}, fmt::a}}, params_t {{{3, 4, 5, 6}, fmt::ABcd16b16a}, {{1, 3, 4, 5, 6}, fmt::aBCde16c16b}}, // UNI_DIRECTION due to ambiguity of adding 1, where there is already another axes of size 1 params_t {{{2, 1, 1}, {2, 1, 1}, {2, 2, 1}}, {{2, 1}, {2, 1}, {2, 2}}, UNI_DIRECTION}, params_t {{{2, 1, 1}, {2, 2, 1}, {2, 1, 2}}, {{2, 1}, {2, 1}, {2, 2}}}, // split and join axes (as test_direction == BI_DIRECTION) params_t {{{6, 2}, fmt::ab}, {{3, 2, 2}, fmt::abc}}, params_t {{{6, 2}, fmt::ab}, {{2, 3, 2}, fmt::abc}}, params_t {{{6, 2}, fmt::ba}, {{2, 3, 2}, /* fmt::cab: */ {3, 1, 6}}}, params_t {{{6, 2}, {4, 1}, {6, 4}}, {{2, 3, 2}, {12, 4, 1}, {2, 3, 4}}}, params_t {{{1, 15, 12}, fmt::aBc8b}, {{1, 15, 3, 4}, fmt::aBcd8b}}, params_t {{{1, 15, 12}, fmt::aBc8b}, {{1, 15, 2, 3, 2}, fmt::aBcde8b}}, // combined cases params_t {{{15, 3, 4}, fmt::abc}, {{3, 5, 6, 1, 2}, fmt::abcde}}, params_t {{{15, 3, 4}, fmt::bca}, {{3, 5, 6, 1, 2}, /* fmt::cdeab */ {5, 1, 30, 30, 15}}} ); // clang-format on INSTANTIATE_TEST_SUITE_P(TestReshapeEF, reshape_test_t, cases_expect_to_fail); INSTANTIATE_TEST_SUITE_P(TestReshapeZeroDim, reshape_test_t, cases_zero_dim); INSTANTIATE_TEST_SUITE_P(TestReshapeOK, reshape_test_t, cases_generic); } // namespace reshape namespace permute_axes { struct params_t { memory_desc_proxy_t in; memory_desc_proxy_t out; std::vector<int> perm; test_direction_t test_direction; dnnl_status_t expected_status; }; class permute_axes_test_t : public ::testing::TestWithParam<params_t> { protected: void Test(const memory::desc &in_md, const memory::desc &out_md, const std::vector<int> &perm) { memory::desc get_out_md = in_md.permute_axes(perm); debug::print_md("in_md", in_md); debug::print_vec("perm : ", perm.data(), (int)perm.size()); debug::print_md("out_md", get_out_md); debug::print_md("expect_out_md", out_md); ASSERT_EQ(get_out_md, out_md); } }; TEST_P(permute_axes_test_t, TestsPermuteAxes) { params_t p = ::testing::TestWithParam<decltype(p)>::GetParam(); catch_expected_failures([=]() { Test(p.in.md, p.out.md, p.perm); }, p.expected_status != dnnl_success, p.expected_status); if (p.test_direction == UNI_DIRECTION) return; std::vector<int> inv_perm(p.perm.size()); for (int i = 0; i < (int)p.perm.size(); ++i) inv_perm[p.perm[i]] = i; catch_expected_failures([=]() { Test(p.out.md, p.in.md, inv_perm); }, p.expected_status != dnnl_success, p.expected_status); } using fmt = dnnl::memory::format_tag; // clang-format off auto cases_expect_to_fail = ::testing::Values( // incorrect permutation params_t {{{2, 2, 1, 1}, fmt::abcd}, {{2, 2, 1, 1}, fmt::abcd}, {0, 1, 2, 2}, UNI_DIRECTION, dnnl_invalid_arguments}, // incorrect permutation params_t {{{2, 2, 1, 1}, fmt::abcd}, {{2, 2, 1, 1}, fmt::abcd}, {0, 1, 2, 4}, UNI_DIRECTION, dnnl_invalid_arguments}, // incorrect permutation params_t {{{2, 2, 1, 1}, fmt::abcd}, {{2, 2, 1, 1}, fmt::abcd}, {0, 1, 2, -1}, UNI_DIRECTION, dnnl_invalid_arguments}, // nothing can be done with zero memory desc params_t {{}, {}, {}, UNI_DIRECTION, dnnl_invalid_arguments}, // invalid format kind params_t {{{2, 2, 1, 1}, memory::format_kind::wino}, {{2, 2, 1, 1}, fmt::any}, {1, 2, 3, 4}, UNI_DIRECTION, dnnl_invalid_arguments}, // invalid format kind params_t {{{2, 2, 1, 1}, memory::format_kind::undef}, {{2, 2, 1, 1}, fmt::any}, {1, 2, 3, 4}, UNI_DIRECTION, dnnl_invalid_arguments}, // run-time dims are not supported params_t {{{DNNL_RUNTIME_DIM_VAL}, {1}}, {{DNNL_RUNTIME_DIM_VAL}, {1}}, {0}, UNI_DIRECTION, dnnl_invalid_arguments} ); auto cases_generic = ::testing::Values( params_t {{{2, 1}, fmt::ab}, {{2, 1}, fmt::ab}, {0, 1}}, params_t {{{2, 1}, fmt::ab}, {{1, 2}, fmt::ba}, {1, 0}}, params_t {{{2, 1}, fmt::ba}, {{1, 2}, fmt::ab}, {1, 0}}, params_t {{{2, 3}, {4, 1}, {2, 4}}, {{3, 2}, {1, 4}, {4, 2}}, {1, 0}}, params_t {{{3, 2}, {2, 30}}, {{2, 3}, {30, 2}}, {1, 0}}, params_t {{{2, 3, 4, 5}, fmt::acdb}, {{2, 4, 5, 3}, fmt::abcd}, {0, 3, 1, 2}}, params_t {{{2, 3, 4, 5}, fmt::cdba}, {{4, 5, 3, 2}, fmt::abcd}, {3, 2, 0, 1}}, params_t {{{2, 15, 3, 4}, fmt::ABcd16b16a}, {{15, 2, 3, 4}, fmt::BAcd16a16b}, {1, 0, 2, 3}}, params_t {{{3, 2, 15, 3, 4, 5}, fmt::aBCdef16b16c}, {{3, 15, 2, 3, 4, 5}, fmt::aCBdef16c16b}, {0, 2, 1, 3, 4, 5}} ); // clang-format on INSTANTIATE_TEST_SUITE_P( TestPermuteAxesEF, permute_axes_test_t, cases_expect_to_fail); INSTANTIATE_TEST_SUITE_P(TestPermuteAxesOK, permute_axes_test_t, cases_generic); } // namespace permute_axes } // namespace memory_desc_ops } // namespace dnnl
44.573883
141
0.599877
[ "vector" ]
ce0473cbdd14c1fa271f390e8ca4d28aa35a32a2
21,622
cpp
C++
src/condor_contrib/aviary/src/hadoop/HadoopObject.cpp
zhangzhehust/htcondor
e07510d62161f38fa2483b299196ef9a7b9f7941
[ "Apache-2.0" ]
1
2017-02-13T01:25:34.000Z
2017-02-13T01:25:34.000Z
src/condor_contrib/aviary/src/hadoop/HadoopObject.cpp
AmesianX/htcondor
10aea32f1717637972af90459034d1543004cb83
[ "Apache-2.0" ]
1
2021-04-06T04:19:40.000Z
2021-04-06T04:19:40.000Z
src/condor_contrib/aviary/src/hadoop/HadoopObject.cpp
AmesianX/htcondor
10aea32f1717637972af90459034d1543004cb83
[ "Apache-2.0" ]
2
2016-05-24T17:12:13.000Z
2017-02-13T01:25:35.000Z
/* * Copyright 2009-2011 Red Hat, Inc. * * 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. */ // condor includes #include "condor_common.h" #include "condor_config.h" #include "condor_attributes.h" #include "condor_debug.h" #include "condor_qmgr.h" #include "../condor_schedd.V6/scheduler.h" #include "stl_string_utils.h" // local includes #include "AviaryUtils.h" #include "AviaryConversionMacros.h" #include "HadoopObject.h" // Global Scheduler object, used for needReschedule etc. extern Scheduler scheduler; extern char * Name; using namespace aviary::hadoop; using namespace aviary::util; using namespace aviary::codec; string quote_it (const char * pszIn) { string ret; aviUtilFmt(ret,"\"%s\"", pszIn); return ret; } HadoopObject* HadoopObject::m_instance = NULL; HadoopObject::HadoopObject() { m_pool = getPoolName(); m_name = getScheddName(); m_codec = new BaseCodec(); } HadoopObject::~HadoopObject() { delete m_codec; } HadoopObject* HadoopObject::getInstance() { if (!m_instance) { m_instance = new HadoopObject(); } return m_instance; } void HadoopObject::update(const ClassAd &ad) { MGMT_DECLARATIONS; m_stats.Pool = getPoolName(); STRING(CondorPlatform); STRING(CondorVersion); TIME_INTEGER(DaemonStartTime); TIME_INTEGER(JobQueueBirthdate); STRING(Machine); INTEGER(MaxJobsRunning); INTEGER(MonitorSelfAge); DOUBLE(MonitorSelfCPUUsage); DOUBLE(MonitorSelfImageSize); INTEGER(MonitorSelfRegisteredSocketCount); INTEGER(MonitorSelfResidentSetSize); TIME_INTEGER(MonitorSelfTime); STRING(MyAddress); //TIME_INTEGER(MyCurrentTime); STRING(Name); INTEGER(NumUsers); STRING(MyAddress); INTEGER(TotalHeldJobs); INTEGER(TotalIdleJobs); INTEGER(TotalJobAds); INTEGER(TotalRemovedJobs); INTEGER(TotalRunningJobs); m_stats.System = m_stats.Machine; // debug //if (DebugFlags & D_FULLDEBUG) { dPrintAd(D_FULLDEBUG|D_NOHEADER, const_cast<ClassAd&>(ad)); //} } int HadoopObject::start( tHadoopInit & hInit ) { int cluster, proc; dprintf( D_FULLDEBUG, "Called HadoopObject::start count:%d owner:(%s) unmanaged(%s) tarball:%s \n", hInit.count, hInit.owner.c_str(), hInit.unmanaged?"TRUE":"FALSE", hInit.idref.tarball.size()?hInit.idref.tarball.c_str():"EMPTY" ); // check input tarball. if ( 0 == hInit.idref.tarball.size() && !hInit.unmanaged ) { if (hInit.unmanaged) { hInit.idref.tarball = "EMPTY"; } else { char * binball = param("HADOOP_BIN_TARBALL"); if (!binball ) { m_lasterror = "No hadoop tarball specified."; return false; } else { hInit.idref.tarball = binball; delete binball; } } } // Create transaction BeginTransaction(); // Create cluster if ( -1 == (cluster = NewCluster()) ) { AbortTransaction(); m_lasterror = "Failed to create new cluster"; return false; } // loop through adding sub-elements for a cluster/proc for (unsigned int iCtr=0; iCtr<hInit.count; iCtr++) { // create proc if ( -1 == (proc = NewProc(cluster)) ) { AbortTransaction(); m_lasterror = "Failed to create new proc"; return false; } // now we will string hadoopType, inputscript, args; MyString IPCAddress, HTTPAddress="", ManagedState; bool hasInputScript=false, bValidId=false; string Iwd="/tmp"; int iStatus=1; PROC_ID id = getProcByString( hInit.idref.id.c_str() ); char * requirements = 0; if (id.cluster > 0 && id.proc >= 0) { bValidId = true; ::GetAttributeInt( id.cluster, id.proc, ATTR_JOB_STATUS, &iStatus); ::GetAttributeString( id.cluster, id.proc, "GridoopManaged", ManagedState); dprintf(D_FULLDEBUG, "Valid ClusterId Ref: %s status: %d\n", hInit.idref.id.c_str(), iStatus); } args = hInit.idref.tarball; bool wantsHadoopRequest = false; switch (hInit.idref.type) { case NAME_NODE: hadoopType = ATTR_NAME_NODE; hasInputScript = param(inputscript, "HADOOP_HDFS_NAMENODE_SCRIPT"); ::SetAttribute(cluster, proc, ATTR_RANK, "memory"); ::SetAttribute(cluster, proc, ATTR_REQUEST_MEMORY, "floor(.50 * Target.Memory)"); // TODO: --> Target.Memory requirements = param(HADOOP_NAMENODE_REQUIREMENTS); if(requirements) { ::SetAttribute(cluster, proc, ATTR_REQUIREMENTS, requirements); delete requirements; } else { ::SetAttribute(cluster, proc, ATTR_REQUIREMENTS, "( HasJava =?= TRUE ) && ( TARGET.OpSys == \"LINUX\" ) && ( TARGET.Memory >= RequestMemory ) && ( TARGET.HasFileTransfer )"); } // "spindle" configuration wantsHadoopRequest = param_boolean("HADOOP_ENABLE_REQUEST_NAMENODE",false); if (wantsHadoopRequest) { ::SetAttributeInt(cluster, proc, ATTR_HADOOP_REQUEST_NAMENODE, 1); } break; case JOB_TRACKER: hadoopType = ATTR_JOB_TRACKER; hasInputScript = param(inputscript, "HADOOP_MAPR_JOBTRACKER_SCRIPT"); ::SetAttribute(cluster, proc, ATTR_RANK, "memory"); requirements = param(HADOOP_JOBTRACKER_REQUIREMENTS); if(requirements) { ::SetAttribute(cluster, proc, ATTR_REQUIREMENTS, requirements); delete requirements; } else { ::SetAttribute(cluster, proc, ATTR_REQUIREMENTS, "( HasJava =?= TRUE ) && ( TARGET.OpSys == \"LINUX\" ) && ( TARGET.HasFileTransfer )"); } // "spindle" configuration wantsHadoopRequest = param_boolean("HADOOP_ENABLE_REQUEST_JOBTRACKER",false); if (wantsHadoopRequest) { ::SetAttributeInt(cluster, proc, ATTR_HADOOP_REQUEST_JOBTRACKER, 1); } // fall through case DATA_NODE: // special case case only a small part the rest is common. if (hInit.idref.type == DATA_NODE) { hadoopType = ATTR_DATA_NODE; hasInputScript = param(inputscript, "HADOOP_HDFS_DATANODE_SCRIPT"); ::SetAttribute(cluster, proc, ATTR_RANK, "disk"); requirements = param(HADOOP_DATANODE_REQUIREMENTS); if(requirements) { ::SetAttribute(cluster, proc, ATTR_REQUIREMENTS, requirements); delete requirements; } else { ::SetAttribute(cluster, proc, ATTR_REQUIREMENTS, "( HasJava =?= TRUE ) && ( TARGET.OpSys == \"LINUX\" ) && ( TARGET.HasFileTransfer )"); } } /////////////////////////////////////////////////////////////////////////////////////// // NOTE: This section is common to both JOB_TRACKER && DATA_NODES // It could possibly be refactored into a function but it's not really pretty/clean. if (bValidId && (iStatus == RUNNING || ManagedState == "UNMANAGED" )) { ::GetAttributeString( id.cluster, id.proc, "IPCAddress", IPCAddress); ::GetAttributeString( id.cluster, id.proc, "HTTPAddress", HTTPAddress); //TODO: there could be extra checks here. ::SetAttribute(cluster, proc, "NameNode", quote_it(hInit.idref.id.c_str()).c_str() ); } else if (hInit.idref.ipcid.length()) { // TODO: there could be extra checks here, validate it's up. IPCAddress = hInit.idref.ipcid.c_str(); ::SetAttribute(cluster, proc, "NameNode", "0" ); } else { AbortTransaction(); aviUtilFmt ( m_lasterror, "Name Node %s Invalid or not running status %d", hInit.idref.id.c_str(), iStatus ); return false; } ::SetAttribute(cluster, proc, "NameNodeHTTPAddress", quote_it(HTTPAddress.Value()).c_str() ); args += " "; args += IPCAddress.Value(); ::SetAttribute(cluster, proc, "NameNodeIPCAddress", quote_it(IPCAddress.Value()).c_str()); /////////////////////////////////////////////////////////////////////////////////////// // "spindle" configuration wantsHadoopRequest = param_boolean("HADOOP_ENABLE_REQUEST_DATANODE",false); if (wantsHadoopRequest) { ::SetAttributeInt(cluster, proc, ATTR_HADOOP_REQUEST_DATANODE, 1); } break; case TASK_TRACKER: hadoopType = ATTR_TASK_TRACKER; hasInputScript = param(inputscript, "HADOOP_MAPR_TASKTRACKER_SCRIPT"); ::SetAttribute(cluster, proc, ATTR_RANK, "Mips"); requirements = param(HADOOP_TASKTRACKER_REQUIREMENTS); if(requirements) { ::SetAttribute(cluster, proc, ATTR_REQUIREMENTS, requirements); delete requirements; } else { ::SetAttribute(cluster, proc, ATTR_REQUIREMENTS, "( HasJava =?= TRUE ) && ( TARGET.OpSys == \"LINUX\" ) && ( TARGET.HasFileTransfer )"); } if (bValidId && iStatus == RUNNING) { ::GetAttributeString( id.cluster, id.proc, "IPCAddress", IPCAddress); ::GetAttributeString( id.cluster, id.proc, "HTTPAddress", HTTPAddress); //TODO: there could be extra checks here. ::SetAttribute(cluster, proc, "JobTracker", quote_it(hInit.idref.id.c_str()).c_str() ); } else if (hInit.idref.ipcid.length()) { // TODO: there could be extra checks here, validate it's up. IPCAddress = hInit.idref.ipcid.c_str(); ::SetAttribute(cluster, proc, "JobTracker", "0" ); } else { AbortTransaction(); m_lasterror = "No valid Job Tracker "; aviUtilFmt ( m_lasterror, "ID %s Invalid or not running status %d", hInit.idref.id.c_str(), iStatus ); return false; } ::SetAttribute(cluster, proc, "JobTrackerHTTPAddress", quote_it(HTTPAddress.Value()).c_str() ); args += " "; args += IPCAddress.Value(); ::SetAttribute(cluster, proc, "JobTrackerIPCAddress", quote_it(IPCAddress.Value()).c_str()); // "spindle" configuration wantsHadoopRequest = param_boolean("HADOOP_ENABLE_REQUEST_TASKTRACKER",false); if (wantsHadoopRequest) { ::SetAttributeInt(cluster, proc, ATTR_HADOOP_REQUEST_TASKTRACKER, 1); } break; } // verify that there is an input script, without it you won't get far. if (!hasInputScript) { AbortTransaction(); aviUtilFmt(m_lasterror, "Missing Script Input KNOB for type %s", hadoopType.c_str() ); return false; } // Set the owner attribute ::SetAttribute(cluster, proc, ATTR_OWNER, quote_it(hInit.owner.c_str()).c_str()); if (hInit.unmanaged) { ::SetAttribute(cluster, proc, "GridoopManaged", quote_it("UNMANAGED").c_str()); ::SetAttribute(cluster, proc, "IPCAddress", quote_it(hInit.idref.ipcid.c_str()).c_str()); ::SetAttribute(cluster, proc, "HTTPAddress", quote_it(hInit.idref.http.c_str()).c_str()); // EARLY SET: These attribute are set early so the incoming ad // has a change to override them. ::SetAttribute(cluster, proc, ATTR_JOB_STATUS, "5"); // 1 = held } else { ::SetAttribute(cluster, proc, "GridoopManaged", quote_it("MANAGED").c_str()); ::SetAttribute(cluster, proc, ATTR_TRANSFER_INPUT_FILES, quote_it(hInit.idref.tarball.c_str()).c_str()); ::SetAttribute(cluster, proc, ATTR_HADOOP_BIN_VERSION, quote_it(hInit.idref.tarball.c_str()).c_str()); // EARLY SET: These attribute are set early so the incoming ad // has a change to override them. ::SetAttribute(cluster, proc, ATTR_JOB_STATUS, "1"); // 1 = idle } if ( !hInit.description.length() ) { hInit.description="N/A"; } ::SetAttribute(cluster, proc, ATTR_HADOOP_DESCRIPTION, quote_it(hInit.description.c_str()).c_str()); param(Iwd, "HADOOP_IWD", "/tmp"); ::SetAttribute(cluster, proc, ATTR_JOB_IWD, quote_it(Iwd.c_str()).c_str() ); ::SetAttribute(cluster, proc, ATTR_JOB_CMD, quote_it(inputscript.c_str()).c_str()); ::SetAttribute(cluster, proc, ATTR_JOB_ARGUMENTS1, quote_it(args.c_str()).c_str()); ::SetAttribute(cluster, proc, ATTR_HADOOP_TYPE, quote_it(hadoopType.c_str()).c_str() ); ::SetAttribute(cluster, proc, ATTR_SHOULD_TRANSFER_FILES, quote_it("YES").c_str()); ::SetAttribute(cluster, proc, ATTR_WANT_IO_PROXY, "true"); // TODO - Handle input & output files (kind of debugging only) ::SetAttribute(cluster, proc, ATTR_WHEN_TO_TRANSFER_OUTPUT, quote_it("ON_EXIT").c_str()); ::SetAttribute(cluster, proc, ATTR_KILL_SIG, quote_it("SIGTERM").c_str()); // Junk that condor_q wants, but really shouldn't be necessary ::SetAttribute(cluster, proc, ATTR_JOB_REMOTE_USER_CPU, "0.0"); // float ::SetAttribute(cluster, proc, ATTR_JOB_PRIO, "0"); // int ::SetAttribute(cluster, proc, ATTR_IMAGE_SIZE, "0"); // int ::SetAttributeInt(cluster, proc, ATTR_JOB_UNIVERSE, CONDOR_UNIVERSE_VANILLA ); // more stuff - without these our idle stats are whack ::SetAttribute(cluster, proc, ATTR_MAX_HOSTS, "1"); ::SetAttribute(cluster, proc, ATTR_MIN_HOSTS, "1"); ::SetAttribute(cluster, proc, ATTR_CURRENT_HOSTS, "0"); // int // LATE SET: These attributes are set late, after the incoming // ad, so they override whatever the incoming ad set. char buf[22]; // 22 is max size for an id, 2^32 + . + 2^32 + \0 snprintf(buf, 22, "%d", cluster); ::SetAttribute(cluster, proc, ATTR_CLUSTER_ID, buf); snprintf(buf, 22, "%d", proc); ::SetAttribute(cluster, proc, ATTR_PROC_ID, buf); snprintf(buf, 22, "%ld", time(NULL)); ::SetAttribute(cluster, proc, ATTR_Q_DATE, buf); } // 5. Commit transaction CommitTransaction(); // 6. Reschedule scheduler.needReschedule(); // fill in the new cluster id aviUtilFmt(hInit.newcluster,"%d",cluster); return true; } bool HadoopObject::stop(const tHadoopRef & hRef) { PROC_ID id = getProcByString( hRef.id.c_str() ); dprintf( D_FULLDEBUG, "Called HadoopObject::stop()\n"); if (id.cluster <= 0 || id.proc < 0) { dprintf(D_FULLDEBUG, "Remove: Failed to parse id: %s\n", hRef.id.c_str()); m_lasterror = "Invalid Id"; return false; } if (!abortJob(id.cluster, id.proc, "Aviary API stop",true )) { m_lasterror = "Failed to remove job"; return false; } return true; } bool HadoopObject::status (ClassAd* cAd, const tHadoopType & type, tHadoopJobStatus & hStatus) { int cluster=0, proc=0, JobStatus=0, EnteredStatus=0; // so the following checks are pretty excessive and could likely be removed if (!cAd->LookupString( ATTR_OWNER, hStatus.owner)) { m_lasterror = "Could not find Owner"; return false; } if (!cAd->LookupInteger(ATTR_CLUSTER_ID, cluster)) { m_lasterror = "Could not find cluster id"; return false; } if (!cAd->LookupInteger(ATTR_PROC_ID, proc)) { m_lasterror = "Could not find proc id"; return false; } if (!cAd->LookupInteger(ATTR_JOB_STATUS, JobStatus)) { m_lasterror = "Could not find job status"; return false; } if (!cAd->LookupString( ATTR_HADOOP_BIN_VERSION, hStatus.idref.tarball)) { hStatus.idref.tarball = "UNMANAGED"; } aviUtilFmt(hStatus.idref.id,"%d.%d", cluster, proc); if (!cAd->LookupString( ATTR_HADOOP_DESCRIPTION, hStatus.description)) { hStatus.description = "N/A"; } cAd->LookupInteger( ATTR_Q_DATE, hStatus.qdate ); if (!cAd->LookupString( ATTR_HTTP_ADDRESS, hStatus.http)) { hStatus.http="N/A"; } hStatus.uptime = 0; // 1st check to see if we are unmanaged. cAd->LookupString( "GridoopManaged", hStatus.state); // if we are not unmanaged then fill in the state if ( strcmp("UNMANAGED", hStatus.state.c_str()) ) { dprintf( D_ALWAYS, "ANything but 0 on comparison\n"); switch (JobStatus) { case 1: hStatus.state = "PENDING"; break; case 2: hStatus.state = "RUNNING"; if ( cAd->LookupInteger(ATTR_ENTERED_CURRENT_STATUS, EnteredStatus) ) { hStatus.uptime=((int)time(NULL)-EnteredStatus); } break; case 3: case 4: hStatus.state = "EXITING"; break; default: hStatus.state = "ERROR"; } } if (!cAd->LookupString( "IPCAddress", hStatus.idref.ipcid)) { hStatus.idref.ipcid="N/A"; } if (!cAd->LookupString( "HTTPAddress", hStatus.idref.http)) { hStatus.idref.http="N/A"; } // default the parent data hStatus.idparent.ipcid="N/A"; hStatus.idparent.id="N/A"; hStatus.idparent.http="N/A"; switch (type) { case DATA_NODE: case JOB_TRACKER: cAd->LookupString("NameNodeIPCAddress", hStatus.idparent.ipcid); cAd->LookupString("NameNode", hStatus.idparent.id); break; case TASK_TRACKER: cAd->LookupString("JobTrackerIPCAddress", hStatus.idparent.ipcid); cAd->LookupString("JobTracker", hStatus.idparent.id); break; default: break; } dprintf( D_ALWAYS, "Called HadoopObject::status() STATUS:%s, ID:%d.%d OWNER:%s PARENT:(%s,%s) DESCRIPTION:%s\n", hStatus.state.c_str(), cluster, proc, hStatus.owner.c_str(), hStatus.idparent.id.c_str(), hStatus.idparent.ipcid.c_str(), hStatus.description.c_str() ); return true; } bool HadoopObject::query (const tHadoopRef & hRef, std::vector<tHadoopJobStatus> & vhStatus) { dprintf( D_FULLDEBUG, "Called HadoopObject::query()\n"); vhStatus.clear(); ClassAd* cAd; string constraint; switch (hRef.type) { case NAME_NODE: // just list all the name nodes constraint = "HadoopType =?= \"NameNode\""; break; case DATA_NODE: // list all name nodes bound query on hRef.idref.id; constraint = "HadoopType =?= \"DataNode\""; break; case JOB_TRACKER: //just list all job trackers. constraint = "HadoopType =?= \"JobTracker\""; break; case TASK_TRACKER: // list all name nodes bound query on hRef.idref.id; constraint = "HadoopType =?= \"TaskTracker\""; break; } // if an id is given use, use reference id. if (hRef.id.length()) { size_t pos = hRef.id.find("."); string cid,pid; if (pos != string::npos) { cid = hRef.id.substr(0,pos); pid = hRef.id.substr(pos+1); } else { cid = hRef.id; } constraint+= " && ClusterId =?= "; constraint+=cid; if (pid.length()) { constraint+= " && ProcId =?= "; constraint+=pid; } } else if (hRef.ipcid.length()) { // if not given a id but given an ipc, try that. constraint+= " && IPCAddress =?= "; constraint+= hRef.ipcid; } // get all adds that match the above constraint. if ( 0 == ( cAd = ::GetJobByConstraint(constraint.c_str()) ) ) { m_lasterror = "Empty query"; dprintf( D_FULLDEBUG, "HadoopObject::status() - FAILED Constraint query(%s)\n", constraint.c_str()); return false; } // loop through the ads while ( cAd ) { tHadoopJobStatus hStatus; if ( status ( cAd, hRef.type, hStatus ) ) { // last error should be set. vhStatus.push_back(hStatus); } else { dprintf( D_FULLDEBUG, "HadoopObject::status() - FAILED status parse\n"); return false; } cAd = ::GetNextJobByConstraint( constraint.c_str(), 0 ); } return true; }
31.750367
186
0.58237
[ "cad", "object", "vector" ]
ce04f4f18c5197e8bfc5c96d2f2a11a9b0901444
1,988
hpp
C++
include/bootloader_util/Intel_hex_loader.hpp
suburbanembedded/bootloader_util
32cd7d2ffee429f1726ca9f0c671f594422ecae6
[ "BSD-3-Clause" ]
null
null
null
include/bootloader_util/Intel_hex_loader.hpp
suburbanembedded/bootloader_util
32cd7d2ffee429f1726ca9f0c671f594422ecae6
[ "BSD-3-Clause" ]
null
null
null
include/bootloader_util/Intel_hex_loader.hpp
suburbanembedded/bootloader_util
32cd7d2ffee429f1726ca9f0c671f594422ecae6
[ "BSD-3-Clause" ]
null
null
null
/** * @brief Intel_hex_loader * @author Jacob Schloss <jacob@schloss.io> * @copyright Copyright (c) 2019 Jacob Schloss. All rights reserved. * @license Licensed under the 3-Clause BSD license. See LICENSE for details */ #pragma once #include <cstdint> #include <vector> #include <string> class IHEX_RECORD { public: enum class IHEX_RECORD_TYPE : uint8_t { REC_DATA = 0x00,//data + 16bit addr REC_EOF = 0x01,//end of file REC_EXTENDED_SEGMENT_ADDRESS = 0x02,//16 addr bits, add to addr bits from data field REC_START_SEGMENT_ADDRESS = 0x03,//CS:IP reg, 16 bit start address REC_EXTENDED_LINEAR_ADDRESS = 0x04,//16 high addr bits, get low addr bits from data field REC_START_LINEAR_ADDRESS = 0x05 //32 bit abs address to jump to }; uint8_t byte_count; uint16_t address; IHEX_RECORD_TYPE record_type; std::vector<uint8_t> data; uint8_t checksum; bool verify_checksum() const; void update_checksum(); static bool verify_checksum(const IHEX_RECORD& rec); static uint8_t calculate_checksum(const IHEX_RECORD& rec); bool to_string(std::string* const str); bool from_string(const std::string& str); }; class Intel_hex_loader { public: Intel_hex_loader() { m_ext_lin_addr = 0; m_start_lin_addr = 0; m_has_start_lin_addr = false; m_eof = false; } bool process_line(const std::string& line); bool has_eof() const { return m_eof; } bool get_boot_addr(uint32_t* addr) const { if(!m_has_start_lin_addr) { return false; } *addr = m_start_lin_addr; return true; } protected: bool handle_DATA(const IHEX_RECORD& rec); bool handle_EOF(const IHEX_RECORD& rec); bool handle_EXTENDED_SEGMENT_ADDRESS(const IHEX_RECORD& rec); bool handle_START_SEGMENT_ADDRESS(const IHEX_RECORD& rec); bool handle_EXTENDED_LINEAR_ADDRESS(const IHEX_RECORD& rec); bool handle_START_LINEAR_ADDRESS(const IHEX_RECORD& rec); uint32_t m_ext_lin_addr; bool m_has_start_lin_addr; uint32_t m_start_lin_addr; bool m_eof; };
22.088889
92
0.745473
[ "vector" ]
ce0653f64ebd6369e7b91020e843964e0003b11d
7,989
cpp
C++
gaap/src/v20180529/model/SecurityPolicyRuleOut.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
null
null
null
gaap/src/v20180529/model/SecurityPolicyRuleOut.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
null
null
null
gaap/src/v20180529/model/SecurityPolicyRuleOut.cpp
li5ch/tencentcloud-sdk-cpp
12ebfd75a399ee2791f6ac1220a79ce8a9faf7c4
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * 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 <tencentcloud/gaap/v20180529/model/SecurityPolicyRuleOut.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Gaap::V20180529::Model; using namespace rapidjson; using namespace std; SecurityPolicyRuleOut::SecurityPolicyRuleOut() : m_actionHasBeenSet(false), m_sourceCidrHasBeenSet(false), m_aliasNameHasBeenSet(false), m_destPortRangeHasBeenSet(false), m_ruleIdHasBeenSet(false), m_protocolHasBeenSet(false), m_policyIdHasBeenSet(false) { } CoreInternalOutcome SecurityPolicyRuleOut::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("Action") && !value["Action"].IsNull()) { if (!value["Action"].IsString()) { return CoreInternalOutcome(Error("response `SecurityPolicyRuleOut.Action` IsString=false incorrectly").SetRequestId(requestId)); } m_action = string(value["Action"].GetString()); m_actionHasBeenSet = true; } if (value.HasMember("SourceCidr") && !value["SourceCidr"].IsNull()) { if (!value["SourceCidr"].IsString()) { return CoreInternalOutcome(Error("response `SecurityPolicyRuleOut.SourceCidr` IsString=false incorrectly").SetRequestId(requestId)); } m_sourceCidr = string(value["SourceCidr"].GetString()); m_sourceCidrHasBeenSet = true; } if (value.HasMember("AliasName") && !value["AliasName"].IsNull()) { if (!value["AliasName"].IsString()) { return CoreInternalOutcome(Error("response `SecurityPolicyRuleOut.AliasName` IsString=false incorrectly").SetRequestId(requestId)); } m_aliasName = string(value["AliasName"].GetString()); m_aliasNameHasBeenSet = true; } if (value.HasMember("DestPortRange") && !value["DestPortRange"].IsNull()) { if (!value["DestPortRange"].IsString()) { return CoreInternalOutcome(Error("response `SecurityPolicyRuleOut.DestPortRange` IsString=false incorrectly").SetRequestId(requestId)); } m_destPortRange = string(value["DestPortRange"].GetString()); m_destPortRangeHasBeenSet = true; } if (value.HasMember("RuleId") && !value["RuleId"].IsNull()) { if (!value["RuleId"].IsString()) { return CoreInternalOutcome(Error("response `SecurityPolicyRuleOut.RuleId` IsString=false incorrectly").SetRequestId(requestId)); } m_ruleId = string(value["RuleId"].GetString()); m_ruleIdHasBeenSet = true; } if (value.HasMember("Protocol") && !value["Protocol"].IsNull()) { if (!value["Protocol"].IsString()) { return CoreInternalOutcome(Error("response `SecurityPolicyRuleOut.Protocol` IsString=false incorrectly").SetRequestId(requestId)); } m_protocol = string(value["Protocol"].GetString()); m_protocolHasBeenSet = true; } if (value.HasMember("PolicyId") && !value["PolicyId"].IsNull()) { if (!value["PolicyId"].IsString()) { return CoreInternalOutcome(Error("response `SecurityPolicyRuleOut.PolicyId` IsString=false incorrectly").SetRequestId(requestId)); } m_policyId = string(value["PolicyId"].GetString()); m_policyIdHasBeenSet = true; } return CoreInternalOutcome(true); } void SecurityPolicyRuleOut::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_actionHasBeenSet) { Value iKey(kStringType); string key = "Action"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_action.c_str(), allocator).Move(), allocator); } if (m_sourceCidrHasBeenSet) { Value iKey(kStringType); string key = "SourceCidr"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_sourceCidr.c_str(), allocator).Move(), allocator); } if (m_aliasNameHasBeenSet) { Value iKey(kStringType); string key = "AliasName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_aliasName.c_str(), allocator).Move(), allocator); } if (m_destPortRangeHasBeenSet) { Value iKey(kStringType); string key = "DestPortRange"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_destPortRange.c_str(), allocator).Move(), allocator); } if (m_ruleIdHasBeenSet) { Value iKey(kStringType); string key = "RuleId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_ruleId.c_str(), allocator).Move(), allocator); } if (m_protocolHasBeenSet) { Value iKey(kStringType); string key = "Protocol"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_protocol.c_str(), allocator).Move(), allocator); } if (m_policyIdHasBeenSet) { Value iKey(kStringType); string key = "PolicyId"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_policyId.c_str(), allocator).Move(), allocator); } } string SecurityPolicyRuleOut::GetAction() const { return m_action; } void SecurityPolicyRuleOut::SetAction(const string& _action) { m_action = _action; m_actionHasBeenSet = true; } bool SecurityPolicyRuleOut::ActionHasBeenSet() const { return m_actionHasBeenSet; } string SecurityPolicyRuleOut::GetSourceCidr() const { return m_sourceCidr; } void SecurityPolicyRuleOut::SetSourceCidr(const string& _sourceCidr) { m_sourceCidr = _sourceCidr; m_sourceCidrHasBeenSet = true; } bool SecurityPolicyRuleOut::SourceCidrHasBeenSet() const { return m_sourceCidrHasBeenSet; } string SecurityPolicyRuleOut::GetAliasName() const { return m_aliasName; } void SecurityPolicyRuleOut::SetAliasName(const string& _aliasName) { m_aliasName = _aliasName; m_aliasNameHasBeenSet = true; } bool SecurityPolicyRuleOut::AliasNameHasBeenSet() const { return m_aliasNameHasBeenSet; } string SecurityPolicyRuleOut::GetDestPortRange() const { return m_destPortRange; } void SecurityPolicyRuleOut::SetDestPortRange(const string& _destPortRange) { m_destPortRange = _destPortRange; m_destPortRangeHasBeenSet = true; } bool SecurityPolicyRuleOut::DestPortRangeHasBeenSet() const { return m_destPortRangeHasBeenSet; } string SecurityPolicyRuleOut::GetRuleId() const { return m_ruleId; } void SecurityPolicyRuleOut::SetRuleId(const string& _ruleId) { m_ruleId = _ruleId; m_ruleIdHasBeenSet = true; } bool SecurityPolicyRuleOut::RuleIdHasBeenSet() const { return m_ruleIdHasBeenSet; } string SecurityPolicyRuleOut::GetProtocol() const { return m_protocol; } void SecurityPolicyRuleOut::SetProtocol(const string& _protocol) { m_protocol = _protocol; m_protocolHasBeenSet = true; } bool SecurityPolicyRuleOut::ProtocolHasBeenSet() const { return m_protocolHasBeenSet; } string SecurityPolicyRuleOut::GetPolicyId() const { return m_policyId; } void SecurityPolicyRuleOut::SetPolicyId(const string& _policyId) { m_policyId = _policyId; m_policyIdHasBeenSet = true; } bool SecurityPolicyRuleOut::PolicyIdHasBeenSet() const { return m_policyIdHasBeenSet; }
27.739583
147
0.687696
[ "model" ]
ce066942cd58599188ab6fa3aca6eb7be7dd2392
6,603
hpp
C++
src/loop-analysis/nest-analysis.hpp
tanvisharma/timeloop
bd6985e6a4faa6d6383e5c2ae9bca4830a752ad2
[ "BSD-3-Clause" ]
2
2021-07-28T09:05:38.000Z
2022-01-22T19:33:18.000Z
src/loop-analysis/nest-analysis.hpp
tanvisharma/timeloop
bd6985e6a4faa6d6383e5c2ae9bca4830a752ad2
[ "BSD-3-Clause" ]
null
null
null
src/loop-analysis/nest-analysis.hpp
tanvisharma/timeloop
bd6985e6a4faa6d6383e5c2ae9bca4830a752ad2
[ "BSD-3-Clause" ]
1
2022-01-22T19:33:19.000Z
2022-01-22T19:33:19.000Z
/* Copyright (c) 2019, NVIDIA CORPORATION. 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 NVIDIA CORPORATION 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 ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include "mapping/nest.hpp" #include "workload/per-problem-dimension.hpp" namespace analysis { class NestAnalysis { private: // Cached copy of loop nest under evaluation (used for speedup). loop::Nest cached_nest; // Properties of the nest being analyzed (copied over during construction). std::vector<uint64_t> storage_tiling_boundaries_; // Live state. std::vector<analysis::LoopState> nest_state_; std::vector<int> indices_; std::uint64_t num_epochs_; // Identifies the spatial element // whose working set is currently being computed. // Dynamically updated by recursive calls. std::uint64_t spatial_id_; tiling::CompoundTileNest working_sets_; tiling::BodyInfo body_info_; // Memoization structures to accelerate IndexToOperationPoint() std::vector<problem::PerProblemDimension<std::uint64_t>> per_level_dim_scales_; // level * dim problem::OperationPoint cur_transform_; std::vector<problem::OperationPoint> mold_low_; std::vector<problem::OperationPoint> mold_high_; // per-level properties. std::vector<uint64_t> num_spatial_elems_; std::vector<uint64_t> spatial_fanouts_; // used to accelerate to IndexToOperationPoint computation // relevant only for master spatial levels. std::vector<uint64_t> horizontal_sizes_; std::vector<uint64_t> vertical_sizes_; // records if a level corresponds to the starting // point of a new storage tile. std::vector<bool> storage_boundary_level_; // any level which is at the transition point from temporal to // spatial nests is a master spatial level. // there should be one such level between each set of // consecutive physical storage levels. std::vector<bool> master_spatial_level_; // true if the spatial elements at a given master spatial // level are connected by on-chip links. std::vector<bool> linked_spatial_level_; bool working_sets_computed_ = false; problem::Workload* workload_ = nullptr; // Internal helper methods. void ComputeWorkingSets(); void InitializeNestProperties(); void InitNumSpatialElems(); void InitStorageBoundaries(); void InitSpatialFanouts(); void InitPerLevelDimScales(); void InitializeLiveState(); void CollectWorkingSets(); problem::OperationPoint IndexToOperationPoint_(const std::vector<int>& indices) const; problem::OperationSpace ComputeDeltas( std::vector<analysis::LoopState>::reverse_iterator cur, bool skip_delta = false); void ComputeTemporalWorkingSet(std::vector<analysis::LoopState>::reverse_iterator cur, problem::OperationSpace& point_set, analysis::ElementState& cur_state); void ComputeSpatialWorkingSet(std::vector<analysis::LoopState>::reverse_iterator cur, problem::OperationSpace& point_set); void FillSpatialDeltas(std::vector<analysis::LoopState>::reverse_iterator cur, std::vector<problem::OperationSpace>& spatial_deltas, std::vector<bool>& valid_delta, std::uint64_t base_index, int depth = 0); void ComputeAccurateMulticastedAccesses( std::vector<analysis::LoopState>::reverse_iterator cur, const std::vector<problem::OperationSpace>& spatial_deltas, std::vector<problem::PerDataSpace<bool>>& unaccounted_delta, problem::PerDataSpace<std::vector<std::uint64_t>>& accesses, problem::PerDataSpace<std::vector<std::uint64_t>>& scatter_factors, problem::PerDataSpace<std::vector<double>>& cumulative_hops ); void ComputeApproxMulticastedAccesses( std::vector<analysis::LoopState>::reverse_iterator cur, const std::vector<problem::OperationSpace>& spatial_deltas); void ComputeNetworkLinkTransfers( std::vector<analysis::LoopState>::reverse_iterator cur, const std::vector<problem::OperationSpace>& cur_spatial_deltas, std::vector<problem::PerDataSpace<bool>>& unaccounted_delta, problem::PerDataSpace<std::uint64_t>& link_transfers); void ComputeDataDensity(); public: // API NestAnalysis(); void Init(problem::Workload* wc, const loop::Nest* nest); void Reset(); std::vector<problem::PerDataSpace<std::size_t>> GetWorkingSetSizes_LTW() const; problem::PerDataSpace<std::vector<tiling::TileInfo>> GetWorkingSets(); tiling::BodyInfo GetBodyInfo(); // Serialization. friend class boost::serialization::access; template <class Archive> void serialize(Archive& ar, const unsigned int version=0) { if(version == 0) { ar& BOOST_SERIALIZATION_NVP(nest_state_); ar& boost::serialization::make_nvp("work_sets_",boost::serialization::make_array(working_sets_.data(),working_sets_.size())); ar& BOOST_SERIALIZATION_NVP(working_sets_computed_); // ar& BOOST_SERIALIZATION_NVP(compute_cycles_); } } friend std::ostream& operator << (std::ostream& out, const NestAnalysis& n); }; } // namespace analysis
37.948276
131
0.7277
[ "vector" ]
ce07f6ce5398c50b49c7fbbc5e07394c3e8279a6
18,519
cpp
C++
LiDAR-SLAM/02-loams/src/lidar_localization/src/aloam_scan_registration_node.cpp
lanqing30/SensorFusionCourse
3fcf935d6a4191563afcf2d95b34718fba7f705a
[ "Apache-2.0" ]
7
2021-03-19T05:51:44.000Z
2021-09-16T06:10:16.000Z
02-loams/src/lidar_localization/src/aloam_scan_registration_node.cpp
WeihengXia0123/LiDar-SLAM
834060da7ee0125cefd310d6215821551bac16c3
[ "MIT" ]
null
null
null
02-loams/src/lidar_localization/src/aloam_scan_registration_node.cpp
WeihengXia0123/LiDar-SLAM
834060da7ee0125cefd310d6215821551bac16c3
[ "MIT" ]
6
2021-02-17T12:31:08.000Z
2022-01-22T17:12:44.000Z
// This is an advanced implementation of the algorithm described in the following paper: // J. Zhang and S. Singh. LOAM: Lidar Odometry and Mapping in Real-time. // Robotics: Science and Systems Conference (RSS). Berkeley, CA, July 2014. // Modifier: Tong Qin qintonguav@gmail.com // Shaozu Cao saozu.cao@connect.ust.hk // Copyright 2013, Ji Zhang, Carnegie Mellon University // Further contributions copyright (c) 2016, Southwest Research Institute // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // 1. Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // 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 <cmath> #include <iostream> #include <vector> #include <string> #include <nav_msgs/Odometry.h> #include <pcl_conversions/pcl_conversions.h> #include <pcl/point_cloud.h> #include <pcl/point_types.h> #include <pcl/filters/voxel_grid.h> #include <pcl/kdtree/kdtree_flann.h> #include <ros/ros.h> #include <sensor_msgs/Imu.h> #include <sensor_msgs/PointCloud2.h> #include <tf/transform_datatypes.h> #include <tf/transform_broadcaster.h> #include "lidar_localization/utils/common.h" #include "lidar_localization/utils/tic_toc.h" using std::atan2; using std::cos; using std::sin; const double scanPeriod = 0.1; const int systemDelay = 0; int systemInitCount = 0; bool systemInited = false; int N_SCANS = 0; float cloudCurvature[400000]; int cloudSortInd[400000]; int cloudNeighborPicked[400000]; int cloudLabel[400000]; bool comp (int i,int j) { return (cloudCurvature[i]<cloudCurvature[j]); } ros::Publisher pubLaserCloud; ros::Publisher pubCornerPointsSharp; ros::Publisher pubCornerPointsLessSharp; ros::Publisher pubSurfPointsFlat; ros::Publisher pubSurfPointsLessFlat; ros::Publisher pubRemovePoints; std::vector<ros::Publisher> pubEachScan; bool PUB_EACH_LINE = false; double MINIMUM_RANGE = 0.1; template <typename PointT> void removeClosedPointCloud( const pcl::PointCloud<PointT> &cloud_in, pcl::PointCloud<PointT> &cloud_out, float thres ) { if (&cloud_in != &cloud_out) { cloud_out.header = cloud_in.header; cloud_out.points.resize(cloud_in.points.size()); } size_t j = 0; for (size_t i = 0; i < cloud_in.points.size(); ++i) { if (cloud_in.points[i].x * cloud_in.points[i].x + cloud_in.points[i].y * cloud_in.points[i].y + cloud_in.points[i].z * cloud_in.points[i].z < thres * thres) continue; cloud_out.points[j] = cloud_in.points[i]; j++; } if (j != cloud_in.points.size()) { cloud_out.points.resize(j); } cloud_out.height = 1; cloud_out.width = static_cast<uint32_t>(j); cloud_out.is_dense = true; } void laserCloudHandler(const sensor_msgs::PointCloud2ConstPtr &laserCloudMsg) { if (!systemInited) { systemInitCount++; if (systemInitCount >= systemDelay) { systemInited = true; std::cout << "Scan Registration has been Inited." << std::endl; } else return; } TicToc t_whole; TicToc t_prepare; std::vector<int> scanStartInd(N_SCANS, 0); std::vector<int> scanEndInd(N_SCANS, 0); pcl::PointCloud<pcl::PointXYZ> laserCloudIn; pcl::fromROSMsg(*laserCloudMsg, laserCloudIn); std::vector<int> indices; pcl::removeNaNFromPointCloud(laserCloudIn, laserCloudIn, indices); removeClosedPointCloud(laserCloudIn, laserCloudIn, MINIMUM_RANGE); int cloudSize = laserCloudIn.points.size(); float startOri = -atan2(laserCloudIn.points[0].y, laserCloudIn.points[0].x); float endOri = -atan2(laserCloudIn.points[cloudSize - 1].y, laserCloudIn.points[cloudSize - 1].x) + 2 * M_PI; if (endOri - startOri > 3 * M_PI) { endOri -= 2 * M_PI; } else if (endOri - startOri < M_PI) { endOri += 2 * M_PI; } //printf("end Ori %f\n", endOri); bool halfPassed = false; int count = cloudSize; PointType point; std::vector<pcl::PointCloud<PointType>> laserCloudScans(N_SCANS); for (int i = 0; i < cloudSize; i++) { point.x = laserCloudIn.points[i].x; point.y = laserCloudIn.points[i].y; point.z = laserCloudIn.points[i].z; float angle = atan(point.z / sqrt(point.x * point.x + point.y * point.y)) * 180 / M_PI; int scanID = 0; if (N_SCANS == 16) { scanID = int((angle + 15) / 2 + 0.5); if (scanID > (N_SCANS - 1) || scanID < 0) { count--; continue; } } else if (N_SCANS == 32) { scanID = int((angle + 92.0/3.0) * 3.0 / 4.0); if (scanID > (N_SCANS - 1) || scanID < 0) { count--; continue; } } else if (N_SCANS == 64) { if (angle >= -8.83) scanID = int((2 - angle) * 3.0 + 0.5); else scanID = N_SCANS / 2 + int((-8.83 - angle) * 2.0 + 0.5); // use [0 50] > 50 remove outlies if (angle > 2 || angle < -24.33 || scanID > 50 || scanID < 0) { count--; continue; } } else { printf("wrong scan number\n"); ROS_BREAK(); } //printf("angle %f scanID %d \n", angle, scanID); float ori = -atan2(point.y, point.x); if (!halfPassed) { if (ori < startOri - M_PI / 2) { ori += 2 * M_PI; } else if (ori > startOri + M_PI * 3 / 2) { ori -= 2 * M_PI; } if (ori - startOri > M_PI) { halfPassed = true; } } else { ori += 2 * M_PI; if (ori < endOri - M_PI * 3 / 2) { ori += 2 * M_PI; } else if (ori > endOri + M_PI / 2) { ori -= 2 * M_PI; } } float relTime = (ori - startOri) / (endOri - startOri); point.intensity = scanID + scanPeriod * relTime; laserCloudScans[scanID].push_back(point); } cloudSize = count; printf("points size %d \n", cloudSize); pcl::PointCloud<PointType>::Ptr laserCloud(new pcl::PointCloud<PointType>()); for (int i = 0; i < N_SCANS; i++) { scanStartInd[i] = laserCloud->size() + 5; *laserCloud += laserCloudScans[i]; scanEndInd[i] = laserCloud->size() - 6; } printf("prepare time %f \n", t_prepare.toc()); for (int i = 5; i < cloudSize - 5; i++) { float diffX = laserCloud->points[i - 5].x + laserCloud->points[i - 4].x + laserCloud->points[i - 3].x + laserCloud->points[i - 2].x + laserCloud->points[i - 1].x - 10 * laserCloud->points[i].x + laserCloud->points[i + 1].x + laserCloud->points[i + 2].x + laserCloud->points[i + 3].x + laserCloud->points[i + 4].x + laserCloud->points[i + 5].x; float diffY = laserCloud->points[i - 5].y + laserCloud->points[i - 4].y + laserCloud->points[i - 3].y + laserCloud->points[i - 2].y + laserCloud->points[i - 1].y - 10 * laserCloud->points[i].y + laserCloud->points[i + 1].y + laserCloud->points[i + 2].y + laserCloud->points[i + 3].y + laserCloud->points[i + 4].y + laserCloud->points[i + 5].y; float diffZ = laserCloud->points[i - 5].z + laserCloud->points[i - 4].z + laserCloud->points[i - 3].z + laserCloud->points[i - 2].z + laserCloud->points[i - 1].z - 10 * laserCloud->points[i].z + laserCloud->points[i + 1].z + laserCloud->points[i + 2].z + laserCloud->points[i + 3].z + laserCloud->points[i + 4].z + laserCloud->points[i + 5].z; cloudCurvature[i] = diffX * diffX + diffY * diffY + diffZ * diffZ; cloudSortInd[i] = i; cloudNeighborPicked[i] = 0; cloudLabel[i] = 0; } TicToc t_pts; pcl::PointCloud<PointType> cornerPointsSharp; pcl::PointCloud<PointType> cornerPointsLessSharp; pcl::PointCloud<PointType> surfPointsFlat; pcl::PointCloud<PointType> surfPointsLessFlat; float t_q_sort = 0; for (int i = 0; i < N_SCANS; i++) { if( scanEndInd[i] - scanStartInd[i] < 6) continue; pcl::PointCloud<PointType>::Ptr surfPointsLessFlatScan(new pcl::PointCloud<PointType>); for (int j = 0; j < 6; j++) { int sp = scanStartInd[i] + (scanEndInd[i] - scanStartInd[i]) * j / 6; int ep = scanStartInd[i] + (scanEndInd[i] - scanStartInd[i]) * (j + 1) / 6 - 1; TicToc t_tmp; std::sort (cloudSortInd + sp, cloudSortInd + ep + 1, comp); t_q_sort += t_tmp.toc(); int largestPickedNum = 0; for (int k = ep; k >= sp; k--) { int ind = cloudSortInd[k]; if (cloudNeighborPicked[ind] == 0 && cloudCurvature[ind] > 0.1) { largestPickedNum++; if (largestPickedNum <= 2) { cloudLabel[ind] = 2; cornerPointsSharp.push_back(laserCloud->points[ind]); cornerPointsLessSharp.push_back(laserCloud->points[ind]); } else if (largestPickedNum <= 20) { cloudLabel[ind] = 1; cornerPointsLessSharp.push_back(laserCloud->points[ind]); } else { break; } cloudNeighborPicked[ind] = 1; for (int l = 1; l <= 5; l++) { float diffX = laserCloud->points[ind + l].x - laserCloud->points[ind + l - 1].x; float diffY = laserCloud->points[ind + l].y - laserCloud->points[ind + l - 1].y; float diffZ = laserCloud->points[ind + l].z - laserCloud->points[ind + l - 1].z; if (diffX * diffX + diffY * diffY + diffZ * diffZ > 0.05) { break; } cloudNeighborPicked[ind + l] = 1; } for (int l = -1; l >= -5; l--) { float diffX = laserCloud->points[ind + l].x - laserCloud->points[ind + l + 1].x; float diffY = laserCloud->points[ind + l].y - laserCloud->points[ind + l + 1].y; float diffZ = laserCloud->points[ind + l].z - laserCloud->points[ind + l + 1].z; if (diffX * diffX + diffY * diffY + diffZ * diffZ > 0.05) { break; } cloudNeighborPicked[ind + l] = 1; } } } int smallestPickedNum = 0; for (int k = sp; k <= ep; k++) { int ind = cloudSortInd[k]; if (cloudNeighborPicked[ind] == 0 && cloudCurvature[ind] < 0.1) { cloudLabel[ind] = -1; surfPointsFlat.push_back(laserCloud->points[ind]); smallestPickedNum++; if (smallestPickedNum >= 4) { break; } cloudNeighborPicked[ind] = 1; for (int l = 1; l <= 5; l++) { float diffX = laserCloud->points[ind + l].x - laserCloud->points[ind + l - 1].x; float diffY = laserCloud->points[ind + l].y - laserCloud->points[ind + l - 1].y; float diffZ = laserCloud->points[ind + l].z - laserCloud->points[ind + l - 1].z; if (diffX * diffX + diffY * diffY + diffZ * diffZ > 0.05) { break; } cloudNeighborPicked[ind + l] = 1; } for (int l = -1; l >= -5; l--) { float diffX = laserCloud->points[ind + l].x - laserCloud->points[ind + l + 1].x; float diffY = laserCloud->points[ind + l].y - laserCloud->points[ind + l + 1].y; float diffZ = laserCloud->points[ind + l].z - laserCloud->points[ind + l + 1].z; if (diffX * diffX + diffY * diffY + diffZ * diffZ > 0.05) { break; } cloudNeighborPicked[ind + l] = 1; } } } for (int k = sp; k <= ep; k++) { if (cloudLabel[k] <= 0) { surfPointsLessFlatScan->push_back(laserCloud->points[k]); } } } pcl::PointCloud<PointType> surfPointsLessFlatScanDS; pcl::VoxelGrid<PointType> downSizeFilter; downSizeFilter.setInputCloud(surfPointsLessFlatScan); downSizeFilter.setLeafSize(0.2, 0.2, 0.2); downSizeFilter.filter(surfPointsLessFlatScanDS); surfPointsLessFlat += surfPointsLessFlatScanDS; } printf("sort q time %f \n", t_q_sort); printf("seperate points time %f \n", t_pts.toc()); sensor_msgs::PointCloud2 laserCloudOutMsg; pcl::toROSMsg(*laserCloud, laserCloudOutMsg); laserCloudOutMsg.header.stamp = laserCloudMsg->header.stamp; laserCloudOutMsg.header.frame_id = "/velo_link"; pubLaserCloud.publish(laserCloudOutMsg); sensor_msgs::PointCloud2 cornerPointsSharpMsg; pcl::toROSMsg(cornerPointsSharp, cornerPointsSharpMsg); cornerPointsSharpMsg.header.stamp = laserCloudMsg->header.stamp; cornerPointsSharpMsg.header.frame_id = "/velo_link"; pubCornerPointsSharp.publish(cornerPointsSharpMsg); sensor_msgs::PointCloud2 cornerPointsLessSharpMsg; pcl::toROSMsg(cornerPointsLessSharp, cornerPointsLessSharpMsg); cornerPointsLessSharpMsg.header.stamp = laserCloudMsg->header.stamp; cornerPointsLessSharpMsg.header.frame_id = "/velo_link"; pubCornerPointsLessSharp.publish(cornerPointsLessSharpMsg); sensor_msgs::PointCloud2 surfPointsFlat2; pcl::toROSMsg(surfPointsFlat, surfPointsFlat2); surfPointsFlat2.header.stamp = laserCloudMsg->header.stamp; surfPointsFlat2.header.frame_id = "/velo_link"; pubSurfPointsFlat.publish(surfPointsFlat2); sensor_msgs::PointCloud2 surfPointsLessFlat2; pcl::toROSMsg(surfPointsLessFlat, surfPointsLessFlat2); surfPointsLessFlat2.header.stamp = laserCloudMsg->header.stamp; surfPointsLessFlat2.header.frame_id = "/velo_link"; pubSurfPointsLessFlat.publish(surfPointsLessFlat2); // pub each scam if(PUB_EACH_LINE) { for(int i = 0; i< N_SCANS; i++) { sensor_msgs::PointCloud2 scanMsg; pcl::toROSMsg(laserCloudScans[i], scanMsg); scanMsg.header.stamp = laserCloudMsg->header.stamp; scanMsg.header.frame_id = "/velo_link"; pubEachScan[i].publish(scanMsg); } } printf("scan registration time %f ms *************\n", t_whole.toc()); if(t_whole.toc() > 100) ROS_WARN("scan registration process over 100ms"); } int main(int argc, char **argv) { ros::init(argc, argv, "aloam_scan_registration_node"); ros::NodeHandle nh; nh.param<int>("scan_line", N_SCANS, 16); nh.param<double>("minimum_range", MINIMUM_RANGE, 0.1); printf("scan line number %d \n", N_SCANS); if( N_SCANS != 16 && N_SCANS != 32 && N_SCANS != 64 ) { printf("only support velodyne with 16, 32 or 64 scan line!"); return EXIT_SUCCESS; } ros::Subscriber subLaserCloud = nh.subscribe<sensor_msgs::PointCloud2>("/kitti/velo/pointcloud", 100, laserCloudHandler); pubLaserCloud = nh.advertise<sensor_msgs::PointCloud2>("/velodyne_cloud_2", 100); pubCornerPointsSharp = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_sharp", 100); pubCornerPointsLessSharp = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_less_sharp", 100); pubSurfPointsFlat = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_flat", 100); pubSurfPointsLessFlat = nh.advertise<sensor_msgs::PointCloud2>("/laser_cloud_less_flat", 100); pubRemovePoints = nh.advertise<sensor_msgs::PointCloud2>("/laser_remove_points", 100); if(PUB_EACH_LINE) { for(int i = 0; i < N_SCANS; i++) { ros::Publisher tmp = nh.advertise<sensor_msgs::PointCloud2>("/laser_scanid_" + std::to_string(i), 100); pubEachScan.push_back(tmp); } } ros::spin(); return EXIT_SUCCESS; }
36.454724
351
0.562503
[ "vector" ]
ce08962c9e9e66b3ba70ec2f3af166c39ba910e6
58,764
cpp
C++
src/Ext/Techno/Hooks.cpp
Otamaa/Antares
7241a5ff20f4dbf7153cc77e16edca5c9db473d4
[ "BSD-4-Clause" ]
4
2021-04-24T04:34:06.000Z
2021-09-19T13:55:33.000Z
src/Ext/Techno/Hooks.cpp
Otamaa/Antares
7241a5ff20f4dbf7153cc77e16edca5c9db473d4
[ "BSD-4-Clause" ]
null
null
null
src/Ext/Techno/Hooks.cpp
Otamaa/Antares
7241a5ff20f4dbf7153cc77e16edca5c9db473d4
[ "BSD-4-Clause" ]
2
2021-08-17T14:44:45.000Z
2021-09-19T11:02:04.000Z
#include "Body.h" #include "../Rules/Body.h" #include "../TechnoType/Body.h" #include "../Building/Body.h" #include "../BuildingType/Body.h" #include "../Rules/Body.h" #include "../Tiberium/Body.h" #include "../WarheadType/Body.h" #include "../WeaponType/Body.h" #include "../../Misc/Debug.h" #include "../../Misc/JammerClass.h" #include "../../Misc/PoweredUnitClass.h" #include <AircraftClass.h> #include <GameOptionsClass.h> #include <HouseClass.h> #include <InfantryClass.h> #include <SpecificStructures.h> #include <TiberiumClass.h> #include <UnitClass.h> #include <algorithm> // bugfix #297: Crewed=yes jumpjets spawn parachuted infantry on destruction, not idle DEFINE_HOOK(737F97, UnitClass_ReceiveDamage, 0) { GET(UnitClass *, t, ESI); GET_STACK(TechnoClass *, Killer, 0x54); GET_STACK(bool, select, 0x13); GET_STACK(bool, ignoreDefenses, 0x58); TechnoExt::SpawnSurvivors(t, Killer, select, ignoreDefenses); R->EBX(-1); // #1489302 trucks and crates return 0x73838A; } // bugfix #297: Crewed=yes AircraftTypes spawn parachuting infantry on death DEFINE_HOOK(41668B, AircraftClass_ReceiveDamage, 6) { GET(AircraftClass *, a, ESI); GET_STACK(TechnoClass *, Killer, 0x28); GET_STACK(int, ignoreDefenses, 0x20); bool select = a->IsSelected && a->Owner->ControlledByPlayer(); TechnoExt::SpawnSurvivors(a, Killer, select, ignoreDefenses != 0); // Crashable support for aircraft if(auto pExt = TechnoTypeExt::ExtMap.Find(a->GetTechnoType())) { if(!pExt->Crashable.Get(true)) { R->EAX(0); return 0x41669A; } } return 0; } // rotation when crashing made optional DEFINE_HOOK(4DECAE, FootClass_Crash_Spin, 5) { GET(FootClass*, pThis, ESI); auto pExt = TechnoTypeExt::ExtMap.Find(pThis->GetTechnoType()); return pExt->CrashSpin ? 0u : 0x4DED4Bu; } // move to the next hva frame, even if this unit isn't moving DEFINE_HOOK(4DA8B2, FootClass_Update_AnimRate, 6) { GET(FootClass*, pThis, ESI); auto pType = pThis->GetTechnoType(); auto pExt = TechnoTypeExt::ExtMap.Find(pType); enum { Undecided = 0u, NoChange = 0x4DAA01u, Advance = 0x4DA9FBu }; // any of these prevents the animation to advance to the next frame if(pThis->IsBeingWarpedOut() || pThis->IsWarpingIn() || pThis->IsAttackedByLocomotor) { return NoChange; } // animate unit whenever in air if(pExt->AirRate && pThis->GetHeight() > 0) { return (Unsorted::CurrentFrame % pExt->AirRate) ? NoChange : Advance; } return Undecided; } DEFINE_HOOK(6F9E50, TechnoClass_Update, 5) { GET(TechnoClass* const, pThis, ECX); auto const pType = pThis->GetTechnoType(); auto const pData = TechnoExt::ExtMap.Find(pThis); auto const pTypeData = TechnoTypeExt::ExtMap.Find(pType); // #1208 if(pTypeData->PassengerTurret) { // 18 = 1 8 = A H = Adolf Hitler. Clearly we can't allow it to come to that. auto const passengerNumber = Math::min(pThis->Passengers.NumPassengers, 17); pThis->CurrentTurretNumber = Math::min(passengerNumber, pType->TurretCount - 1); } // #617 powered units if(!pTypeData->PoweredBy.empty()) { if(!pData->PoweredUnit) { pData->PoweredUnit = std::make_unique<PoweredUnitClass>(pThis); } if(!pData->PoweredUnit->Update()) { TechnoExt::Destroy(pThis); } } AttachEffectClass::Update(pThis); return 0; } //! TechnoClass::Update is called every frame; returning 0 tells it to execute the original function's code as well. //! EXCEPT if the target is under Temporal, use the 71A860 hook for that - Graion, 2013-06-13. DEFINE_HOOK(6F9E76, TechnoClass_Update_CheckOperators, 6) { GET(TechnoClass* const, pThis, ESI); // object this is called on auto const pData = TechnoExt::ExtMap.Find(pThis); // Related to operators/drivers, issue #342 auto const pBuildingBelow = pThis->GetCell()->GetBuilding(); auto const buildingBelowIsMe = pThis == pBuildingBelow; /* Conditions checked: pBuildingBelow will be NULL if no building was found This check ensures that Operator'd units don't Deactivate above structures such as War Factories, Repair Depots or Battle Bunkers. (Which is potentially abusable, but let's hope no one figures that out.) */ if(!pBuildingBelow || (buildingBelowIsMe && pBuildingBelow->IsPowerOnline())) { bool Override = false; if(auto const pFoot = abstract_cast<FootClass*>(pThis)) { if(!pBuildingBelow) { // immobile, though not disabled. like hover tanks after // a repair depot has been sold or warped away. Override = (pFoot->Locomotor->Is_Powered() == pThis->Deactivated); } } if(pData->IsOperated()) { // either does have an operator or doesn't need one, so... if(Override || (pThis->Deactivated && !pThis->IsUnderEMP() && pData->IsPowered())) { // ...if it's currently off, turn it on! (oooh baby) pThis->Reactivate(); if(buildingBelowIsMe) { pThis->Owner->RecheckTechTree = true; // #885 } } } else { // doesn't have an operator, so... if(!pThis->Deactivated) { // ...if it's not off yet, turn it off! pThis->Deactivate(); if(buildingBelowIsMe) { pThis->Owner->RecheckTechTree = true; // #885 } } } } // prevent disabled units from driving around. if(pThis->Deactivated) { if(auto const pUnit = abstract_cast<UnitClass*>(pThis)) { if(pUnit->Locomotor->Is_Moving() && pUnit->Destination && !pThis->LocomotorSource) { pUnit->SetDestination(nullptr, true); pUnit->StopMoving(); } } // dropping Radar Jammers (#305) here for now; should check if another TechnoClass::Update hook might be better ~Ren if(pData->RadarJam) { // RadarJam should only be non-null if the object is an active radar jammer pData->RadarJam->UnjamAll(); } } else { // dropping Radar Jammers (#305) here for now; should check if another TechnoClass::Update hook might be better ~Ren auto const pType = pThis->GetTechnoType(); auto const pTypeData = TechnoTypeExt::ExtMap.Find(pType); if(pTypeData->RadarJamRadius) { if(!pData->RadarJam) { pData->RadarJam = std::make_unique<JammerClass>(pThis); } pData->RadarJam->Update(); } } /* using 0x6F9E7C instead makes this function override the original game one's entirely - don't activate that unless you handle _everything_ originally handled by the game */ return 0; } // Radar Jammers (#305) unjam all on owner change DEFINE_HOOK(7014D5, TechnoClass_ChangeOwnership_RadarJammer, 6) { GET(TechnoClass* const, pThis, ESI); auto const pExt = TechnoExt::ExtMap.Find(pThis); if(auto const& pJammer = pExt->RadarJam) { pJammer->UnjamAll(); } return 0; } // fix for vehicle paradrop alignment DEFINE_HOOK(415CA6, AircraftClass_Paradrop, 6) { GET(AircraftClass *, A, EDI); GET(FootClass *, P, ESI); if(P->WhatAmI() != AbstractType::Unit) { return 0; } CoordStruct SrcXYZ = A->GetCoords(); LEA_STACK(CoordStruct *, XYZ, 0x20); XYZ->X = (SrcXYZ.X & ~0xFF) + 0x80; XYZ->Y = (SrcXYZ.Y & ~0xFF) + 0x80; XYZ->Z = SrcXYZ.Z - 1; R->ECX<CoordStruct *>(XYZ); return 0x415DE3; } // #1232: fix for dropping units out of flying Carryalls DEFINE_HOOK(415DF6, AircraftClass_Paradrop_Carryall, 6) { GET(FootClass *, pTechno, ESI); pTechno->IsOnCarryall = false; return 0; } DEFINE_HOOK(6F407D, TechnoClass_Init_1, 6) { GET(TechnoClass* const, pThis, ESI); auto const pType = pThis->GetTechnoType(); auto const pData = TechnoExt::ExtMap.Find(pThis); CaptureManagerClass* pCapturer = nullptr; ParasiteClass* pParasite = nullptr; TemporalClass* pTemporal = nullptr; auto const pFoot = abstract_cast<FootClass*>(pThis); auto const CheckWeapon = [=, &pCapturer, &pParasite, &pTemporal]( WeaponTypeClass* pWeapon, int idxWeapon, const char* pTagName) { constexpr auto const Note = "Constructing an instance of [%s]:\r\n" "%s %s (slot %d) has no %s!"; if(!pWeapon->Projectile) { Debug::FatalErrorAndExit( Note, pType->ID, pTagName, pWeapon->ID, idxWeapon, "Projectile"); } auto const pWarhead = pWeapon->Warhead; if(!pWarhead) { Debug::FatalErrorAndExit( Note, pType->ID, pTagName, pWeapon->ID, idxWeapon, "Warhead"); } if(pWarhead->MindControl && !pCapturer) { pCapturer = GameCreate<CaptureManagerClass>( pThis, pWeapon->Damage, pWeapon->InfiniteMindControl); } if(pWarhead->Temporal && !pTemporal) { pTemporal = GameCreate<TemporalClass>(pThis); pTemporal->WarpPerStep = pWeapon->Damage; pData->idxSlot_Warp = static_cast<BYTE>(idxWeapon); } if(pWarhead->Parasite && pFoot && !pParasite) { pParasite = GameCreate<ParasiteClass>(pFoot); pData->idxSlot_Parasite = static_cast<BYTE>(idxWeapon); } }; // iterate all weapons and their elite counterparts for(auto i = 0; i < TechnoTypeClass::MaxWeapons; ++i) { if(auto const pWeapon = pType->Weapon[i].WeaponType) { CheckWeapon(pWeapon, i, "Weapon"); } if(auto const pWeapon = pType->EliteWeapon[i].WeaponType) { CheckWeapon(pWeapon, i, "EliteWeapon"); } } pThis->CaptureManager = pCapturer; pThis->TemporalImUsing = pTemporal; if(pFoot) { pFoot->ParasiteImUsing = pParasite; } auto const pHouseType = pThis->Owner->Type; pData->OriginalHouseType = pHouseType->FindParentCountry(); if(!pData->OriginalHouseType) { pData->OriginalHouseType = pHouseType; } // if override is in effect, do not create initial payload. // this object might have been deployed, undeployed, ... if(Unsorted::IKnowWhatImDoing && Unsorted::CurrentFrame) { pData->PayloadCreated = true; } return 0x6F4102; } DEFINE_HOOK(6F4103, TechnoClass_Init_2, 6) { return 0x6F41C0; } DEFINE_HOOK(446EE2, BuildingClass_Place_InitialPayload, 6) { GET(BuildingClass* const, pThis, EBP); auto const pExt = TechnoExt::ExtMap.Find(pThis); pExt->CreateInitialPayload(); return 0; } DEFINE_HOOK(4D718C, FootClass_Put_InitialPayload, 6) { GET(FootClass* const, pThis, ESI); if(pThis->WhatAmI() != AbstractType::Infantry) { auto const pExt = TechnoExt::ExtMap.Find(pThis); pExt->CreateInitialPayload(); } return 0; } // temporal per-slot DEFINE_HOOK(71A84E, TemporalClass_UpdateA, 5) { GET(TemporalClass* const, pThis, ESI); // it's not guaranteed that there is a target if(auto const pTarget = pThis->Target) { auto const pExt = TechnoExt::ExtMap.Find(pTarget); // Temporal should disable RadarJammers pExt->RadarJam = nullptr; //AttachEffect handling under Temporal if(!pExt->AttachEffects_RecreateAnims) { for(auto& Item : pExt->AttachedEffects) { if(Item.Type->TemporalHidesAnim) { Item.KillAnim(); } } pExt->AttachEffects_RecreateAnims = true; } } pThis->WarpRemaining -= pThis->GetWarpPerStep(0); R->EAX(pThis->WarpRemaining); return 0x71A88D; } // temporal per-slot DEFINE_HOOK(71AB30, TemporalClass_GetHelperDamage, 5) { GET(TemporalClass *, Temp, ESI); TechnoClass *T = Temp->Owner; TechnoExt::ExtData *pData = TechnoExt::ExtMap.Find(T); WeaponStruct *W = T->GetWeapon(pData->idxSlot_Warp); WarheadTypeExt::Temporal_WH = W->WeaponType->Warhead; R->EAX<WeaponStruct *>(W); return 0x71AB47; } // parasite per-slot DEFINE_HOOK(62A020, ParasiteClass_Update, A) { GET(TechnoClass *, T, ECX); TechnoExt::ExtData *pData = TechnoExt::ExtMap.Find(T); WeaponStruct *W = T->GetWeapon(pData->idxSlot_Parasite); R->EAX<WeaponStruct *>(W); return 0x62A02A; } DEFINE_HOOK(62A7B1, Parasite_ExitUnit, 9) { GET(TechnoClass *, T, ECX); TechnoExt::ExtData *pData = TechnoExt::ExtMap.Find(T); WeaponStruct *W = T->GetWeapon(pData->idxSlot_Parasite); R->EAX<WeaponStruct *>(W); return 0x62A7BA; } DEFINE_HOOK(629804, ParasiteClass_UpdateSquiddy, 9) { GET(TechnoClass *, T, ECX); TechnoExt::ExtData *pData = TechnoExt::ExtMap.Find(T); WeaponStruct *W = T->GetWeapon(pData->idxSlot_Parasite); R->EAX<WeaponStruct *>(W); return 0x62980D; } /* DEFINE_HOOK(6F3330, TechnoClass_SelectWeapon, 5) { GET(TechnoClass *, pThis, ECX); GET_STACK(TechnoClass *, pTarg, 0x4); DWORD Selected = TechnoClassExt::SelectWeaponAgainst(pThis, pTarg); R->EAX(Selected); return 0x6F3813; } int TechnoClassExt::SelectWeaponAgainst(TechnoClass *pThis, TechnoClass *pTarget) { int Index = 0; WeaponStruct* W1 = pThis->GetWeapon(0); WeaponTypeClass* W1T = W1->WeaponType; WeaponStruct* W2 = pThis->GetWeapon(1); WeaponTypeClass* W2T = W2->WeaponType; TechnoTypeClass *pThisT = pThis->GetTechnoType(); // TechnoTypeClass *pTargetT = pTarget->GetTechnoType(); if(pThisT->HasMultipleTurrets() && !pThisT->get_IsGattling()) { return pThis->get_CurrentTurret(); } if(pThis->CanOccupyFire()) { return 0; } if(pThis->get_InOpenToppedTransport()) { Index = pThisT->get_OpenTransportWeapon(); if(Index != -1) { return Index; } } if(pThisT->get_IsGattling()) { int CurrentStage = pThis->get_CurrentGattlingStage() * 2; if(pTarget->get_AbstractFlags() & ABSFLAGS_ISTECHNO && pTarget->IsInAir()) { if(W2T && W2T->get_Projectile()->get_AA()) { return CurrentStage + 1; } } return CurrentStage; } if(pThis->WhatAmI() == abs_Building && ((BuildingClass *)pThis)->get_IsOverpowered()) { return 1; } if(pTarget->WhatAmI() == abs_Aircraft && ((AircraftClass *)pTarget)->get_IsCrashing()) { return 1; } // haaaaaaaate if(pTarget->WhatAmI() == abs_Cell) { CellClass *pTargetCell = (CellClass *)pTarget; if( (pTargetCell->get_LandType() != lt_Water && pTargetCell->IsOnFloor()) || ((pTargetCell->get_Flags() & cf_Bridge) && pThisT->get_Naval()) && (!pTargetCell->IsInAir() && pThisT->get_LandTargeting() == 2) ) { return 1; } } eLandType ltTgt = pTarget->GetCell()->get_LandType(); bool InWater = !pTarget->get_OnBridge() && !pTarget->IsInAir() && (ltTgt == 2 || ltTgt == 6); if(InWater) { Index = pThis->SelectNavalTargeting(pTarget); if(Index != -1) { return Index; } else { return 0; // what? } } if(!pTarget->IsInAir() && pThisT->get_LandTargeting() == 2) { return 1; } int WCount = pThisT->get_WeaponCount(); if(WCount < 1) { return 0; } std::vector<WeaponTypeClassExt::WeaponWeight> Weights(WCount); // Weights.reserve(WCount); for(short i = 0; i < WCount; ++i) { WeaponTypeClass* W = pThis->GetWeapon(Index)->WeaponType; Weights[i].index = i; if(W) { CoordStruct xyz1 = *pThis->get_Location(); CoordStruct xyz2 = *pTarget->get_Location(); float distance = abs(xyz1.DistanceFrom(xyz2)); bool CloseEnough = distance <= W->get_Range() && distance >= W->get_MinimumRange(); Weights[i].DPF = TechnoClassExt::EvalVersesAgainst(pThis, pTarget, W); Weights[i].InRange = CloseEnough; } else { Weights[i].DPF = 0.0; Weights[i].InRange = 0; } } std::stable_sort(Weights.begin(), Weights.end()); std::reverse(Weights.begin(), Weights.end()); return Weights[0].index; } float TechnoClassExt::EvalVersesAgainst(TechnoClass *pThis, TechnoClass *pTarget, WeaponTypeClass* W) { WarheadTypeClass *WH = W->get_Warhead(); WarheadTypeClassExt::WarheadTypeClassData *pData = WarheadTypeClassExt::Ext_p[WH]; float Verses = pData->Verses[pTarget->GetType()->get_Armor()]; return W->get_Damage() * Verses / W->get_ROF(); } bool TechnoClassExt::EvalWeaponAgainst(TechnoClass *pThis, TechnoClass *pTarget, WeaponTypeClass* W) { if(!W || W->get_NeverUse()) { return 0; } WarheadTypeClass *WH = W->get_Warhead(); if(!WH) { return 0; } // TechnoTypeClass *pThisT = pThis->GetTechnoType(); TechnoTypeClass *pTargetT = pTarget->GetTechnoType(); if(WH->get_Airstrike()) { if(pTarget->WhatAmI() != abs_Building) { return 0; } BuildingTypeClass *pBT = ((BuildingClass *)pTarget)->get_Type(); // not my design, leave me alone return pBT->get_CanC4() && (!pBT->get_ResourceDestination() || !pBT->get_ResourceGatherer()); } if(WH->get_IsLocomotor()) { return (pTarget->get_AbstractFlags() & ABSFLAGS_ISFOOT) != 0; } if(W->get_DrainWeapon()) { return pTargetT->get_Drainable() && !pThis->get_DrainTarget() && !pThis->get_Owner()->IsAlliedWith(pTarget); } if(W->get_AreaFire()) { return pThis->GetCurrentMission() == mission_Unload; } if(pTarget->WhatAmI() == abs_Building && ((BuildingClass *)pTarget)->get_Type()->get_Overpowerable()) { return WH->get_ElectricAssault() && pThis->get_Owner()->CanOverpower(pTarget); } if(pTarget->IsInAir() && !W->get_Projectile()->get_AA()) { return 0; } if(pTarget->IsOnFloor() && !W->get_Projectile()->get_AG()) { return 0; } return 1; } */ DEFINE_HOOK(51F76D, InfantryClass_Unload, 5) { GET(TechnoClass *, I, ESI); TechnoTypeExt::ExtData *pData = TechnoTypeExt::ExtMap.Find(I->GetTechnoType()); return pData->Is_Deso ? 0x51F77Du : 0x51F792u; } DEFINE_HOOK(51CE9A, InfantryClass_Idle, 5) { GET(InfantryClass *, I, ESI); TechnoTypeExt::ExtData *pData = TechnoTypeExt::ExtMap.Find(I->GetTechnoType()); // don't play idle when paralyzed if(I->IsUnderEMP()) { R->BL(false); return 0x51CECD; } R->EDI(R->EAX()); // argh R->BL(pData->Is_Cow); // aaaargh! again! return pData->Is_Cow ? 0x51CEAEu : 0x51CECDu; } DEFINE_HOOK(747BBD, UnitTypeClass_LoadFromINI, 5) { GET(UnitTypeClass *, U, ESI); U->AltImage = R->EAX<SHPStruct *>(); // jumping over, so replicated return U->Gunner ? 0x747BD7u : 0x747E90u; } // godawful hack - Desolator deploy fire is triggered by ImmuneToRadiation ! DEFINE_HOOK(5215F9, InfantryClass_UpdateDeploy, 6) { GET(TechnoClass *, I, ESI); return TechnoTypeExt::ExtMap.Find(I->GetTechnoType())->Is_Deso ? 0x5216B6u : 0x52160Du; } // 52138C, 6 // godawful hack 2 - Desolator deploy fire is triggered by ImmuneToRadiation ! // DON'T USE EXPORT_FUNC(InfantryClass_UpdateDeploy2) { /* GET(TechnoClass *, I, ESI); TechnoTypeClassExt::TechnoTypeClassData *pData = TechnoTypeClassExt::Ext_p[I->GetTechnoType()]; return pData->Is_Deso_Radiation ? 0x52139A : 0x5214B9; WRONG: needs more code to reimplement weapon shooting without rad checks */ return 0; } // stops movement sound from being played while unit is being pulled by a magnetron (see terror drone) DEFINE_HOOK(7101CF, FootClass_ImbueLocomotor, 7) { GET(FootClass *, F, ESI); F->Audio7.ShutUp(); return 0; } DEFINE_HOOK(4DAA68, FootClass_Update_MoveSound, 6) { GET(FootClass *, F, ESI); if(F->unknown_bool_53C) { return 0x4DAAEE; } if(F->LocomotorSource) { F->Audio7.ShutUp(); return 0x4DAAEE; } return 0x4DAA70; } /* #397 - AffectsEnemies */ DEFINE_HOOK(701C97, TechnoClass_ReceiveDamage_AffectsEnemies, 6) { GET(WarheadTypeClass *, pThis, EBP); GET(TechnoClass *, Victim, ESI); LEA_STACK(args_ReceiveDamage *, Arguments, 0xC8); // get the owner of the attacker. if there's none, use source house auto pSourceHouse = Arguments->Attacker ? Arguments->Attacker->Owner : Arguments->SourceHouse; // default for ownerless damage i.e. crates/fire particles bool CanAffect = true; // check if allied to target, then apply either AffectsAllies or AffectsEnemies if(pSourceHouse) { auto pExt = WarheadTypeExt::ExtMap.Find(pThis); CanAffect = Victim->Owner->IsAlliedWith(pSourceHouse) ? pThis->AffectsAllies : pExt->AffectsEnemies; /* Ren, 08.01.2011: <not applicable any more \> The question of how this works came up because the current treatment of Neutral is technically wrong: Semantically, AffectsEnemies=no only means "you cannot attack enemies", but our code renders it as "you cannot attack non-allies"; this obviously means that AffectsEnemies=no includes being unable to attack Neutral, despite the fact that Neutral is, well, neutral - not our enemy. In the specific situation this came up in, the current behavior was desired and no one else complained so far, so I'm not proposing a change at this point. In fact, since this flag is AffectsAllies's evil twin, it is very most likely that practically *all* users of AffectsEnemies assume this behavior; he who sets AffectsEnemies=no likely does so with the intention of limiting damage to allied troops. I just wanted this behavior and the logic behind it to be documented for the future. Note that, in the specific case of AffectsEnemies=no, AffectsAllies=no, this will rear its ugly head as a bug: Neutral should be affected, but won't be. */ /* AlexB, 2013-08-19: "You're either with us, or against us" -- Old saying in Tennessee, ... or was it Texas? The game has no clear concept of neutrality. If something like that is going to be added, it could be in the form of a Nullable<bool> AffectsNeutral, and a CanAffect = AffectsNeutral.Get(CanAffect) if the source house is neutral (however this is going to be inferred). */ } return CanAffect ? 0x701CD7u : 0x701CC2u; } // select the most appropriate firing voice and also account // for undefined flags, so you actually won't lose functionality // when a unit becomes elite. DEFINE_HOOK(7090A8, TechnoClass_SelectFiringVoice, 0) { GET(TechnoClass*, pThis, ESI); GET(TechnoClass*, pTarget, ECX); TechnoTypeClass* pType = pThis->GetTechnoType(); TechnoTypeExt::ExtData* pData = TechnoTypeExt::ExtMap.Find(pType); int idxVoice = -1; int idxWeapon = pThis->SelectWeapon(pTarget); WeaponTypeClass* pWeapon = pThis->GetWeapon(idxWeapon)->WeaponType; // repair if(pWeapon && pWeapon->Damage < 0) { idxVoice = pData->VoiceRepair; if(idxVoice < 0) { if(!_strcmpi(pType->ID, "FV")) { idxVoice = RulesClass::Instance->VoiceIFVRepair; } } } // don't mix them up, but fall back to rookie voice if there // is no elite voice. if(idxVoice < 0) { if(idxWeapon) { // secondary if(pThis->Veterancy.IsElite()) { idxVoice = pType->VoiceSecondaryEliteWeaponAttack; } if(idxVoice < 0) { idxVoice = pType->VoiceSecondaryWeaponAttack; } } else { // primary if(pThis->Veterancy.IsElite()) { idxVoice = pType->VoicePrimaryEliteWeaponAttack; } if(idxVoice < 0) { idxVoice = pType->VoicePrimaryWeaponAttack; } } } // generic attack voice if(idxVoice < 0 && pType->VoiceAttack.Count) { unsigned int idxRandom = Randomizer::Global()->Random(); idxVoice = pType->VoiceAttack.GetItem(idxRandom % pType->VoiceAttack.Count); } // play voice if(idxVoice > -1) { pThis->QueueVoice(idxVoice); } return 0x7091C5; } // Support per unit modification of Iron Curtain effect duration DEFINE_HOOK(70E2B0, TechnoClass_IronCurtain, 5) { GET(TechnoClass*, pThis, ECX); GET_STACK(int, duration, STACK_OFFS(0x0, -0x4)); //GET_STACK(HouseClass*, source, STACK_OFFS(0x0, -0x8)); GET_STACK(bool, force, STACK_OFFS(0x0, -0xC)); // if it's no force shield then it's the iron curtain. auto pData = TechnoTypeExt::ExtMap.Find(pThis->GetTechnoType()); double modifier = force ? pData->ForceShield_Modifier : pData->IronCurtain_Modifier; duration = static_cast<int>(duration * modifier); pThis->IronCurtainTimer.Start(duration); pThis->IronTintStage = 0; pThis->ForceShielded = force ? TRUE : FALSE; R->EAX(DamageState::Unaffected); return 0x70E2FD; } // update the vehicle thief's destination. needed to follow a // target without the requirement to also enable Thief=yes. DEFINE_HOOK(5202F9, InfantryClass_UpdateVehicleThief_Check, 6) { GET(InfantryClass*, pThis, ESI); // good old WW checks for Thief. idiots. if(!pThis->Type->VehicleThief) { // also allow for drivers, because vehicles may still drive around. usually they are not. TechnoTypeExt::ExtData* pTypeExt = TechnoTypeExt::ExtMap.Find(pThis->Type); if(!pTypeExt->CanDrive) { return 0x5206A1; } } return 0x52030D; } // the hijacker is close to the target. capture. DEFINE_HOOK(5203F7, InfantryClass_UpdateVehicleThief_Hijack, 5) { enum {GoOn = 0x5206A1, Stop = 0x520473}; GET(InfantryClass*, pThis, ESI); GET(FootClass*, pTarget, EDI); TechnoExt::ExtData* pExt = TechnoExt::ExtMap.Find(pThis); bool finalize = pExt->PerformActionHijack(pTarget); if(finalize) { // manually deinitialize this infantry pThis->UnInit(); } return finalize ? Stop : GoOn; } DEFINE_HOOK(51E7BF, InfantryClass_GetCursorOverObject_CanCapture, 6) { GET(InfantryClass *, pSelected, EDI); GET(ObjectClass *, pTarget, ESI); enum { Capture = 0x51E84B, // the game will return an Enter cursor no questions asked DontCapture = 0x51E85A, // the game will assume this is not a VehicleThief and will check for other cursors normally Select = 0x51E7EF, // select target instead of ordering this DontMindMe = 0, // the game will check if this is a VehicleThief } DoWhat = DontMindMe; if(TechnoClass* pTechno = generic_cast<TechnoClass*>(pTarget)) { if(pTechno->GetTechnoType()->IsTrain) { DoWhat = Select; } else { TechnoExt::ExtData* pExt = TechnoExt::ExtMap.Find(pSelected); TechnoTypeExt::ExtData* pTypeExt = TechnoTypeExt::ExtMap.Find(pSelected->Type); if(pSelected->Type->VehicleThief || pTypeExt->CanDrive) { DoWhat = (pExt->GetActionHijack(pTechno) != AresAction::None ? Capture : DontCapture); } } } return DoWhat; } // change all the special things infantry do, like vehicle thief, infiltration, // bridge repair, enter transports or bio reactors, ... DEFINE_HOOK(519675, InfantryClass_UpdatePosition_BeforeInfantrySpecific, A) { // called after FootClass:UpdatePosition has been called and before // all specific infantry handling takes place. enum { Return = 0x51AA01, // skip the original logic Destroy = 0x51A010, // uninits this infantry and returns Handle = 0 // resume the original function } DoWhat = Handle; GET(InfantryClass*, pThis, ESI); if(pThis) { // steal vehicles / reclaim KillDriver'd units using CanDrive if(pThis->CurrentMission == Mission::Capture) { if(TechnoClass* pDest = generic_cast<TechnoClass*>(pThis->Destination)) { // this is the possible target we stand on CellClass* pCell = pThis->GetCell(); TechnoClass* pTarget = pCell->GetUnit(pThis->OnBridge); if(!pTarget) { pTarget = pCell->GetAircraft(pThis->OnBridge); if(!pTarget) { pTarget = pCell->GetBuilding(); if(pTarget && !pTarget->IsStrange()) { pTarget = nullptr; } } } // reached its destination? if(pTarget && pTarget == pDest) { // reached the target. capture. TechnoExt::ExtData* pExt = TechnoExt::ExtMap.Find(pThis); bool finalize = pExt->PerformActionHijack(pTarget); DoWhat = finalize ? Destroy : Return; } } } } return DoWhat; } DEFINE_HOOK(471C96, CaptureManagerClass_CanCapture, A) { // this is a complete rewrite, because it might be easier to change // this in a central place than spread all over the source code. enum { Allowed = 0x471D2E, // this can be captured Disallowed = 0x471D35 // can't be captured }; GET(CaptureManagerClass*, pThis, ECX); GET(TechnoClass*, pTarget, ESI); TechnoClass* pCapturer = pThis->Owner; // target exists and doesn't belong to capturing player if(!pTarget || pTarget->Owner == pCapturer->Owner) { return Disallowed; } // generally not capturable if(pTarget->GetTechnoType()->ImmuneToPsionics) { return Disallowed; } // disallow capturing bunkered units if(pTarget->BunkerLinkedItem && pTarget->BunkerLinkedItem->WhatAmI() == AbstractType::Unit) { return Disallowed; } // TODO: extend this for mind-control priorities if(pTarget->IsMindControlled() || pTarget->MindControlledByHouse) { return Disallowed; } // free slot? (move on if infinite or single slot which will be freed if used) if(!pThis->InfiniteMindControl && pThis->MaxControlNodes != 1 && pThis->ControlNodes.Count >= pThis->MaxControlNodes) { return Disallowed; } // currently disallowed auto mission = pTarget->CurrentMission; if(pTarget->IsIronCurtained() || mission == Mission::Selling || mission == Mission::Construction) { return Disallowed; } // driver killed. has no mind. TechnoExt::ExtData* pTargetExt = TechnoExt::ExtMap.Find(pTarget); if(pTargetExt->DriverKilled) { return Disallowed; } // passed all tests return Allowed; } DEFINE_HOOK(53C450, TechnoClass_CanBePermaMC, 5) { // complete rewrite. used by psychic dominator, ai targeting, etc. GET(TechnoClass*, pThis, ECX); BYTE ret = 0; if(pThis && pThis->WhatAmI() != AbstractType::Building && !pThis->IsIronCurtained() && !pThis->IsInAir()) { TechnoTypeClass* pType = pThis->GetTechnoType(); if(!pType->ImmuneToPsionics && !pType->BalloonHover) { // KillDriver check TechnoExt::ExtData* pExt = TechnoExt::ExtMap.Find(pThis); if(!pExt->DriverKilled) { ret = 1; } } } R->AL(ret); return 0x53C4BA; } DEFINE_HOOK(73758A, UnitClass_ReceivedRadioCommand_QueryEnterAsPassenger_KillDriver, 6) { // prevent units from getting the enter cursor on transports // with killed drivers. GET(TechnoClass*, pThis, ESI); TechnoExt::ExtData* pExt = TechnoExt::ExtMap.Find(pThis); return (pExt->DriverKilled ? 0x73761Fu : 0u); } DEFINE_HOOK(41946B, AircraftClass_ReceivedRadioCommand_QueryEnterAsPassenger_KillDriver, 6) { // prevent units from getting the enter cursor on transports // with killed drivers. GET(TechnoClass*, pThis, ESI); TechnoExt::ExtData* pExt = TechnoExt::ExtMap.Find(pThis); return (pExt->DriverKilled ? 0x4190DDu : 0u); } DEFINE_HOOK(6F6A58, TechnoClass_DrawHealthBar_HidePips_KillDriver, 6) { // prevent player from seeing pips on transports with killed drivers. GET(TechnoClass*, pThis, ESI); TechnoExt::ExtData* pExt = TechnoExt::ExtMap.Find(pThis); return (pExt->DriverKilled ? 0x6F6AB6u : 0u); } DEFINE_HOOK(7087EB, TechnoClass_ShouldRetaliate_KillDriver, 6) { // prevent units with killed drivers from retaliating. GET(TechnoClass*, pThis, ESI); TechnoExt::ExtData* pExt = TechnoExt::ExtMap.Find(pThis); return (pExt->DriverKilled ? 0x708B17u : 0u); } DEFINE_HOOK(7091D6, TechnoClass_CanPassiveAquire_KillDriver, 6) { // prevent units with killed drivers from looking for victims. GET(TechnoClass*, pThis, ESI); TechnoExt::ExtData* pExt = TechnoExt::ExtMap.Find(pThis); return (pExt->DriverKilled ? 0x70927Du : 0u); } DEFINE_HOOK(6F3283, TechnoClass_CanScatter_KillDriver, 8) { // prevent units with killed drivers from scattering when attacked. GET(TechnoClass*, pThis, ESI); TechnoExt::ExtData* pExt = TechnoExt::ExtMap.Find(pThis); return (pExt->DriverKilled ? 0x6F32C5u : 0u); } DEFINE_HOOK(5198AD, InfantryClass_UpdatePosition_EnteredGrinder, 6) { GET(InfantryClass *, Infantry, ESI); GET(BuildingClass *, Grinder, EBX); BuildingExt::ExtData *pData = BuildingExt::ExtMap.Find(Grinder); if(pData->ReverseEngineer(Infantry)) { if(Infantry->Owner->ControlledByPlayer()) { VoxClass::Play("EVA_ReverseEngineeredInfantry"); VoxClass::Play("EVA_NewTechnologyAcquired"); } } return 0; } DEFINE_HOOK(73A1BC, UnitClass_UpdatePosition_EnteredGrinder, 7) { GET(UnitClass *, Vehicle, EBP); GET(BuildingClass *, Grinder, EBX); BuildingExt::ExtData *pData = BuildingExt::ExtMap.Find(Grinder); if(pData->ReverseEngineer(Vehicle)) { if(Vehicle->Owner->ControlledByPlayer()) { VoxClass::Play("EVA_ReverseEngineeredVehicle"); VoxClass::Play("EVA_NewTechnologyAcquired"); } } // #368: refund hijackers if(Vehicle->HijackerInfantryType != -1) { if(InfantryTypeClass *Hijacker = InfantryTypeClass::Array->GetItem(Vehicle->HijackerInfantryType)) { int refund = Hijacker->GetRefund(Vehicle->Owner, 0); Grinder->Owner->GiveMoney(refund); } } return 0; } DEFINE_HOOK(6F6AC9, TechnoClass_Remove, 6) { GET(TechnoClass *, pThis, ESI); TechnoExt::ExtData* TechnoExt = TechnoExt::ExtMap.Find(pThis); // if the removed object is a radar jammer, unjam all jammed radars TechnoExt->RadarJam = nullptr; // #617 powered units TechnoExt->PoweredUnit = nullptr; //#1573, #1623, #255 attached effects auto& Effects = TechnoExt->AttachedEffects; if(!Effects.empty()) { //auto const pID = pThis->GetTechnoType()->ID; for(auto& Item : Effects) { //Debug::Log("[AttachEffect] Removing %d. item from %s\n", // &Item - Effects.data(), pID); Item.KillAnim(); } auto const it = std::remove_if( Effects.begin(), Effects.end(), [](AttachEffectClass const& Item) { return static_cast<bool>(Item.Type->DiscardOnEntry); }); if(it != Effects.end()) { Effects.erase(it, Effects.end()); TechnoExt->RecalculateStats(); } TechnoExt->AttachEffects_RecreateAnims = true; } return pThis->InLimbo ? 0x6F6C93u : 0x6F6AD5u; } DEFINE_HOOK(74642C, UnitClass_ReceiveGunner, 6) { GET(UnitClass *, Unit, ESI); auto pData = TechnoExt::ExtMap.Find(Unit); pData->MyOriginalTemporal = Unit->TemporalImUsing; Unit->TemporalImUsing = nullptr; return 0; } DEFINE_HOOK(74653C, UnitClass_RemoveGunner, 0) { GET(UnitClass *, Unit, EDI); auto pData = TechnoExt::ExtMap.Find(Unit); Unit->TemporalImUsing = pData->MyOriginalTemporal; pData->MyOriginalTemporal = nullptr; return 0x746546; } DEFINE_HOOK(741206, UnitClass_GetFireError, 6) { GET(UnitClass *, Unit, ESI); auto Type = Unit->Type; if(!Type->TurretCount || Type->IsGattling) { return 0x741229; } auto idxW = Unit->SelectWeapon(nullptr); auto W = Unit->GetWeapon(idxW); return (W->WeaponType && W->WeaponType->Warhead->Temporal) ? 0x741210u : 0x741229u ; } // bug #1290: carryall size limit DEFINE_HOOK(417D75, AircraftClass_GetCursorOverObject_CanTote, 5) { GET(AircraftClass *, pCarryall, ESI); GET(UnitClass *, pTarget, EDI); auto pCarryallData = TechnoTypeExt::ExtMap.Find(pCarryall->Type); return (pCarryallData->CarryallCanLift(pTarget)) ? 0u : 0x417DF6u ; } DEFINE_HOOK(416E37, AircraftClass_Mi_MoveCarryall_CanTote, 5) { GET(AircraftClass *, pCarryall, ESI); GET(UnitClass *, pTarget, EDI); auto pCarryallData = TechnoTypeExt::ExtMap.Find(pCarryall->Type); return (pCarryallData->CarryallCanLift(pTarget)) ? 0u : 0x416EC9u ; } DEFINE_HOOK(416C4D, AircraftClass_Carryall_Unload_DestroyCargo, 5) { GET(AircraftClass* , pCarryall, EDI); GET(UnitClass *, pCargo, ESI); int Damage = pCargo->Health; pCargo->ReceiveDamage(&Damage, 0, RulesClass::Instance->C4Warhead, nullptr, true, true, nullptr); Damage = pCarryall->Health; pCarryall->ReceiveDamage(&Damage, 0, RulesClass::Instance->C4Warhead, nullptr, true, true, nullptr); return 0x416C53; } DEFINE_HOOK(416C94, AircraftClass_Carryall_Unload_UpdateCargo, 6) { GET(UnitClass *, pCargo, ESI); pCargo->UpdatePosition(2); if(pCargo->Deactivated && pCargo->Locomotor->Is_Powered()) { pCargo->Locomotor->Power_Off(); } return 0; } // support Occupier and VehicleThief on one type. if this is not done // the Occupier handling will leave a dangling Destination pointer. DEFINE_HOOK(4D9A83, FootClass_PointerGotInvalid_OccupierVehicleThief, 6) { GET(InfantryClass*, pInfantry, ESI); GET(InfantryTypeClass*, pType, EAX); if(pType->VehicleThief) { if(abstract_cast<FootClass*>(pInfantry->Destination)) { return 0x4D9AB9; } } return 0; } // issue #895788: cells' high occupation flags are marked only if they // actually contains a bridge while unmarking depends solely on object // height above ground. this mismatch causes the cell to become blocked. DEFINE_HOOK(7441B6, UnitClass_MarkOccupationBits, 6) { GET(UnitClass*, pThis, ECX); GET(CoordStruct*, pCrd, ESI); CellClass* pCell = MapClass::Instance->GetCellAt(*pCrd); int height = MapClass::Instance->GetCellFloorHeight(*pCrd) + CellClass::BridgeHeight; bool alt = (pCrd->Z >= height && pCell->ContainsBridge()); // remember which occupation bit we set auto pExt = TechnoExt::ExtMap.Find(pThis); pExt->AltOccupation = alt; if(alt) { pCell->AltOccupationFlags |= 0x20; } else { pCell->OccupationFlags |= 0x20; } return 0x744209; } DEFINE_HOOK(744216, UnitClass_UnmarkOccupationBits, 6) { GET(UnitClass*, pThis, ECX); GET(CoordStruct*, pCrd, ESI); enum { obNormal = 1, obAlt = 2 }; CellClass* pCell = MapClass::Instance->GetCellAt(*pCrd); int height = MapClass::Instance->GetCellFloorHeight(*pCrd) + CellClass::BridgeHeight; int alt = (pCrd->Z >= height) ? obAlt : obNormal; // also clear the last occupation bit, if set auto pExt = TechnoExt::ExtMap.Find(pThis); if(!pExt->AltOccupation.empty()) { int lastAlt = pExt->AltOccupation ? obAlt : obNormal; alt |= lastAlt; pExt->AltOccupation.clear(); } if(alt & obAlt) { pCell->AltOccupationFlags &= ~0x20; } if(alt & obNormal) { pCell->OccupationFlags &= ~0x20; } return 0x74425E; } DEFINE_HOOK(70DEBA, TechnoClass_UpdateGattling_Cycle, 6) { GET(TechnoClass*, pThis, ESI); GET(int, lastStageValue, EAX); GET_STACK(int, a2, 0x24); auto pType = pThis->GetTechnoType(); if(pThis->GattlingValue < lastStageValue) { // just increase the value pThis->GattlingValue += a2 * pType->RateUp; } else { // if max or higher, reset cyclic gattlings auto pExt = TechnoTypeExt::ExtMap.Find(pType); if(pExt->GattlingCyclic) { pThis->GattlingValue = 0; pThis->CurrentGattlingStage = 0; pThis->Audio4.DTOR_1(); pThis->unknown_bool_4B8 = false; } } // recreate hooked instruction R->Stack<int>(0x10, pThis->GattlingValue); return 0x70DEEB; } // make the space between gunner name segment and ifv // name smart. it disappears if one of them is empty, // eliminating leading and trailing spaces. DEFINE_HOOK(746C55, UnitClass_GetUIName, 6) { GET(UnitClass*, pThis, ESI); GET(wchar_t*, pGunnerName, EAX); auto pName = pThis->Type->UIName; auto pSpace = L""; if(pName && *pName && pGunnerName && *pGunnerName) { pSpace = L" "; } _snwprintf_s(pThis->ToolTipText, _TRUNCATE, L"%s%s%s", pGunnerName, pSpace, pName); R->EAX(pThis->ToolTipText); return 0x746C76; } // spawn tiberium when a unit dies. this is a minor part of the // tiberium heal feature. the actual healing happens in FootClass_Update. DEFINE_HOOK(702216, TechnoClass_ReceiveDamage_TiberiumHeal, 6) { GET(TechnoClass*, pThis, ESI); TechnoTypeClass* pType = pThis->GetTechnoType(); auto pExt = TechnoTypeExt::ExtMap.Find(pType); // TS did not check for HasAbility here, either if(pExt->TiberiumRemains.Get(pType->TiberiumHeal && RulesExt::Global()->Tiberium_HealEnabled)) { CoordStruct crd = pThis->GetCoords(); CellClass* pCenter = MapClass::Instance->GetCellAt(crd); // increase the tiberium for the four neighbours and center. // center is retrieved by getting a neighbour cell index >= 8 for(auto i = 0u; i < 5u; ++i) { CellClass* pCell = pCenter->GetNeighbourCell(2*i); int value = ScenarioClass::Instance->Random.RandomRanged(0, 2); pCell->IncreaseTiberium(0, value); } } return 0; } // damage the techno when it is moving over a cell containing tiberium DEFINE_HOOK(4D85E4, FootClass_UpdatePosition_TiberiumDamage, 9) { GET(FootClass*, pThis, ESI); int damage = 0; WarheadTypeClass* pWarhead = nullptr; int transmogrify = RulesClass::Instance->TiberiumTransmogrify; if(RulesExt::Global()->Tiberium_DamageEnabled && pThis->GetHeight() <= RulesClass::Instance->HoverHeight) { TechnoTypeClass* pType = pThis->GetTechnoType(); TechnoTypeExt::ExtData* pExt = TechnoTypeExt::ExtMap.Find(pType); // default is: infantry can be damaged, others cannot bool enabled = (pThis->WhatAmI() != InfantryClass::AbsID); if(!pExt->TiberiumProof.Get(enabled) && !pThis->HasAbility(Ability::TiberiumProof)) { if(pThis->Health > 0) { CellClass* pCell = pThis->GetCell(); int idxTiberium = pCell->GetContainedTiberiumIndex(); if(auto pTiberium = TiberiumClass::Array->GetItemOrDefault(idxTiberium)) { auto pTibExt = TiberiumExt::ExtMap.Find(pTiberium); pWarhead = pTibExt->GetWarhead(); damage = pTibExt->GetDamage(); transmogrify = pExt->TiberiumTransmogrify.Get(transmogrify); } } } } if(damage && pWarhead) { CoordStruct crd = pThis->GetCoords(); if(pThis->ReceiveDamage(&damage, 0, pWarhead, nullptr, false, false, nullptr) == DamageState::NowDead) { TechnoExt::SpawnVisceroid(crd, RulesClass::Instance->SmallVisceroid, transmogrify, false); return 0x4D8F29; } } return 0; } // spill the stored tiberium on destruction DEFINE_HOOK(702200, TechnoClass_ReceiveDamage_SpillTiberium, 6) { GET(TechnoClass*, pThis, ESI); TechnoTypeClass* pType = pThis->GetTechnoType(); auto pExt = TechnoTypeExt::ExtMap.Find(pType); if(pExt->TiberiumSpill) { double stored = pThis->Tiberium.GetTotalAmount(); if(pThis->WhatAmI() != BuildingClass::AbsID && stored > 0.0 && !ScenarioClass::Instance->SpecialFlags.HarvesterImmune) { // don't spill more than we can hold double max = 9.0; if(max > pType->Storage) { max = pType->Storage; } // assume about half full, recalc if possible int value = static_cast<int>(max / 2); if(pType->Storage > 0) { value = Game::F2I(stored / pType->Storage * max); } // get the spill center CoordStruct crd = pThis->GetCoords(); CellClass* pCenter = MapClass::Instance->GetCellAt(crd); const unsigned int Neighbours[] = {9, 2, 7, 1, 4, 3, 0, 5, 6}; for(auto neighbour : Neighbours) { // spill random amount int amount = ScenarioClass::Instance->Random.RandomRanged(0, 2); CellClass* pCell = pCenter->GetNeighbourCell(neighbour); pCell->IncreaseTiberium(0, amount); value -= amount; // stop if value is reached if(value <= 0) { break; } } } } return 0; } // blow up harvester units big time DEFINE_HOOK(738749, UnitClass_Destroy_TiberiumExplosive, 6) { GET(UnitClass*, pThis, ESI); if(RulesClass::Instance->TiberiumExplosive) { if(!ScenarioClass::Instance->SpecialFlags.HarvesterImmune) { if(pThis->Tiberium.GetTotalAmount() > 0.0f) { // multiply the amounts with their powers and sum them up int morePower = 0; for(int i=0; i<TiberiumClass::Array->Count; ++i) { TiberiumClass* pTiberium = TiberiumClass::Array->GetItem(i); double power = pThis->Tiberium.GetAmount(i) * pTiberium->Power; morePower += Game::F2I(power); } // go boom WarheadTypeClass* pWH = RulesExt::Global()->Tiberium_ExplosiveWarhead; if(morePower > 0 && pWH) { CoordStruct crd = pThis->GetCoords(); MapClass::DamageArea(crd, morePower, pThis, pWH, false, nullptr); } } } } return 0x7387C4; } // merge two small visceroids into one large visceroid DEFINE_HOOK(739F21, UnitClass_UpdatePosition_Visceroid, 6) { GET(UnitClass*, pThis, EBP); // fleshbag erotic if(pThis->Type->SmallVisceroid) { if(UnitTypeClass* pLargeType = RulesClass::Instance->LargeVisceroid) { if(UnitClass* pDest = specific_cast<UnitClass*>(pThis->Destination)) { if(pDest->Type->SmallVisceroid) { // nice to meat you! auto crdMe = pThis->GetCoords(); auto crdHim = pDest->GetCoords(); auto cellMe = CellClass::Coord2Cell(crdMe); auto cellHim = CellClass::Coord2Cell(crdHim); // two become one if(cellMe == cellHim) { pDest->Type = pLargeType; pDest->Health = pLargeType->Strength; CellClass* pCell = MapClass::Instance->GetCellAt(pDest->LastMapCoords); pDest->UpdateThreatInCell(pCell); pThis->UnInit(); return 0x73B0A5; } } } } } return 0; } // complete rewrite DEFINE_HOOK(4D98C0, FootClass_Destroyed, A) { GET(FootClass*, pThis, ECX); //GET_STACK(AbstractClass*, pKiller, 0x4); auto pType = pThis->GetTechnoType(); // exclude unimportant units, and only play for current player if(!pType->DontScore && !pType->Insignificant && !pType->Spawned && pThis->Owner->ControlledByPlayer()) { auto pExt = TechnoTypeExt::ExtMap.Find(pType); int idx = pExt->EVA_UnitLost; if(idx != -1) { CellStruct cell = pThis->GetMapCoords(); RadarEventClass::Create(RadarEventType::UnitLost, cell); VoxClass::PlayIndex(idx, -1, -1); } } return 0x4D9918; } // linking units for type selection DEFINE_HOOK(732C30, TechnoClass_IDMatches, 5) { GET(TechnoClass*, pThis, ECX); GET(DynamicVectorClass<const char*>*, pNames, EDX); TechnoTypeClass* pType = pThis->GetTechnoType(); auto pExt = TechnoTypeExt::ExtMap.Find(pType); const char* id = pExt->GetSelectionGroupID(); bool match = false; // find any match for(auto i=pNames->begin(); i<pNames->end(); ++i) { if(!_strcmpi(*i, id)) { if(pThis->CanBeSelectedNow()) { match = true; break; } // buildings are exempt if they can't undeploy if(pThis->WhatAmI() == BuildingClass::AbsID && pType->UndeploysInto) { match = true; break; } } } R->EAX(match ? 1 : 0); return 0x732C97; } // #1283653: fix for jammed buildings and attackers in open topped transports DEFINE_HOOK(702A38, TechnoClass_ReceiveDamage_OpenTopped, 7) { REF_STACK(TechnoClass*, pAttacker, STACK_OFFS(0xC4, -0x10)); // decide as if the transporter fired at this building if(pAttacker && pAttacker->InOpenToppedTransport && pAttacker->Transporter) { pAttacker = pAttacker->Transporter; } R->EDI(pAttacker); return 0x702A3F; } // #912875: respect the remove flag for invalidating SpawnManager owners DEFINE_HOOK(707B19, TechnoClass_PointerGotInvalid_SpawnCloakOwner, 6) { GET(TechnoClass*, pThis, ESI); GET(void*, ptr, EBP); REF_STACK(bool, remove, STACK_OFFS(0x20, -0x8)); if(auto pSM = pThis->SpawnManager) { // ignore disappearing owner if(remove || pSM->Owner != ptr) { R->ECX(pSM); return 0x707B23; } } return 0x707B29; } // flying aircraft carriers // allow spawned units to spawn above ground DEFINE_HOOK(414338, AircraftClass_Put_SpawnHigh, 6) { GET(AircraftClass*, pThis, ESI); GET(AircraftTypeClass*, pType, ECX); R->EAX(pType->MissileSpawn || pThis->SpawnOwner); return 0x41433E; } // aim for the cell for flying carriers DEFINE_HOOK(6B783B, SpawnManagerClass_Update_SpawnHigh, 5) { GET(SpawnManagerClass*, pThis, ESI); AbstractClass* pDest = pThis->Owner; if(pThis->Owner->GetHeight() > 0) { pDest = pThis->Owner->GetCell(); } R->EAX(pDest); return 0; } // issue #279: per unit AirstrikeAttackVoice and AirstrikeAbortSound DEFINE_HOOK(41D940, AirstrikeClass_Fire_AirstrikeAttackVoice, 5) { GET(AirstrikeClass*, pAirstrike, EDI); // get default from rules int index = RulesClass::Instance->AirstrikeAttackVoice; // get from aircraft auto pAircraftExt = TechnoTypeExt::ExtMap.Find(pAirstrike->FirstObject->GetTechnoType()); index = pAircraftExt->VoiceAirstrikeAttack.Get(index); // get from designator if(auto pOwner = pAirstrike->Owner) { auto pOwnerExt = TechnoTypeExt::ExtMap.Find(pOwner->GetTechnoType()); index = pOwnerExt->VoiceAirstrikeAttack.Get(index); } VocClass::PlayAt(index, pAirstrike->FirstObject->Location, nullptr); return 0x41D970; } DEFINE_HOOK(41D5AE, AirstrikeClass_PointerGotInvalid_AirstrikeAbortSound, 9) { GET(AirstrikeClass*, pAirstrike, ESI); // get default from rules int index = RulesClass::Instance->AirstrikeAbortSound; // get from aircraft auto pAircraftExt = TechnoTypeExt::ExtMap.Find(pAirstrike->FirstObject->GetTechnoType()); index = pAircraftExt->VoiceAirstrikeAbort.Get(index); // get from designator if(auto pOwner = pAirstrike->Owner) { auto pOwnerExt = TechnoTypeExt::ExtMap.Find(pOwner->GetTechnoType()); index = pOwnerExt->VoiceAirstrikeAbort.Get(index); } VocClass::PlayAt(index, pAirstrike->FirstObject->Location, nullptr); return 0x41D5E0; } DEFINE_HOOK(702CFE, TechnoClass_ReceiveDamage_PreventScatter, 6) { GET(FootClass*, pThis, ESI); GET_STACK(WarheadTypeClass*, pWarhead, STACK_OFFS(0xC4, -0xC)); auto pExt = WarheadTypeExt::ExtMap.Find(pWarhead); // only allow to scatter if not prevented if(!pExt->PreventScatter) { pThis->Scatter(CoordStruct::Empty, true, false); } return 0x702D11; } DEFINE_HOOK(6F826E, TechnoClass_CanAutoTargetObject_CivilianEnemy, 5) { GET(TechnoClass*, pThis, EDI); GET(TechnoClass*, pTarget, ESI); GET(TechnoTypeClass*, pTargetType, EBP); enum { Undecided = 0, ConsiderEnemy = 0x6F8483, ConsiderCivilian = 0x6F83B1, Ignore = 0x6F894F }; auto pExt = TechnoTypeExt::ExtMap.Find(pTargetType); // always consider this an enemy if(pExt->CivilianEnemy) { return ConsiderEnemy; } // if the potential target is attacking an allied object, consider it an enemy // to not allow civilians to overrun a player if(auto pTargetTarget = abstract_cast<TechnoClass*>(pTarget->Target)) { auto pOwner = pThis->Owner; if(pOwner->IsAlliedWith(pTargetTarget)) { auto pData = RulesExt::Global(); bool repel = pOwner->ControlledByHuman() ? pData->AutoRepelPlayer : pData->AutoRepelAI; if(repel) { return ConsiderEnemy; } } } return Undecided; } // particle system related // make damage sparks customizable, using game setting as default. DEFINE_HOOK(6FACD9, TechnoClass_Update_DamageSparks, 6) { GET(TechnoTypeClass*, pType, EBX); auto pExt = TechnoTypeExt::ExtMap.Find(pType); bool sparks = pExt->DamageSparks.Get(pType->DamageSparks); R->EAX(sparks); return 0x6FACDF; } // smoke particle systems created when a techno is damaged DEFINE_HOOK(702894, TechnoClass_ReceiveDamage_SmokeParticles, 6) { GET(TechnoClass*, pThis, ESI); REF_STACK(DynamicVectorClass<ParticleSystemTypeClass const *>, Systems, 0x30); auto pType = pThis->GetTechnoType(); auto pExt = TechnoTypeExt::ExtMap.Find(pType); auto it = pExt->ParticleSystems_DamageSmoke.GetElements(pType->DamageParticleSystems); auto allowAny = pExt->ParticleSystems_DamageSmoke.HasValue(); for(auto pSystem : it) { if(allowAny || pSystem->BehavesLike == BehavesLike::Smoke) { Systems.AddItem(pSystem); } } return 0x702938; } // spark particle systems created at random intervals DEFINE_HOOK(6FAD49, TechnoClass_Update_SparkParticles, 0) // breaks the loop { GET(TechnoClass*, pThis, ESI); REF_STACK(DynamicVectorClass<ParticleSystemTypeClass const *>, Systems, 0x60); auto pType = pThis->GetTechnoType(); auto pExt = TechnoTypeExt::ExtMap.Find(pType); auto it = pExt->ParticleSystems_DamageSparks.GetElements(pType->DamageParticleSystems); auto allowAny = pExt->ParticleSystems_DamageSparks.HasValue(); for(auto pSystem : it) { if(allowAny || pSystem->BehavesLike == BehavesLike::Spark) { Systems.AddItem(pSystem); } } return 0x6FADB3; } // customizable berserk fire rate modification DEFINE_HOOK(6FF28F, TechnoClass_Fire_BerserkROFMultiplier, 6) { GET(TechnoClass*, pThis, ESI); GET(int, ROF, EAX); if(pThis->Berzerk) { auto pExt = TechnoTypeExt::ExtMap.Find(pThis->GetTechnoType()); double multiplier = pExt->BerserkROFMultiplier.Get(RulesExt::Global()->BerserkROFMultiplier); ROF = static_cast<int>(ROF * multiplier); } R->EAX(ROF); return 0x6FF29E; } DEFINE_HOOK(6FE31C, TechnoClass_Fire_AllowDamage, 8) { //GET(TechnoClass*, pThis, ESI); GET(WeaponTypeClass*, pWeapon, EBX); auto pExt = WeaponTypeExt::ExtMap.Find(pWeapon); // whether conventional damage should be used bool applyDamage = pExt->ApplyDamage.Get(!pWeapon->IsSonic && !pWeapon->UseFireParticles); if(!applyDamage) { // clear damage R->EDI(0); } return applyDamage ? 0x6FE32Fu : 0x6FE3DFu; } // issue #1324: enemy repair wrench visible when it shouldn't DEFINE_HOOK(6F525B, TechnoClass_DrawExtras_PowerOff, 5) { GET(TechnoClass*, pTechno, EBP); GET_STACK(RectangleStruct*, pRect, 0xA0); if(auto pBld = abstract_cast<BuildingClass*>(pTechno)) { auto const pExt = BuildingExt::ExtMap.Find(pBld); // allies and observers can always see by default bool canSeeRepair = HouseClass::Player->IsAlliedWith(pBld->Owner) || HouseClass::IsPlayerObserver(); bool showRepair = FileSystem::WRENCH_SHP && pBld->IsBeingRepaired // fixes the wrench playing over a temporally challenged building && !pBld->IsBeingWarpedOut() && !pBld->WarpingOut // never show to enemies when cloaked, and only if allowed && (canSeeRepair || (pBld->CloakState == CloakState::Uncloaked && RulesExt::Global()->EnemyWrench)); // display power off marker only for current player's buildings bool showPower = FileSystem::POWEROFF_SHP && !pExt->TogglePower_HasPower // only for owned buildings, but observers got magic eyes && (pBld->Owner->ControlledByPlayer() || HouseClass::IsPlayerObserver()); // display any? if(showPower || showRepair) { auto cell = pBld->GetMapCoords(); if(!MapClass::Instance->GetCellAt(cell)->IsShrouded()) { CoordStruct crd; pBld->GetPosition_2(&crd); Point2D point; TacticalClass::Instance->CoordsToClient(&crd, &point); // offset the markers Point2D ptRepair = point; if(showPower) { ptRepair.X -= 7; ptRepair.Y -= 7; } Point2D ptPower = point; if(showRepair) { ptPower.X += 18; ptPower.Y += 18; } // animation display speed // original frame calculation: ((currentframe%speed)*6)/(speed-1) int speed = GameOptionsClass::Instance->GetAnimSpeed(14) / 4; if(speed < 2) { speed = 2; } // draw the markers if(showRepair) { int frame = (FileSystem::WRENCH_SHP->Frames * (Unsorted::CurrentFrame % speed)) / speed; DSurface::Hidden_2->DrawSHP(FileSystem::MOUSE_PAL, FileSystem::WRENCH_SHP, frame, &ptRepair, pRect, BlitterFlags(0xE00), 0, 0, 0, 1000, 0, 0, 0, 0, 0); } if(showPower) { int frame = (FileSystem::POWEROFF_SHP->Frames * (Unsorted::CurrentFrame % speed)) / speed; DSurface::Hidden_2->DrawSHP(FileSystem::MOUSE_PAL, FileSystem::POWEROFF_SHP, frame, &ptPower, pRect, BlitterFlags(0xE00), 0, 0, 0, 1000, 0, 0, 0, 0, 0); } } } } return 0x6F5347; } DEFINE_HOOK(741613, UnitClass_ApproachTarget_OmniCrusher, 6) { GET(UnitClass* const, pThis, ESI); auto const pExt = TechnoTypeExt::ExtMap.Find(pThis->Type); auto const aggressive = pExt->OmniCrusher_Aggressive; return aggressive ? 0u : 0x741685u; } DEFINE_HOOK(7418AA, UnitClass_CrushCell_CrushDamage, 6) { GET(UnitClass* const, pThis, EDI); GET(ObjectClass* const, pVictim, ESI); if(auto const pTechno = abstract_cast<TechnoClass*>(pVictim)) { auto pExt = TechnoTypeExt::ExtMap.Find(pVictim->GetTechnoType()); auto const pWarhead = pExt->CrushDamageWarhead.Get( RulesClass::Instance->C4Warhead); auto damage = pExt->CrushDamage.Get(pTechno); if(pWarhead && damage) { pThis->ReceiveDamage( &damage, 0, pWarhead, nullptr, false, false, nullptr); } } return 0; } DEFINE_HOOK(4D9920, FootClass_SelectAutoTarget_Cloaked, 9) { GET(FootClass* const, pThis, ECX); if(pThis->Owner->ControlledByHuman() && pThis->GetCurrentMission() == Mission::Guard) { auto const pType = pThis->GetTechnoType(); auto const pExt = TechnoTypeExt::ExtMap.Find(pType); auto allowAquire = true; if(!pExt->CanPassiveAcquire_Guard) { // we are in guard mode allowAquire = false; } else if(!pExt->CanPassiveAcquire_Cloak) { // passive acquire is disallowed when guarding and cloakable if(pThis->IsCloakable() || pThis->HasAbility(Ability::Cloak)) { allowAquire = false; } } if(!allowAquire) { R->EAX(static_cast<TechnoClass*>(nullptr)); return 0x4D995C; } } return 0; } DEFINE_HOOK(70BE80, TechnoClass_ShouldSelfHealOneStep, 5) { GET(TechnoClass* const, pThis, ECX); auto const pExt = TechnoExt::ExtMap.Find(pThis); R->EAX(pExt->GetSelfHealAmount() > 0); return 0x70BF46; } DEFINE_HOOK(6FA743, TechnoClass_Update_SelfHeal, A) { GET(TechnoClass* const, pThis, ESI); // prevent crashing and sinking technos from self-healing if(pThis->IsCrashing || pThis->IsSinking) { return 0x6FA941; } auto const pExt = TechnoExt::ExtMap.Find(pThis); // this replaces the call to pThis->ShouldSelfHealOneStep() if(auto const amount = pExt->GetSelfHealAmount()) { pThis->Health += amount; R->ECX(pThis); return 0x6FA75A; } return 0x6FA793; } DEFINE_HOOK(7162B0, TechnoTypeClass_GetPipMax_MindControl, 6) { GET(TechnoTypeClass const* const, pThis, ECX); auto const GetMindDamage = [](WeaponTypeClass const* const pWeapon) { return (pWeapon && pWeapon->Warhead->MindControl) ? pWeapon->Damage : 0; }; auto count = GetMindDamage(pThis->Weapon[0].WeaponType); if(count <= 0) { count = GetMindDamage(pThis->Weapon[1].WeaponType); } R->EAX(count); return 0x7162BC; } DEFINE_HOOK(73769E, UnitClass_ReceivedRadioCommand_SpecificPassengers, 8) { GET(UnitClass* const, pThis, ESI); GET(TechnoClass const* const, pSender, EDI); auto const pType = pThis->GetTechnoType(); auto const pExt = TechnoTypeExt::ExtMap.Find(pType); auto const pSenderType = pSender->GetTechnoType(); auto const allowed = (pExt->PassengersWhitelist.empty() || pExt->PassengersWhitelist.Contains(pSenderType)) && !pExt->PassengersBlacklist.Contains(pSenderType); return allowed ? 0u : 0x73780Fu; } DEFINE_HOOK(41949F, AircraftClass_ReceivedRadioCommand_SpecificPassengers, 6) { GET(AircraftClass* const, pThis, ESI); GET_STACK(TechnoClass const* const, pSender, 0x14); enum { Allowed = 0x41945Fu, Disallowed = 0x41951Fu }; auto const pType = pThis->GetTechnoType(); if(pThis->Passengers.NumPassengers >= pType->Passengers) { return Disallowed; } auto const pSenderType = pSender->GetTechnoType(); auto const pExt = TechnoTypeExt::ExtMap.Find(pType); auto const allowed = (pExt->PassengersWhitelist.empty() || pExt->PassengersWhitelist.Contains(pSenderType)) && !pExt->PassengersBlacklist.Contains(pSenderType); return allowed ? Allowed : Disallowed; } DEFINE_HOOK(740031, UnitClass_GetCursorOverObject_NoManualUnload, 6) { GET(UnitClass const* const, pThis, ESI); auto const pType = pThis->GetTechnoType(); auto const pExt = TechnoTypeExt::ExtMap.Find(pType); return pExt->NoManualUnload ? 0x740115u : 0u; } DEFINE_HOOK(700EEC, TechnoClass_CanDeploySlashUnload_NoManualUnload, 6) { // this techno is known to be a unit GET(UnitClass const* const, pThis, ESI); auto const pType = pThis->GetTechnoType(); auto const pExt = TechnoTypeExt::ExtMap.Find(pType); return pExt->NoManualUnload ? 0x700DCEu : 0u; } DEFINE_HOOK(700536, TechnoClass_GetCursorOverObject_NoManualFire, 6) { GET(TechnoClass const* const, pThis, ESI); auto const pType = pThis->GetTechnoType(); auto const pExt = TechnoTypeExt::ExtMap.Find(pType); return pExt->NoManualFire ? 0x70056Cu : 0u; } DEFINE_HOOK(7008D4, TechnoClass_GetCursorOverCell_NoManualFire, 6) { GET(TechnoClass const* const, pThis, ESI); auto const pType = pThis->GetTechnoType(); auto const pExt = TechnoTypeExt::ExtMap.Find(pType); return pExt->NoManualFire ? 0x700AB7u : 0u; } DEFINE_HOOK(51ED8E, InfantryClass_GetCursorOverObject_NoManualEnter, 6) { //GET(InfantryClass const* const, pThis, ESI); GET(TechnoTypeClass const* const, pTargetType, EAX); auto const pExt = TechnoTypeExt::ExtMap.Find(pTargetType); bool enterable = pTargetType->Passengers > 0 && !pExt->NoManualEnter; return enterable ? 0x51ED9Cu : 0x51EE3Bu; } DEFINE_HOOK(74031A, UnitClass_GetCursorOverObject_NoManualEnter, 6) { //GET(UnitClass const* const, pThis, ESI); GET(TechnoTypeClass const* const, pTargetType, EAX); auto const pExt = TechnoTypeExt::ExtMap.Find(pTargetType); bool enterable = pTargetType->Passengers > 0 && !pExt->NoManualEnter; return enterable ? 0x740324u : 0x74037Au; }
28.361004
155
0.712613
[ "object", "vector" ]
ce09192c76ac1582fff0e6fecce9b3967d4075fc
45,513
cpp
C++
wallet/core/base_tx_builder.cpp
Webonnix/beam
0ad43c861470a7cd97758b0d59daf6b683e09977
[ "Apache-2.0" ]
631
2018-11-10T05:56:05.000Z
2022-03-30T13:21:00.000Z
wallet/core/base_tx_builder.cpp
Webonnix/beam
0ad43c861470a7cd97758b0d59daf6b683e09977
[ "Apache-2.0" ]
1,824
2018-11-08T11:32:58.000Z
2022-03-28T12:33:03.000Z
wallet/core/base_tx_builder.cpp
Webonnix/beam
0ad43c861470a7cd97758b0d59daf6b683e09977
[ "Apache-2.0" ]
216
2018-11-12T08:07:21.000Z
2022-03-08T20:50:19.000Z
// Copyright 2018 The Beam Team // // 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 "base_tx_builder.h" #include "core/block_crypt.h" #include "core/shielded.h" #include "base_transaction.h" #include "strings_resources.h" #include "utility/executor.h" // TODO: getrandom not available until API 28 in the Android NDK 17b // https://github.com/boostorg/uuid/issues/76 #if defined(__ANDROID__) #define BOOST_UUID_RANDOM_PROVIDER_DISABLE_GETRANDOM 1 #endif #include <boost/uuid/uuid_generators.hpp> #include <numeric> #include "utility/logger.h" namespace beam::wallet { using namespace ECC; using namespace std; /////////////////////////////////////// // BaseTxBuilder::KeyKeeperHandler BaseTxBuilder::KeyKeeperHandler::KeyKeeperHandler(BaseTxBuilder& b, Stage& s) { m_pBuilder = b.weak_from_this(); m_pStage = &s; assert(Stage::None == s); s = Stage::InProgress; } BaseTxBuilder::KeyKeeperHandler::~KeyKeeperHandler() { if (m_pStage) { std::shared_ptr<BaseTxBuilder> pBld = m_pBuilder.lock(); if (pBld) Detach(*pBld, Stage::None); } } void BaseTxBuilder::KeyKeeperHandler::Detach(BaseTxBuilder&, Stage s) { if (m_pStage) { assert(Stage::InProgress == *m_pStage); *m_pStage = s; m_pStage = nullptr; } } void BaseTxBuilder::KeyKeeperHandler::OnDone(IPrivateKeyKeeper2::Status::Type n) { if (m_pStage) { std::shared_ptr<BaseTxBuilder> pBld = m_pBuilder.lock(); if (pBld) { BaseTxBuilder& b = *pBld; if (IPrivateKeyKeeper2::Status::Success == n) { ITransaction::Ptr pGuard(b.m_Tx.shared_from_this()); // extra ref on transaction object. // Otherwise it can crash in Update() -> CompleteTx(), which will remove its ptr from live tx map try { OnSuccess(b); } catch (const TransactionFailedException& ex) { Detach(b, Stage::None); pBld->m_Tx.OnFailed(ex.GetReason(), ex.ShouldNofify()); } } else OnFailed(b, n); } else m_pStage = nullptr; } } void BaseTxBuilder::KeyKeeperHandler::OnFailed(BaseTxBuilder& b, IPrivateKeyKeeper2::Status::Type n) { Detach(b, Stage::None); b.m_Tx.OnFailed(BaseTransaction::KeyKeeperErrorToFailureReason(n), true); } void BaseTxBuilder::KeyKeeperHandler::OnAllDone(BaseTxBuilder& b) { Detach(b, Stage::Done); b.m_Tx.Update(); // may complete transaction } /////////////////////////////////////// // BaseTxBuilder::Coins void BaseTxBuilder::Coins::AddOffset(ECC::Scalar::Native& kOffs, const Key::IKdf::Ptr& pMasterKdf) const { ECC::Scalar::Native sk; for (const CoinID& cid : m_Input) { CoinID::Worker(cid).Create(sk, *cid.get_ChildKdf(pMasterKdf)); kOffs += sk; } for (const auto& si : m_InputShielded) { si.get_SkOut(sk, si.m_Fee, *pMasterKdf); kOffs += sk; } kOffs = -kOffs; for (const CoinID& cid : m_Output) { CoinID::Worker(cid).Create(sk, *cid.get_ChildKdf(pMasterKdf)); kOffs += sk; } kOffs = -kOffs; } /////////////////////////////////////// // BaseTxBuilder::Balance BaseTxBuilder::Balance::Balance(BaseTxBuilder& b) :m_Builder(b) { } void BaseTxBuilder::Balance::Add(const Coin::ID& cid, bool bOutp) { (bOutp ? m_Builder.m_Coins.m_Output : m_Builder.m_Coins.m_Input).push_back(cid); Entry& x = m_Map[cid.m_AssetID]; if (bOutp) x.m_Value -= cid.m_Value; else x.m_Value += cid.m_Value; } void BaseTxBuilder::Balance::Add(const IPrivateKeyKeeper2::ShieldedInput& si) { m_Builder.m_Coins.m_InputShielded.push_back(si); m_Map[si.m_AssetID].m_Value += si.m_Value; m_Map[0].m_Value -= si.m_Fee; } void BaseTxBuilder::Balance::Add(const ShieldedTxo::ID& sid) { auto& fs = Transaction::FeeSettings::get(m_Builder.m_Height.m_Min); IPrivateKeyKeeper2::ShieldedInput si; Cast::Down<ShieldedTxo::ID>(si) = sid; si.m_Fee = fs.m_ShieldedInputTotal; // auto-fee for shielded inputs Add(si); } void BaseTxBuilder::Balance::CreateOutput(Amount val, Asset::ID aid, Key::Type type) { Coin newUtxo = m_Builder.m_Tx.GetWalletDB()->generateNewCoin(val, aid); newUtxo.m_ID.m_Type = type; newUtxo.m_createTxId = m_Builder.m_Tx.GetTxID(); m_Builder.m_Tx.GetWalletDB()->storeCoin(newUtxo); Add(newUtxo.m_ID, true); } void BaseTxBuilder::Balance::AddPreselected() { CoinIDList cidl; m_Builder.GetParameter(TxParameterID::PreselectedCoins, cidl); for (const auto& cid : cidl) Add(cid, false); } void BaseTxBuilder::Balance::CompleteBalance() { std::set<Asset::ID> setRcv; // those auto-created coins should be 'Regular' instead of 'Change' for (const auto& v : m_Map) { if (v.second.m_Value > 0) setRcv.insert(v.first); } AddPreselected(); uint32_t nNeedInputs = 0; for (const auto& v : m_Map) { if (v.second.m_Value < 0) nNeedInputs++; } if (nNeedInputs) { if (m_Map[0].m_Value >= 0) nNeedInputs++; // although there's no dificiency in def asset, assume it may arise due to involuntary fees // go by asset type in reverse order, to reach the def asset last for (auto it = m_Map.rbegin(); m_Map.rend() != it; it++) { AmountSigned& val = it->second.m_Value; if (val >= 0) continue; uint32_t nShieldedMax = Rules::get().Shielded.MaxIns; uint32_t nShieldedInUse = static_cast<uint32_t>(m_Builder.m_Coins.m_InputShielded.size()); // preselected? if (nShieldedMax <= nShieldedInUse) nShieldedMax = 0; else nShieldedMax -= nShieldedInUse; assert(nNeedInputs); nShieldedMax = (nShieldedMax + nNeedInputs - 1) / nNeedInputs; // leave some reserve to other assets Asset::ID aid = it->first; std::vector<Coin> vSelStd; std::vector<ShieldedCoin> vSelShielded; m_Builder.m_Tx.GetWalletDB()->selectCoins2(m_Builder.m_Height.m_Min, -val, aid, vSelStd, vSelShielded, nShieldedMax, true); for (const auto& c : vSelStd) Add(c.m_ID, false); for (const auto& c : vSelShielded) Add(c.m_CoinID); if (val < 0) { LOG_ERROR() << m_Builder.m_Tx.GetTxID() << "[" << m_Builder.m_SubTxID << "]" << " Missing " << PrintableAmount(Amount(-val), false, aid); throw TransactionFailedException(!m_Builder.m_Tx.IsInitiator(), TxFailureReason::NoInputs); } nNeedInputs--; } } for (const auto& v : m_Map) { AmountSigned val = v.second.m_Value; assert(val >= 0); if (val > 0) { Asset::ID aid = v.first; bool bRcv = setRcv.end() != setRcv.find(aid); CreateOutput(val, aid, bRcv ? Key::Type::Regular : Key::Type::Change); } assert(!v.second.m_Value); } } /////////////////////////////////////// // BaseTxBuilder BaseTxBuilder::BaseTxBuilder(BaseTransaction& tx, SubTxID subTxID) :m_Tx(tx) ,m_SubTxID(subTxID) { GetParameter(TxParameterID::MinHeight, m_Height.m_Min); if (!m_Height.m_Min) { // automatically set current height Block::SystemState::Full s; if (m_Tx.GetTip(s)) SaveAndStore(m_Height.m_Min, TxParameterID::MinHeight, s.m_Height); } GetParameter(TxParameterID::InputCoins, m_Coins.m_Input); GetParameter(TxParameterID::InputCoinsShielded, m_Coins.m_InputShielded); GetParameter(TxParameterID::OutputCoins, m_Coins.m_Output); m_pTransaction = std::make_shared<Transaction>(); auto& trans = *m_pTransaction; // alias GetParameter(TxParameterID::Inputs, trans.m_vInputs); GetParameter(TxParameterID::ExtraKernels, trans.m_vKernels); GetParameter(TxParameterID::Outputs, trans.m_vOutputs); if (!GetParameter(TxParameterID::Offset, trans.m_Offset)) trans.m_Offset = Zero; GetParameter(TxParameterID::MaxHeight, m_Height.m_Max); GetParameter(TxParameterID::Fee, m_Fee); bool bNoInOuts = trans.m_vInputs.empty() && trans.m_vOutputs.empty() && !wallet::GetShieldedInputsNum(trans.m_vKernels); m_GeneratingInOuts = bNoInOuts ? Stage::None : Stage::Done; GetParameter(TxParameterID::MutualTxState, m_Status); TxKernel::Ptr pKrn; GetParameter(TxParameterID::Kernel, pKrn); if (pKrn) { AddKernel(std::move(pKrn)); if (Status::FullTx == m_Status) trans.NormalizeE(); // everything else must have already been normalized } } void BaseTxBuilder::SaveCoins() { bool bAssets = false; for (const auto& cid : m_Coins.m_Input) if (cid.m_AssetID) bAssets = true; for (const auto& si : m_Coins.m_InputShielded) if (si.m_AssetID) bAssets = true; for (const auto& cid : m_Coins.m_Output) if (cid.m_AssetID) bAssets = true; if (bAssets) VerifyAssetsEnabled(); SetParameter(TxParameterID::InputCoins, m_Coins.m_Input); SetParameter(TxParameterID::InputCoinsShielded, m_Coins.m_InputShielded); SetParameter(TxParameterID::OutputCoins, m_Coins.m_Output); // tag inputs for (const auto& cid : m_Coins.m_Input) { Coin coin; coin.m_ID = cid; if (m_Tx.GetWalletDB()->findCoin(coin) && coin.m_status == Coin::Status::Available) { coin.m_spentTxId = m_Tx.GetTxID(); m_Tx.GetWalletDB()->saveCoin(coin); } else { auto message("Coin with ID: " + toString(coin.m_ID) + " is unreachable."); LOG_ERROR() << message; throw TransactionFailedException(true, TxFailureReason::NoInputs, message.c_str()); } } for (auto& cid : m_Coins.m_InputShielded) { auto pCoin = m_Tx.GetWalletDB()->getShieldedCoin(cid.m_Key); if (pCoin) { pCoin->m_spentTxId = m_Tx.GetTxID(); m_Tx.GetWalletDB()->saveShieldedCoin(*pCoin); } } } bool BaseTxBuilder::IsGeneratingInOuts() const { return (Stage::InProgress == m_GeneratingInOuts); } bool BaseTxBuilder::IsSigning() const { return (Stage::InProgress == m_Signing); } template <typename TDst, typename TSrc> void MoveIntoVec1(std::vector<TDst>& vDst, std::vector<TSrc>& vSrc) { std::move(vSrc.begin(), vSrc.end(), back_inserter(vDst)); } template <typename T> void MoveIntoVec(std::vector<T>& vDst, std::vector<T>& vSrc) { if (vDst.empty()) vDst = std::move(vSrc); else MoveIntoVec1(vDst, vSrc); } struct BaseTxBuilder::HandlerInOuts :public KeyKeeperHandler ,public std::enable_shared_from_this<HandlerInOuts> { using KeyKeeperHandler::KeyKeeperHandler; virtual ~HandlerInOuts() {} // auto struct Outputs { std::vector<IPrivateKeyKeeper2::Method::CreateOutput> m_vMethods; std::vector<Output::Ptr> m_Done; bool IsAllDone() const { return m_vMethods.size() == m_Done.size(); } bool OnNext() { size_t iDone = m_Done.size(); assert(m_vMethods[iDone].m_pResult); m_Done.push_back(std::move(m_vMethods[iDone].m_pResult)); return true; } } m_Outputs; struct Inputs { struct CoinPars :public IPrivateKeyKeeper2::Method::get_Kdf { CoinID m_Cid; }; std::vector<CoinPars> m_vMethods; std::vector<Input::Ptr> m_Done; bool IsAllDone() const { return m_vMethods.size() == m_Done.size(); } bool OnNext() { size_t iDone = m_Done.size(); CoinPars& c = m_vMethods[iDone]; if (!c.m_pPKdf) return false; Point::Native comm; CoinID::Worker(c.m_Cid).Recover(comm, *c.m_pPKdf); m_Done.emplace_back(); m_Done.back().reset(new Input); m_Done.back()->m_Commitment = comm; return true; } } m_Inputs; struct InputsShielded { struct MyList :public Sigma::CmList { std::vector<ECC::Point::Storage> m_vec; ECC::Point::Storage* m_p0; uint32_t m_Skip; virtual bool get_At(ECC::Point::Storage& res, uint32_t iIdx) override { if (iIdx < m_Skip) { res.m_X = Zero; res.m_Y = Zero; } else res = m_p0[iIdx - m_Skip]; return true; } }; IPrivateKeyKeeper2::Method::CreateInputShielded m_Method; MyList m_Lst; std::vector<TxKernelShieldedInput::Ptr> m_Done; TxoID m_Wnd0; uint32_t m_N; uint32_t m_Count; bool IsAllDone(BaseTxBuilder& b) const { return b.m_Coins.m_InputShielded.size() == m_Done.size(); } bool OnNext(BaseTxBuilder& b) { m_Done.push_back(std::move(m_Method.m_pKernel)); return MoveNextSafe(b); } bool MoveNextSafe(BaseTxBuilder&); bool OnList(BaseTxBuilder&, proto::ShieldedList& msg); IMPLEMENT_GET_PARENT_OBJ(HandlerInOuts, m_InputsShielded) } m_InputsShielded; void CheckAllDone(BaseTxBuilder& b) { if (m_Outputs.IsAllDone() && m_Inputs.IsAllDone() && m_InputsShielded.IsAllDone(b)) { MoveIntoVec(b.m_pTransaction->m_vOutputs, m_Outputs.m_Done); MoveIntoVec(b.m_pTransaction->m_vInputs, m_Inputs.m_Done); MoveIntoVec1(b.m_pTransaction->m_vKernels, m_InputsShielded.m_Done); b.SaveInOuts(); OnAllDone(b); } } bool OnNext(BaseTxBuilder& b) { if (!m_Outputs.IsAllDone()) return m_Outputs.OnNext(); if (!m_Inputs.IsAllDone()) return m_Inputs.OnNext(); assert(!m_InputsShielded.IsAllDone(b)); return m_InputsShielded.OnNext(b); } virtual void OnSuccess(BaseTxBuilder& b) override { if (OnNext(b)) CheckAllDone(b); else OnFailed(b, IPrivateKeyKeeper2::Status::Unspecified); // although shouldn't happen } }; struct MyWrapper { const TxKernel::Ptr* m_p0; size_t m_Count; TxKernel* m_pSkip; template <typename Archive> void serialize(Archive& ar) { size_t n = m_Count - (!!m_pSkip); ar & n; for (size_t i = 0; i < m_Count; i++) { const auto& pKrn = m_p0[i]; if (pKrn.get() != m_pSkip) ar & pKrn; } } }; void BaseTxBuilder::SaveInOuts() { SetParameter(TxParameterID::Inputs, m_pTransaction->m_vInputs); SetParameter(TxParameterID::Outputs, m_pTransaction->m_vOutputs); // serialize kernels, except the 'main' one const auto& v = m_pTransaction->m_vKernels; MyWrapper wr; wr.m_pSkip = m_pKrn; wr.m_Count = v.size(); if (wr.m_Count) wr.m_p0 = &v.front(); SetParameter(TxParameterID::ExtraKernels, wr); } void BaseTxBuilder::GenerateInOuts() { if (Stage::None != m_GeneratingInOuts) return; if (m_Coins.IsEmpty()) { m_GeneratingInOuts = Stage::Done; return; } KeyKeeperHandler::Ptr pHandler = std::make_shared<HandlerInOuts>(*this, m_GeneratingInOuts); HandlerInOuts& x = Cast::Up<HandlerInOuts>(*pHandler); // outputs x.m_Outputs.m_vMethods.resize(m_Coins.m_Output.size()); x.m_Outputs.m_Done.reserve(m_Coins.m_Output.size()); for (size_t i = 0; i < m_Coins.m_Output.size(); i++) { x.m_Outputs.m_vMethods[i].m_hScheme = m_Height.m_Min; x.m_Outputs.m_vMethods[i].m_Cid = m_Coins.m_Output[i]; FillUserData(Output::User::ToPacked(x.m_Outputs.m_vMethods[i].m_User)); m_Tx.get_KeyKeeperStrict()->InvokeAsync(x.m_Outputs.m_vMethods[i], pHandler); } // inputs x.m_Inputs.m_vMethods.resize(m_Coins.m_Input.size()); x.m_Inputs.m_Done.reserve(m_Coins.m_Input.size()); for (size_t i = 0; i < m_Coins.m_Input.size(); i++) { HandlerInOuts::Inputs::CoinPars& c = x.m_Inputs.m_vMethods[i]; c.m_Cid = m_Coins.m_Input[i]; c.m_Root = !c.m_Cid.get_ChildKdfIndex(c.m_iChild); m_Tx.get_KeyKeeperStrict()->InvokeAsync(x.m_Inputs.m_vMethods[i], pHandler); } // inputs shielded x.m_InputsShielded.m_Done.reserve(m_Coins.m_InputShielded.size()); if (!x.m_InputsShielded.MoveNextSafe(*this)) throw TransactionFailedException(true, TxFailureReason::Unknown); } bool BaseTxBuilder::HandlerInOuts::InputsShielded::MoveNextSafe(BaseTxBuilder& b) { if (IsAllDone(b)) return true; // currently process inputs 1-by-1 // don't cache retrieved elements (i.e. ignore overlaps for multiple inputs) const IPrivateKeyKeeper2::ShieldedInput& si = b.m_Coins.m_InputShielded[m_Done.size()]; auto pCoin = b.m_Tx.GetWalletDB()->getShieldedCoin(si.m_Key); if (!pCoin) return false; const ShieldedCoin& c = *pCoin; Cast::Down<ShieldedTxo::ID>(m_Method) = c.m_CoinID; m_Method.m_pKernel = std::make_unique<TxKernelShieldedInput>(); m_Method.m_pKernel->m_Fee = si.m_Fee; TxoID nShieldedCurrently = b.m_Tx.GetWalletDB()->get_ShieldedOuts(); std::setmax(nShieldedCurrently, c.m_TxoID + 1); // assume stored shielded count may be inaccurate, the being-spent element must be present ShieldedCoin::UnlinkStatus us(c, nShieldedCurrently); bool bWndLost = us.IsLargeSpendWindowLost(); m_Method.m_pKernel->m_SpendProof.m_Cfg = bWndLost ? Rules::get().Shielded.m_ProofMin : Rules::get().Shielded.m_ProofMax; m_N = m_Method.m_pKernel->m_SpendProof.m_Cfg.get_N(); if (!m_N) return false; m_Method.m_iIdx = c.get_WndIndex(m_N); if (!bWndLost && (us.m_WndReserve0 < 0)) { // move the selected window forward m_Method.m_iIdx += us.m_WndReserve0; // actually decrease assert(m_Method.m_iIdx < m_N); } m_Wnd0 = c.m_TxoID - m_Method.m_iIdx; m_Count = m_N; TxoID nWndEnd = m_Wnd0 + m_N; if (nWndEnd > nShieldedCurrently) { // move the selected window backward uint32_t nExtra = static_cast<uint32_t>(nWndEnd - nShieldedCurrently); if (nExtra < m_Wnd0) m_Wnd0 -= nExtra; else { nExtra = static_cast<uint32_t>(m_Wnd0); m_Wnd0 = 0; } m_Method.m_iIdx += nExtra; m_Count += nExtra; } LOG_INFO() << "ShieldedInput window N=" << m_N << ", Wnd0=" << m_Wnd0 << ", iIdx=" << m_Method.m_iIdx << ", TxoID=" << c.m_TxoID << ", PoolSize=" << nShieldedCurrently; b.m_Tx.GetGateway().get_shielded_list(b.m_Tx.GetTxID(), m_Wnd0, m_Count, [pHandler = get_ParentObj().shared_from_this(), weakTx = b.m_Tx.weak_from_this()](TxoID, uint32_t, proto::ShieldedList& msg) { auto pBldr = pHandler->m_pBuilder.lock(); if (!pBldr) return; BaseTxBuilder& b = *pBldr; auto pTx = weakTx.lock(); if (!pTx) return; try { if (!pHandler->m_InputsShielded.OnList(b, msg)) b.m_Tx.OnFailed(TxFailureReason::Unknown); } catch (const TransactionFailedException& ex) { b.m_Tx.OnFailed(ex.GetReason(), ex.ShouldNofify()); } }); return true; } bool BaseTxBuilder::HandlerInOuts::InputsShielded::OnList(BaseTxBuilder& b, proto::ShieldedList& msg) { if (msg.m_Items.size() > m_Count) { LOG_ERROR() << "ShieldedList message returned more coins than requested " << TRACE(msg.m_Items.size()) << TRACE(m_Count); return false; } uint32_t nItems = static_cast<uint32_t>(msg.m_Items.size()); m_Lst.m_p0 = &msg.m_Items.front(); m_Lst.m_Skip = 0; m_Lst.m_vec.swap(msg.m_Items); m_Method.m_pList = &m_Lst; m_Method.m_pKernel->m_NotSerialized.m_hvShieldedState = msg.m_State1; m_Method.m_pKernel->m_Height = b.m_Height; m_Method.m_pKernel->m_WindowEnd = m_Wnd0 + nItems; if (nItems > m_N) { uint32_t nDelta = nItems - m_N; m_Lst.m_p0 += nDelta; assert(m_Method.m_iIdx >= nDelta); m_Method.m_iIdx -= nDelta; } if (nItems < m_N) { if (m_Wnd0 || (nItems <= m_Method.m_iIdx)) { LOG_ERROR() << "ShieldedList message returned unexpected data " << TRACE(m_Wnd0) << TRACE(nItems) << TRACE(m_Method.m_iIdx); return false; } uint32_t nDelta = m_N - nItems; m_Lst.m_Skip = nDelta; m_Method.m_iIdx += nDelta; assert(m_Method.m_iIdx < m_N); } b.m_Tx.get_KeyKeeperStrict()->InvokeAsync(m_Method, get_ParentObj().shared_from_this()); return true; } void BaseTxBuilder::AddOffset(const ECC::Scalar& k1) { AddOffset(ECC::Scalar::Native(k1)); } void BaseTxBuilder::AddOffset(const ECC::Scalar::Native& k1) { ECC::Scalar::Native k(m_pTransaction->m_Offset); k += k1; m_pTransaction->m_Offset = k; SetParameter(TxParameterID::Offset, m_pTransaction->m_Offset); } bool BaseTxBuilder::Aggregate(ECC::Point& ptDst, const ECC::Point::Native& ptSrcN) { ECC::Point::Native pt; if (!pt.Import(ptDst)) return false; pt += ptSrcN; pt.Export(ptDst); return true; } bool BaseTxBuilder::Aggregate(ECC::Point& ptDst, ECC::Point::Native& ptSrcN, const ECC::Point& ptSrc) { return ptSrcN.Import(ptSrc) && Aggregate(ptDst, ptSrcN); } void BaseTxBuilder::SaveKernel() { // this is ugly hack, but should work without extra code generated SetParameter(TxParameterID::Kernel, Cast::Reinterpret<TxKernel::Ptr>(m_pKrn)); } void BaseTxBuilder::SaveKernelID() { assert(m_pKrn); SetParameter(TxParameterID::KernelID, m_pKrn->m_Internal.m_ID); } void BaseTxBuilder::SetInOuts(IPrivateKeyKeeper2::Method::TxCommon& m) { m.m_vInputs = m_Coins.m_Input; m.m_vOutputs = m_Coins.m_Output; m.m_vInputsShielded = m_Coins.m_InputShielded; m.m_NonConventional = !IsConventional(); } void BaseTxBuilder::SetCommon(IPrivateKeyKeeper2::Method::TxCommon& m) { BaseTxBuilder::SetInOuts(m); m.m_pKernel.reset(new TxKernelStd); m.m_pKernel->m_Fee = m_Fee; m.m_pKernel->m_Height = m_Height; } void BaseTxBuilder::VerifyTx() { TxBase::Context::Params pars; TxBase::Context ctx(pars); ctx.m_Height.m_Min = m_Height.m_Min; // TODO:DEX set to false, other side will not see it!!! if (!m_pTransaction->IsValid(ctx)) throw TransactionFailedException(false, TxFailureReason::InvalidTransaction); } void BaseTxBuilder::VerifyAssetsEnabled() { TxFailureReason res = CheckAssetsEnabled(m_Height.m_Min); if (TxFailureReason::Count != res) throw TransactionFailedException(!m_Tx.IsInitiator(), res); } bool BaseTxBuilder::SignTx() { return true; } void BaseTxBuilder::FinalyzeTx() { if (Status::FullTx == m_Status) return; assert(!IsGeneratingInOuts()); FinalizeTxInternal(); } void BaseTxBuilder::FinalizeTxInternal() { m_pTransaction->Normalize(); VerifyTx(); SaveInOuts(); SetStatus(Status::FullTx); } void BaseTxBuilder::AddKernel(TxKernel::Ptr&& pKrn) { m_pKrn = pKrn.get(); m_pTransaction->m_vKernels.push_back(std::move(pKrn)); } void BaseTxBuilder::SetStatus(Status::Type s) { SaveAndStore(m_Status, TxParameterID::MutualTxState, s); } void BaseTxBuilder::FillUserData(Output::User::Packed* user) { user->m_TxID = Blob(m_Tx.GetTxID().data(), (uint32_t)m_Tx.GetTxID().size()); user->m_Fee = m_Fee; } string BaseTxBuilder::GetKernelIDString() const { Merkle::Hash kernelID; GetParameter(TxParameterID::KernelID, kernelID); char sz[Merkle::Hash::nTxtLen + 1]; kernelID.Print(sz); return string(sz); } void BaseTxBuilder::CheckMinimumFee(const TxStats* pFromPeer /* = nullptr */) { // after 1st fork fee should be >= minimal fee if (Rules::get().pForks[1].m_Height <= m_Height.m_Min) { Amount feeInps = 0; for (const auto& si : m_Coins.m_InputShielded) feeInps += si.m_Fee; // account for shielded inputs, they carry their fee individually TxStats ts; ts.m_Outputs = static_cast<uint32_t>(m_Coins.m_Output.size()); ts.m_InputsShielded = static_cast<uint32_t>(m_Coins.m_InputShielded.size()); ts.m_Kernels = 1 + static_cast<uint32_t>(m_Coins.m_InputShielded.size()); if (pFromPeer) ts += *pFromPeer; auto& fs = Transaction::FeeSettings::get(m_Height.m_Min); Amount minFee = fs.Calculate(ts); if (m_Fee + feeInps < minFee) { stringstream ss; ss << "The minimum fee must be: " << (minFee - feeInps) << " ."; throw TransactionFailedException(false, TxFailureReason::FeeIsTooSmall, ss.str().c_str()); } } } /////////////////////////////////////// // SimpleTxBuilder SimpleTxBuilder::SimpleTxBuilder(BaseTransaction& tx, SubTxID subTxID) : BaseTxBuilder(tx, subTxID) , m_Lifetime(kDefaultTxLifetime) { GetParameter(TxParameterID::Amount, m_Amount); GetParameter(TxParameterID::AssetID, m_AssetID); GetParameter(TxParameterID::Lifetime, m_Lifetime); } void SimpleTxBuilder::SignSplit() { if (Stage::None != m_Signing) return; struct MyHandler :public KeyKeeperHandler { using KeyKeeperHandler::KeyKeeperHandler; IPrivateKeyKeeper2::Method::SignSplit m_Method; virtual ~MyHandler() {} // auto virtual void OnSuccess(BaseTxBuilder& b_) override { SimpleTxBuilder& b = Cast::Up<SimpleTxBuilder>(b_); b.AddOffset(m_Method.m_kOffset); b.AddKernel(std::move(m_Method.m_pKernel)); b.SaveKernel(); b.SaveKernelID(); b.SetStatus(Status::SelfSigned); OnAllDone(b); } }; KeyKeeperHandler::Ptr pHandler = std::make_shared<MyHandler>(*this, m_Signing); MyHandler& x = Cast::Up<MyHandler>(*pHandler); SetCommon(x.m_Method); m_Tx.get_KeyKeeperStrict()->InvokeAsync(x.m_Method, pHandler); } bool SimpleTxBuilder::SignTx() { GenerateInOuts(); SignSplit(); return (m_Status >= Status::SelfSigned) && !IsGeneratingInOuts(); } void SimpleTxBuilder::FillUserData(Output::User::Packed* user) { BaseTxBuilder::FillUserData(user); user->m_Amount = m_Amount; } /////////////////////////////////////// // MutualTxBuilder MutualTxBuilder::MutualTxBuilder(BaseTransaction& tx, SubTxID subTxID) :SimpleTxBuilder(tx, subTxID) { GetParameter(TxParameterID::IsSender, m_IsSender); Height responseTime = 0; Height responseHeight = 0; if (GetParameter(TxParameterID::PeerResponseTime, responseTime) && !GetParameter(TxParameterID::PeerResponseHeight, responseHeight)) { auto currentHeight = m_Tx.GetWalletDB()->getCurrentHeight(); // adjust response height, if min height did not set then it should be equal to responce time SetParameter(TxParameterID::PeerResponseHeight, responseTime + currentHeight); } } void MutualTxBuilder::CreateKernel(TxKernelStd::Ptr& pKrn) { pKrn = make_unique<TxKernelStd>(); pKrn->m_Fee = m_Fee; pKrn->m_Height.m_Min = m_Height.m_Min; pKrn->m_Height.m_Max = m_Height.m_Max; pKrn->m_Commitment = Zero; ZeroObject(pKrn->m_Signature); // load kernel's extra data Hash::Value hv; if (GetParameter(TxParameterID::PeerLockImage, hv)) { pKrn->m_pHashLock = make_unique<TxKernelStd::HashLock>(); pKrn->m_pHashLock->m_IsImage = true; pKrn->m_pHashLock->m_Value = hv; } if (GetParameter(TxParameterID::PreImage, hv)) { pKrn->m_pHashLock = make_unique<TxKernelStd::HashLock>(); pKrn->m_pHashLock->m_Value = hv; } } void MutualTxBuilder::AddPeerSignature(const ECC::Point::Native& ptNonce, const ECC::Point::Native& ptExc) { GetParameterStrict(TxParameterID::PeerSignature, m_pKrn->CastTo_Std().m_Signature.m_k); if (!m_pKrn->CastTo_Std().m_Signature.IsValidPartial(m_pKrn->m_Internal.m_ID, ptNonce, ptExc)) throw TransactionFailedException(true, TxFailureReason::InvalidPeerSignature); } bool MutualTxBuilder::LoadPeerPart(ECC::Point::Native& ptNonce, ECC::Point::Native& ptExc) { ECC::Point pt; return GetParameter(TxParameterID::PeerPublicNonce, pt) && ptNonce.Import(pt) && GetParameter(TxParameterID::PeerPublicExcess, pt) && ptExc.Import(pt); } void MutualTxBuilder::AddPeerOffset() { ECC::Scalar k; if (GetParameter(TxParameterID::PeerOffset, k)) AddOffset(k); } void MutualTxBuilder::FinalizeTxInternal() { // add peer in/out/offs AddPeerOffset(); std::vector<Input::Ptr> vIns; if (GetParameter(TxParameterID::PeerInputs, vIns)) MoveIntoVec(m_pTransaction->m_vInputs, vIns); std::vector<Output::Ptr> vOuts; if (GetParameter(TxParameterID::PeerOutputs, vOuts)) MoveIntoVec(m_pTransaction->m_vOutputs, vOuts); SimpleTxBuilder::FinalizeTxInternal(); } void MutualTxBuilder::SignSender(bool initial) { if (Stage::InProgress == m_Signing) return; m_Signing = Stage::None; struct MyHandler :public KeyKeeperHandler { using KeyKeeperHandler::KeyKeeperHandler; IPrivateKeyKeeper2::Method::SignSender m_Method; virtual ~MyHandler() {} // auto virtual void OnSuccess(BaseTxBuilder& b_) override { MutualTxBuilder& b = Cast::Up<MutualTxBuilder>(b_); if (b.m_pKrn) { // final, update the signature only b.m_pKrn->CastTo_Std().m_Signature.m_k = m_Method.m_pKernel->m_Signature.m_k; b.AddOffset(m_Method.m_kOffset); b.m_Tx.FreeSlotSafe(); // release it ASAP b.SetStatus(Status::SndFull); } else { // initial b.SetParameter(TxParameterID::UserConfirmationToken, m_Method.m_UserAgreement); b.AddKernel(std::move(m_Method.m_pKernel)); b.SetStatus(Status::SndHalf); } b.SaveKernel(); OnAllDone(b); } }; KeyKeeperHandler::Ptr pHandler = std::make_shared<MyHandler>(*this, m_Signing); MyHandler& x = Cast::Up<MyHandler>(*pHandler); IPrivateKeyKeeper2::Method::SignSender& m = x.m_Method; SetInOuts(m); m.m_Slot = m_Tx.GetSlotSafe(true); if (GetParameter(TxParameterID::PeerWalletIdentity, m.m_Peer) && GetParameter(TxParameterID::MyWalletIdentity, m.m_MyID)) { // newer scheme GetParameterStrict(TxParameterID::MyAddressID, m.m_MyIDKey); } else { // legacy. Will fail for trustless key keeper. m.m_MyIDKey = 0; WalletID widMy, widPeer; if (GetParameter(TxParameterID::PeerID, widPeer) && GetParameter(TxParameterID::MyID, widMy)) { m.m_Peer = widPeer.m_Pk; m.m_MyID = widMy.m_Pk; } else { if (!m.m_NonConventional) throw TransactionFailedException(true, TxFailureReason::NotEnoughDataForProof); ZeroObject(m.m_Peer); ZeroObject(m.m_MyID); } } ZeroObject(m.m_PaymentProofSignature); m.m_UserAgreement = Zero; if (initial) CreateKernel(m.m_pKernel); else { m_pKrn->Clone(Cast::Reinterpret<TxKernel::Ptr>(m.m_pKernel)); GetParameter(TxParameterID::UserConfirmationToken, m.m_UserAgreement); if (m.m_UserAgreement == Zero) throw TransactionFailedException(true, TxFailureReason::FailedToGetParameter); GetParameter(TxParameterID::PaymentConfirmation, m.m_PaymentProofSignature); } m_Tx.get_KeyKeeperStrict()->InvokeAsync(x.m_Method, pHandler); } void MutualTxBuilder::SignReceiver() { if (Stage::InProgress == m_Signing) return; m_Signing = Stage::None; struct MyHandler :public KeyKeeperHandler { using KeyKeeperHandler::KeyKeeperHandler; IPrivateKeyKeeper2::Method::SignReceiver m_Method; virtual ~MyHandler() {} // auto void AssignExtractDiff(BaseTxBuilder& b, ECC::Point& dst, const ECC::Point& src, TxParameterID par) { dst.m_Y ^= 1; ECC::Point::Native pt; b.Aggregate(dst, pt, src); b.SetParameter(par, dst); dst = src; } virtual void OnSuccess(BaseTxBuilder& b_) override { MutualTxBuilder& b = Cast::Up<MutualTxBuilder>(b_); AssignExtractDiff(b, b.m_pKrn->CastTo_Std().m_Commitment, m_Method.m_pKernel->m_Commitment, TxParameterID::PublicExcess); AssignExtractDiff(b, b.m_pKrn->CastTo_Std().m_Signature.m_NoncePub, m_Method.m_pKernel->m_Signature.m_NoncePub, TxParameterID::PublicNonce); b.m_pKrn->CastTo_Std().m_Signature.m_k = m_Method.m_pKernel->m_Signature.m_k; b.m_pKrn->UpdateID(); b.SaveKernel(); b.SaveKernelID(); b.SetStatus(Status::RcvFullHalfSig); b.AddOffset(m_Method.m_kOffset); if (m_Method.m_MyIDKey) b.SetParameter(TxParameterID::PaymentConfirmation, m_Method.m_PaymentProofSignature); OnAllDone(b); } }; KeyKeeperHandler::Ptr pHandler = std::make_shared<MyHandler>(*this, m_Signing); MyHandler& x = Cast::Up<MyHandler>(*pHandler); IPrivateKeyKeeper2::Method::SignReceiver& m = x.m_Method; SetInOuts(m); m_pKrn->Clone(Cast::Reinterpret<TxKernel::Ptr>(m.m_pKernel)); m.m_Peer = Zero; m.m_MyIDKey = 0; GetParameter(TxParameterID::PeerWalletIdentity, m.m_Peer); if (m.m_Peer != Zero) GetParameter(TxParameterID::MyAddressID, m.m_MyIDKey); m_Tx.get_KeyKeeperStrict()->InvokeAsync(x.m_Method, pHandler); } void MutualTxBuilder::FinalyzeMaxHeight() { if (MaxHeight != m_Height.m_Max) return; // already decided GetParameter(TxParameterID::PeerMaxHeight, m_Height.m_Max); GetParameter(TxParameterID::Lifetime, m_Lifetime); // refresh it too // receiver is allowed to adjust what was suggested by the sender if (!m_IsSender && m_Lifetime) { // we're allowed to adjust peer's sugggested max height Block::SystemState::Full s; if (m_Tx.GetTip(s)) m_Height.m_Max = s.m_Height + m_Lifetime; } // sanity check Height hPeerResponce = 0; GetParameter(TxParameterID::PeerResponseHeight, hPeerResponce); if (hPeerResponce && (m_Height.m_Max > m_Lifetime + hPeerResponce)) throw TransactionFailedException(true, TxFailureReason::MaxHeightIsUnacceptable); SetParameter(TxParameterID::MaxHeight, m_Height.m_Max); } bool MutualTxBuilder::SignTx() { GenerateInOuts(); bool bRes = m_IsSender ? SignTxSender() : SignTxReceiver(); if (!bRes) m_Tx.UpdateOnNextTip(); return bRes; } bool MutualTxBuilder::SignTxSender() { switch (m_Status) { case Status::None: SignSender(true); break; case Status::SndHalf: { SetTxParameter msg; msg .AddParameter(TxParameterID::PeerPublicExcess, m_pKrn->CastTo_Std().m_Commitment) .AddParameter(TxParameterID::PeerPublicNonce, m_pKrn->CastTo_Std().m_Signature.m_NoncePub); if (m_pKrn->CastTo_Std().m_pHashLock) { ECC::Hash::Value lockImage = m_pKrn->CastTo_Std().m_pHashLock->get_Image(lockImage); msg.AddParameter(TxParameterID::PeerLockImage, lockImage); } SendToPeer(std::move(msg)); SetStatus(Status::SndHalfSent); } // no break; case Status::SndHalfSent: { // check if receiver part is ready ECC::Point::Native ptNonce, ptExc; if (!LoadPeerPart(ptNonce, ptExc)) break; Aggregate(m_pKrn->CastTo_Std().m_Commitment, ptExc); Aggregate(m_pKrn->CastTo_Std().m_Signature.m_NoncePub, ptNonce); FinalyzeMaxHeight(); m_pKrn->m_Height.m_Max = m_Height.m_Max; // can be different from the original m_pKrn->UpdateID(); // must be valid already SaveKernelID(); AddPeerSignature(ptNonce, ptExc); SaveKernel(); SetStatus(Status::SndFullHalfSig); } // no break; case Status::SndFullHalfSig: SignSender(false); } return (m_Status >= Status::SndFull) && !IsGeneratingInOuts(); } bool MutualTxBuilder::SignTxReceiver() { switch (m_Status) { case Status::None: { ECC::Point ptNonce, ptExc; if (!GetParameter(TxParameterID::PeerPublicNonce, ptNonce) || !GetParameter(TxParameterID::PeerPublicExcess, ptExc)) break; FinalyzeMaxHeight(); TxKernelStd::Ptr pKrn; CreateKernel(pKrn); pKrn->m_Commitment = ptExc; pKrn->m_Signature.m_NoncePub = ptNonce; AddKernel(std::move(pKrn)); SaveKernel(); SetStatus(Status::RcvHalf); } // no break; case Status::RcvHalf: SignReceiver(); break; case Status::RcvFullHalfSig: { if (IsGeneratingInOuts()) break; SetTxParameter msg; msg .AddParameter(TxParameterID::PeerPublicExcess, GetParameterStrict<ECC::Point>(TxParameterID::PublicExcess)) .AddParameter(TxParameterID::PeerPublicNonce, GetParameterStrict<ECC::Point>(TxParameterID::PublicNonce)) .AddParameter(TxParameterID::PeerSignature, m_pKrn->CastTo_Std().m_Signature.m_k) .AddParameter(TxParameterID::PeerInputs, m_pTransaction->m_vInputs) .AddParameter(TxParameterID::PeerOutputs, m_pTransaction->m_vOutputs) .AddParameter(TxParameterID::PeerOffset, m_pTransaction->m_Offset); Signature sig; if (GetParameter(TxParameterID::PaymentConfirmation, sig)) msg.AddParameter(TxParameterID::PaymentConfirmation, sig); SendToPeer(std::move(msg)); SetStatus(Status::RcvFullHalfSigSent); } } return (m_Status >= Status::RcvFullHalfSigSent); } void MutualTxBuilder::FillUserData(Output::User::Packed* user) { SimpleTxBuilder::FillUserData(user); PeerID peerID = Zero; m_Tx.GetParameter(TxParameterID::PeerWalletIdentity, peerID); user->m_Peer = peerID; } }
32.393594
177
0.546811
[ "object", "vector" ]
ce09d5cdd803f99aeac2b5622f7ade5379581fd0
68,943
cpp
C++
third_party/subzero/src/IceCfg.cpp
cmwheat/swiftshader
a36f7d145540d8b51510295db1fc595ad3b17e4a
[ "Apache-2.0" ]
1
2021-11-04T21:24:16.000Z
2021-11-04T21:24:16.000Z
third_party/subzero/src/IceCfg.cpp
cmwheat/swiftshader
a36f7d145540d8b51510295db1fc595ad3b17e4a
[ "Apache-2.0" ]
null
null
null
third_party/subzero/src/IceCfg.cpp
cmwheat/swiftshader
a36f7d145540d8b51510295db1fc595ad3b17e4a
[ "Apache-2.0" ]
null
null
null
//===- subzero/src/IceCfg.cpp - Control flow graph implementation ---------===// // // The Subzero Code Generator // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Implements the Cfg class. /// //===----------------------------------------------------------------------===// #include "IceCfg.h" #include "IceAssembler.h" #include "IceBitVector.h" #include "IceCfgNode.h" #include "IceClFlags.h" #include "IceDefs.h" #include "IceELFObjectWriter.h" #include "IceGlobalInits.h" #include "IceInst.h" #include "IceInstVarIter.h" #include "IceInstrumentation.h" #include "IceLiveness.h" #include "IceLoopAnalyzer.h" #include "IceOperand.h" #include "IceTargetLowering.h" #include <memory> #include <utility> namespace Ice { Cfg::Cfg(GlobalContext *Ctx, uint32_t SequenceNumber) : Allocator(createAllocator()), Ctx(Ctx), SequenceNumber(SequenceNumber), VMask(getFlags().getVerbose()), FunctionName(), NextInstNumber(Inst::NumberInitial), Live(nullptr) { NodeStrings.reset(new StringPool); VarStrings.reset(new StringPool); CfgLocalAllocatorScope _(this); Target = TargetLowering::createLowering(getFlags().getTargetArch(), this); VMetadata.reset(new VariablesMetadata(this)); TargetAssembler = Target->createAssembler(); if (getFlags().getRandomizeAndPoolImmediatesOption() == RPI_Randomize) { // If -randomize-pool-immediates=randomize, create a random number // generator to generate a cookie for constant blinding. RandomNumberGenerator RNG(getFlags().getRandomSeed(), RPE_ConstantBlinding, this->SequenceNumber); ConstantBlindingCookie = (uint32_t)RNG.next((uint64_t)std::numeric_limits<uint32_t>::max() + 1); } } Cfg::~Cfg() { assert(CfgAllocatorTraits::current() == nullptr); if (getFlags().getDumpStrings()) { OstreamLocker _(Ctx); Ostream &Str = Ctx->getStrDump(); getNodeStrings()->dump(Str); getVarStrings()->dump(Str); } } // Called in the initalizer list of Cfg's constructor to create the Allocator // and set it as TLS before any other member fields are constructed, since they // may depend on it. ArenaAllocator *Cfg::createAllocator() { ArenaAllocator *Allocator = new ArenaAllocator(); CfgAllocatorTraits::set_current(Allocator); return Allocator; } /// Create a string like "foo(i=123:b=9)" indicating the function name, number /// of high-level instructions, and number of basic blocks. This string is only /// used for dumping and other diagnostics, and the idea is that given a set of /// functions to debug a problem on, it's easy to find the smallest or simplest /// function to attack. Note that the counts may change somewhat depending on /// what point it is called during the translation passes. std::string Cfg::getFunctionNameAndSize() const { if (!BuildDefs::dump()) return getFunctionName().toString(); SizeT NodeCount = 0; SizeT InstCount = 0; for (CfgNode *Node : getNodes()) { ++NodeCount; // Note: deleted instructions are *not* ignored. InstCount += Node->getPhis().size(); for (Inst &I : Node->getInsts()) { if (!llvm::isa<InstTarget>(&I)) ++InstCount; } } return getFunctionName() + "(i=" + std::to_string(InstCount) + ":b=" + std::to_string(NodeCount) + ")"; } void Cfg::setError(const std::string &Message) { HasError = true; ErrorMessage = Message; } CfgNode *Cfg::makeNode() { SizeT LabelIndex = Nodes.size(); auto *Node = CfgNode::create(this, LabelIndex); Nodes.push_back(Node); return Node; } void Cfg::swapNodes(NodeList &NewNodes) { assert(Nodes.size() == NewNodes.size()); Nodes.swap(NewNodes); for (SizeT I = 0, NumNodes = getNumNodes(); I < NumNodes; ++I) Nodes[I]->resetIndex(I); } template <> Variable *Cfg::makeVariable<Variable>(Type Ty) { SizeT Index = Variables.size(); Variable *Var; if (Target->shouldSplitToVariableVecOn32(Ty)) { Var = VariableVecOn32::create(this, Ty, Index); } else if (Target->shouldSplitToVariable64On32(Ty)) { Var = Variable64On32::create(this, Ty, Index); } else { Var = Variable::create(this, Ty, Index); } Variables.push_back(Var); return Var; } void Cfg::addArg(Variable *Arg) { Arg->setIsArg(); Args.push_back(Arg); } void Cfg::addImplicitArg(Variable *Arg) { Arg->setIsImplicitArg(); ImplicitArgs.push_back(Arg); } // Returns whether the stack frame layout has been computed yet. This is used // for dumping the stack frame location of Variables. bool Cfg::hasComputedFrame() const { return getTarget()->hasComputedFrame(); } namespace { constexpr char BlockNameGlobalPrefix[] = ".L$profiler$block_name$"; constexpr char BlockStatsGlobalPrefix[] = ".L$profiler$block_info$"; } // end of anonymous namespace void Cfg::createNodeNameDeclaration(const std::string &NodeAsmName) { auto *Var = VariableDeclaration::create(GlobalInits.get()); Var->setName(Ctx, BlockNameGlobalPrefix + NodeAsmName); Var->setIsConstant(true); Var->addInitializer(VariableDeclaration::DataInitializer::create( GlobalInits.get(), NodeAsmName.data(), NodeAsmName.size() + 1)); const SizeT Int64ByteSize = typeWidthInBytes(IceType_i64); Var->setAlignment(Int64ByteSize); // Wasteful, 32-bit could use 4 bytes. GlobalInits->push_back(Var); } void Cfg::createBlockProfilingInfoDeclaration( const std::string &NodeAsmName, VariableDeclaration *NodeNameDeclaration) { auto *Var = VariableDeclaration::create(GlobalInits.get()); Var->setName(Ctx, BlockStatsGlobalPrefix + NodeAsmName); const SizeT Int64ByteSize = typeWidthInBytes(IceType_i64); Var->addInitializer(VariableDeclaration::ZeroInitializer::create( GlobalInits.get(), Int64ByteSize)); const RelocOffsetT NodeNameDeclarationOffset = 0; Var->addInitializer(VariableDeclaration::RelocInitializer::create( GlobalInits.get(), NodeNameDeclaration, {RelocOffset::create(Ctx, NodeNameDeclarationOffset)})); Var->setAlignment(Int64ByteSize); GlobalInits->push_back(Var); } void Cfg::profileBlocks() { if (GlobalInits == nullptr) GlobalInits.reset(new VariableDeclarationList()); for (CfgNode *Node : Nodes) { const std::string NodeAsmName = Node->getAsmName(); createNodeNameDeclaration(NodeAsmName); createBlockProfilingInfoDeclaration(NodeAsmName, GlobalInits->back()); Node->profileExecutionCount(GlobalInits->back()); } } bool Cfg::isProfileGlobal(const VariableDeclaration &Var) { if (!Var.getName().hasStdString()) return false; return Var.getName().toString().find(BlockStatsGlobalPrefix) == 0; } void Cfg::addCallToProfileSummary() { // The call(s) to __Sz_profile_summary are added by the profiler in functions // that cause the program to exit. This function is defined in // runtime/szrt_profiler.c. Constant *ProfileSummarySym = Ctx->getConstantExternSym(Ctx->getGlobalString("__Sz_profile_summary")); constexpr SizeT NumArgs = 0; constexpr Variable *Void = nullptr; constexpr bool HasTailCall = false; auto *Call = InstCall::create(this, NumArgs, Void, ProfileSummarySym, HasTailCall); getEntryNode()->getInsts().push_front(Call); } void Cfg::translate() { if (hasError()) return; // Cache the possibly-overridden optimization level once translation begins. // It would be nicer to do this in the constructor, but we need to wait until // after setFunctionName() has a chance to be called. OptimizationLevel = getFlags().matchForceO2(getFunctionName(), getSequenceNumber()) ? Opt_2 : getFlags().getOptLevel(); if (BuildDefs::timers()) { if (getFlags().matchTimingFocus(getFunctionName(), getSequenceNumber())) { setFocusedTiming(); getContext()->resetTimer(GlobalContext::TSK_Default); } } if (BuildDefs::dump()) { if (isVerbose(IceV_Status) && getFlags().matchTestStatus(getFunctionName(), getSequenceNumber())) { getContext()->getStrDump() << ">>>Translating " << getFunctionNameAndSize() << " seq=" << getSequenceNumber() << "\n"; } } TimerMarker T_func(getContext(), getFunctionName().toStringOrEmpty()); TimerMarker T(TimerStack::TT_translate, this); dump("Initial CFG"); if (getFlags().getEnableBlockProfile()) { profileBlocks(); // TODO(jpp): this is fragile, at best. Figure out a better way of // detecting exit functions. if (getFunctionName().toStringOrEmpty() == "exit") { addCallToProfileSummary(); } dump("Profiled CFG"); } // Create the Hi and Lo variables where a split was needed for (Variable *Var : Variables) { if (auto *Var64On32 = llvm::dyn_cast<Variable64On32>(Var)) { Var64On32->initHiLo(this); } else if (auto *VarVecOn32 = llvm::dyn_cast<VariableVecOn32>(Var)) { VarVecOn32->initVecElement(this); } } // Instrument the Cfg, e.g. with AddressSanitizer if (!BuildDefs::minimal() && getFlags().getSanitizeAddresses()) { getContext()->instrumentFunc(this); dump("Instrumented CFG"); } // The set of translation passes and their order are determined by the // target. getTarget()->translate(); dump("Final output"); if (getFocusedTiming()) { getContext()->dumpLocalTimers(getFunctionName().toString()); } } void Cfg::fixPhiNodes() { for (auto *Node : Nodes) { // Fix all the phi edges since WASM can't tell how to make them correctly at // the beginning. assert(Node); const auto &InEdges = Node->getInEdges(); for (auto &Instr : Node->getPhis()) { auto *Phi = llvm::cast<InstPhi>(&Instr); assert(Phi); for (SizeT i = 0; i < InEdges.size(); ++i) { Phi->setLabel(i, InEdges[i]); } } } } void Cfg::computeInOutEdges() { // Compute the out-edges. for (CfgNode *Node : Nodes) { Node->computeSuccessors(); } // Prune any unreachable nodes before computing in-edges. SizeT NumNodes = getNumNodes(); BitVector Reachable(NumNodes); BitVector Pending(NumNodes); Pending.set(getEntryNode()->getIndex()); while (true) { int Index = Pending.find_first(); if (Index == -1) break; Pending.reset(Index); Reachable.set(Index); CfgNode *Node = Nodes[Index]; assert(Node->getIndex() == (SizeT)Index); for (CfgNode *Succ : Node->getOutEdges()) { SizeT SuccIndex = Succ->getIndex(); if (!Reachable.test(SuccIndex)) Pending.set(SuccIndex); } } SizeT Dest = 0; for (SizeT Source = 0; Source < NumNodes; ++Source) { if (Reachable.test(Source)) { Nodes[Dest] = Nodes[Source]; Nodes[Dest]->resetIndex(Dest); // Compute the in-edges. Nodes[Dest]->computePredecessors(); ++Dest; } } Nodes.resize(Dest); TimerMarker T(TimerStack::TT_phiValidation, this); for (CfgNode *Node : Nodes) Node->enforcePhiConsistency(); } void Cfg::renumberInstructions() { TimerMarker T(TimerStack::TT_renumberInstructions, this); NextInstNumber = Inst::NumberInitial; for (CfgNode *Node : Nodes) Node->renumberInstructions(); // Make sure the entry node is the first node and therefore got the lowest // instruction numbers, to facilitate live range computation of function // arguments. We want to model function arguments as being live on entry to // the function, otherwise an argument whose only use is in the first // instruction will be assigned a trivial live range and the register // allocator will not recognize its live range as overlapping another // variable's live range. assert(Nodes.empty() || (*Nodes.begin() == getEntryNode())); } // placePhiLoads() must be called before placePhiStores(). void Cfg::placePhiLoads() { TimerMarker T(TimerStack::TT_placePhiLoads, this); for (CfgNode *Node : Nodes) Node->placePhiLoads(); } // placePhiStores() must be called after placePhiLoads(). void Cfg::placePhiStores() { TimerMarker T(TimerStack::TT_placePhiStores, this); for (CfgNode *Node : Nodes) Node->placePhiStores(); } void Cfg::deletePhis() { TimerMarker T(TimerStack::TT_deletePhis, this); for (CfgNode *Node : Nodes) Node->deletePhis(); } void Cfg::advancedPhiLowering() { TimerMarker T(TimerStack::TT_advancedPhiLowering, this); // Clear all previously computed live ranges (but not live-in/live-out bit // vectors or last-use markers), because the follow-on register allocation is // only concerned with live ranges across the newly created blocks. for (Variable *Var : Variables) { Var->getLiveRange().reset(); } // This splits edges and appends new nodes to the end of the node list. This // can invalidate iterators, so don't use an iterator. SizeT NumNodes = getNumNodes(); SizeT NumVars = getNumVariables(); for (SizeT I = 0; I < NumNodes; ++I) Nodes[I]->advancedPhiLowering(); TimerMarker TT(TimerStack::TT_lowerPhiAssignments, this); if (true) { // The following code does an in-place update of liveness and live ranges // as a result of adding the new phi edge split nodes. getLiveness()->initPhiEdgeSplits(Nodes.begin() + NumNodes, Variables.begin() + NumVars); TimerMarker TTT(TimerStack::TT_liveness, this); // Iterate over the newly added nodes to add their liveness info. for (auto I = Nodes.begin() + NumNodes, E = Nodes.end(); I != E; ++I) { InstNumberT FirstInstNum = getNextInstNumber(); (*I)->renumberInstructions(); InstNumberT LastInstNum = getNextInstNumber() - 1; (*I)->liveness(getLiveness()); (*I)->livenessAddIntervals(getLiveness(), FirstInstNum, LastInstNum); } } else { // The following code does a brute-force recalculation of live ranges as a // result of adding the new phi edge split nodes. The liveness calculation // is particularly expensive because the new nodes are not yet in a proper // topological order and so convergence is slower. // // This code is kept here for reference and can be temporarily enabled in // case the incremental code is under suspicion. renumberInstructions(); liveness(Liveness_Intervals); getVMetadata()->init(VMK_All); } Target->regAlloc(RAK_Phi); } // Find a reasonable placement for nodes that have not yet been placed, while // maintaining the same relative ordering among already placed nodes. void Cfg::reorderNodes() { // TODO(ascull): it would be nice if the switch tests were always followed by // the default case to allow for fall through. using PlacedList = CfgList<CfgNode *>; PlacedList Placed; // Nodes with relative placement locked down PlacedList Unreachable; // Unreachable nodes PlacedList::iterator NoPlace = Placed.end(); // Keep track of where each node has been tentatively placed so that we can // manage insertions into the middle. CfgVector<PlacedList::iterator> PlaceIndex(Nodes.size(), NoPlace); for (CfgNode *Node : Nodes) { // The "do ... while(0);" construct is to factor out the --PlaceIndex and // assert() statements before moving to the next node. do { if (Node != getEntryNode() && Node->getInEdges().empty()) { // The node has essentially been deleted since it is not a successor of // any other node. Unreachable.push_back(Node); PlaceIndex[Node->getIndex()] = Unreachable.end(); Node->setNeedsPlacement(false); continue; } if (!Node->needsPlacement()) { // Add to the end of the Placed list. Placed.push_back(Node); PlaceIndex[Node->getIndex()] = Placed.end(); continue; } Node->setNeedsPlacement(false); // Assume for now that the unplaced node is from edge-splitting and // therefore has 1 in-edge and 1 out-edge (actually, possibly more than 1 // in-edge if the predecessor node was contracted). If this changes in // the future, rethink the strategy. assert(Node->getInEdges().size() >= 1); assert(Node->hasSingleOutEdge()); // If it's a (non-critical) edge where the successor has a single // in-edge, then place it before the successor. CfgNode *Succ = Node->getOutEdges().front(); if (Succ->getInEdges().size() == 1 && PlaceIndex[Succ->getIndex()] != NoPlace) { Placed.insert(PlaceIndex[Succ->getIndex()], Node); PlaceIndex[Node->getIndex()] = PlaceIndex[Succ->getIndex()]; continue; } // Otherwise, place it after the (first) predecessor. CfgNode *Pred = Node->getInEdges().front(); auto PredPosition = PlaceIndex[Pred->getIndex()]; // It shouldn't be the case that PredPosition==NoPlace, but if that // somehow turns out to be true, we just insert Node before // PredPosition=NoPlace=Placed.end() . if (PredPosition != NoPlace) ++PredPosition; Placed.insert(PredPosition, Node); PlaceIndex[Node->getIndex()] = PredPosition; } while (0); --PlaceIndex[Node->getIndex()]; assert(*PlaceIndex[Node->getIndex()] == Node); } // Reorder Nodes according to the built-up lists. NodeList Reordered; Reordered.reserve(Placed.size() + Unreachable.size()); for (CfgNode *Node : Placed) Reordered.push_back(Node); for (CfgNode *Node : Unreachable) Reordered.push_back(Node); assert(getNumNodes() == Reordered.size()); swapNodes(Reordered); } namespace { void getRandomPostOrder(CfgNode *Node, BitVector &ToVisit, Ice::NodeList &PostOrder, Ice::RandomNumberGenerator *RNG) { assert(ToVisit[Node->getIndex()]); ToVisit[Node->getIndex()] = false; NodeList Outs = Node->getOutEdges(); Ice::RandomShuffle(Outs.begin(), Outs.end(), [RNG](int N) { return RNG->next(N); }); for (CfgNode *Next : Outs) { if (ToVisit[Next->getIndex()]) getRandomPostOrder(Next, ToVisit, PostOrder, RNG); } PostOrder.push_back(Node); } } // end of anonymous namespace void Cfg::shuffleNodes() { if (!getFlags().getReorderBasicBlocks()) return; NodeList ReversedReachable; NodeList Unreachable; BitVector ToVisit(Nodes.size(), true); // Create Random number generator for function reordering RandomNumberGenerator RNG(getFlags().getRandomSeed(), RPE_BasicBlockReordering, SequenceNumber); // Traverse from entry node. getRandomPostOrder(getEntryNode(), ToVisit, ReversedReachable, &RNG); // Collect the unreachable nodes. for (CfgNode *Node : Nodes) if (ToVisit[Node->getIndex()]) Unreachable.push_back(Node); // Copy the layout list to the Nodes. NodeList Shuffled; Shuffled.reserve(ReversedReachable.size() + Unreachable.size()); for (CfgNode *Node : reverse_range(ReversedReachable)) Shuffled.push_back(Node); for (CfgNode *Node : Unreachable) Shuffled.push_back(Node); assert(Nodes.size() == Shuffled.size()); swapNodes(Shuffled); dump("After basic block shuffling"); } void Cfg::localCSE(bool AssumeSSA) { // Performs basic-block local common-subexpression elimination // If we have // t1 = op b c // t2 = op b c // This pass will replace future references to t2 in a basic block by t1 // Points to note: // 1. Assumes SSA by default. To change this, use -lcse=no-ssa // This is needed if this pass is moved to a point later in the pipeline. // If variables have a single definition (in the node), CSE can work just // on the basis of an equality compare on instructions (sans Dest). When // variables can be updated (hence, non-SSA) the result of a previous // instruction which used that variable as an operand can not be reused. // 2. Leaves removal of instructions to DCE. // 3. Only enabled on arithmetic instructions. pnacl-clang (-O2) is expected // to take care of cases not arising from GEP simplification. // 4. By default, a single pass is made over each basic block. Control this // with -lcse-max-iters=N TimerMarker T(TimerStack::TT_localCse, this); struct VariableHash { size_t operator()(const Variable *Var) const { return Var->hashValue(); } }; struct InstHash { size_t operator()(const Inst *Instr) const { auto Kind = Instr->getKind(); auto Result = std::hash<typename std::underlying_type<Inst::InstKind>::type>()( Kind); for (SizeT i = 0; i < Instr->getSrcSize(); ++i) { Result ^= Instr->getSrc(i)->hashValue(); } return Result; } }; struct InstEq { bool srcEq(const Operand *A, const Operand *B) const { if (llvm::isa<Variable>(A) || llvm::isa<Constant>(A)) return (A == B); return false; } bool operator()(const Inst *InstrA, const Inst *InstrB) const { if ((InstrA->getKind() != InstrB->getKind()) || (InstrA->getSrcSize() != InstrB->getSrcSize())) return false; if (auto *A = llvm::dyn_cast<InstArithmetic>(InstrA)) { auto *B = llvm::cast<InstArithmetic>(InstrB); // A, B are guaranteed to be of the same 'kind' at this point // So, dyn_cast is not needed if (A->getOp() != B->getOp()) return false; } // Does not enter loop if different kind or number of operands for (SizeT i = 0; i < InstrA->getSrcSize(); ++i) { if (!srcEq(InstrA->getSrc(i), InstrB->getSrc(i))) return false; } return true; } }; for (CfgNode *Node : getNodes()) { CfgUnorderedSet<Inst *, InstHash, InstEq> Seen; // Stores currently available instructions. CfgUnorderedMap<Variable *, Variable *, VariableHash> Replacements; // Combining the above two into a single data structure might consume less // memory but will be slower i.e map of Instruction -> Set of Variables CfgUnorderedMap<Variable *, std::vector<Inst *>, VariableHash> Dependency; // Maps a variable to the Instructions that depend on it. // a = op1 b c // x = op2 c d // Will result in the map : b -> {a}, c -> {a, x}, d -> {x} // Not necessary for SSA as dependencies will never be invalidated, and the // container will use minimal memory when left unused. auto IterCount = getFlags().getLocalCseMaxIterations(); for (uint32_t i = 0; i < IterCount; ++i) { // TODO(manasijm): Stats on IterCount -> performance for (Inst &Instr : Node->getInsts()) { if (Instr.isDeleted() || !llvm::isa<InstArithmetic>(&Instr)) continue; if (!AssumeSSA) { // Invalidate replacements auto Iter = Replacements.find(Instr.getDest()); if (Iter != Replacements.end()) { Replacements.erase(Iter); } // Invalidate 'seen' instructions whose operands were just updated. auto DepIter = Dependency.find(Instr.getDest()); if (DepIter != Dependency.end()) { for (auto *DepInst : DepIter->second) { Seen.erase(DepInst); } } } // Replace - doing this before checking for repetitions might enable // more optimizations for (SizeT i = 0; i < Instr.getSrcSize(); ++i) { auto *Opnd = Instr.getSrc(i); if (auto *Var = llvm::dyn_cast<Variable>(Opnd)) { if (Replacements.find(Var) != Replacements.end()) { Instr.replaceSource(i, Replacements[Var]); } } } // Check for repetitions auto SeenIter = Seen.find(&Instr); if (SeenIter != Seen.end()) { // seen before const Inst *Found = *SeenIter; Replacements[Instr.getDest()] = Found->getDest(); } else { // new Seen.insert(&Instr); if (!AssumeSSA) { // Update dependencies for (SizeT i = 0; i < Instr.getSrcSize(); ++i) { auto *Opnd = Instr.getSrc(i); if (auto *Var = llvm::dyn_cast<Variable>(Opnd)) { Dependency[Var].push_back(&Instr); } } } } } } } } void Cfg::loopInvariantCodeMotion() { TimerMarker T(TimerStack::TT_loopInvariantCodeMotion, this); // Does not introduce new nodes as of now. for (auto &Loop : LoopInfo) { CfgNode *Header = Loop.Header; assert(Header); if (Header->getLoopNestDepth() < 1) return; CfgNode *PreHeader = Loop.PreHeader; if (PreHeader == nullptr || PreHeader->getInsts().size() == 0) { return; // try next loop } auto &Insts = PreHeader->getInsts(); auto &LastInst = Insts.back(); Insts.pop_back(); for (auto *Inst : findLoopInvariantInstructions(Loop.Body)) { PreHeader->appendInst(Inst); } PreHeader->appendInst(&LastInst); } } CfgVector<Inst *> Cfg::findLoopInvariantInstructions(const CfgUnorderedSet<SizeT> &Body) { CfgUnorderedSet<Inst *> InvariantInsts; CfgUnorderedSet<Variable *> InvariantVars; for (auto *Var : getArgs()) { InvariantVars.insert(Var); } bool Changed = false; do { Changed = false; for (auto NodeIndex : Body) { auto *Node = Nodes[NodeIndex]; CfgVector<std::reference_wrapper<Inst>> Insts(Node->getInsts().begin(), Node->getInsts().end()); for (auto &InstRef : Insts) { auto &Inst = InstRef.get(); if (Inst.isDeleted() || InvariantInsts.find(&Inst) != InvariantInsts.end()) continue; switch (Inst.getKind()) { case Inst::InstKind::Alloca: case Inst::InstKind::Br: case Inst::InstKind::Ret: case Inst::InstKind::Phi: case Inst::InstKind::Call: case Inst::InstKind::IntrinsicCall: case Inst::InstKind::Load: case Inst::InstKind::Store: case Inst::InstKind::Switch: continue; default: break; } bool IsInvariant = true; for (SizeT i = 0; i < Inst.getSrcSize(); ++i) { if (auto *Var = llvm::dyn_cast<Variable>(Inst.getSrc(i))) { if (InvariantVars.find(Var) == InvariantVars.end()) { IsInvariant = false; } } } if (IsInvariant) { Changed = true; InvariantInsts.insert(&Inst); Node->getInsts().remove(Inst); if (Inst.getDest() != nullptr) { InvariantVars.insert(Inst.getDest()); } } } } } while (Changed); CfgVector<Inst *> InstVector(InvariantInsts.begin(), InvariantInsts.end()); std::sort(InstVector.begin(), InstVector.end(), [](Inst *A, Inst *B) { return A->getNumber() < B->getNumber(); }); return InstVector; } void Cfg::shortCircuitJumps() { // Split Nodes whenever an early jump is possible. // __N : // a = <something> // Instruction 1 without side effect // ... b = <something> ... // Instruction N without side effect // t1 = or a b // br t1 __X __Y // // is transformed into: // __N : // a = <something> // br a __X __N_ext // // __N_ext : // Instruction 1 without side effect // ... b = <something> ... // Instruction N without side effect // br b __X __Y // (Similar logic for AND, jump to false instead of true target.) TimerMarker T(TimerStack::TT_shortCircuit, this); getVMetadata()->init(VMK_Uses); auto NodeStack = this->getNodes(); CfgUnorderedMap<SizeT, CfgVector<CfgNode *>> Splits; while (!NodeStack.empty()) { auto *Node = NodeStack.back(); NodeStack.pop_back(); auto NewNode = Node->shortCircuit(); if (NewNode) { NodeStack.push_back(NewNode); NodeStack.push_back(Node); Splits[Node->getIndex()].push_back(NewNode); } } // Insert nodes in the right place NodeList NewList; NewList.reserve(Nodes.size()); CfgUnorderedSet<SizeT> Inserted; for (auto *Node : Nodes) { if (Inserted.find(Node->getIndex()) != Inserted.end()) continue; // already inserted NodeList Stack{Node}; while (!Stack.empty()) { auto *Current = Stack.back(); Stack.pop_back(); Inserted.insert(Current->getIndex()); NewList.push_back(Current); for (auto *Next : Splits[Current->getIndex()]) { Stack.push_back(Next); } } } SizeT NodeIndex = 0; for (auto *Node : NewList) { Node->resetIndex(NodeIndex++); } Nodes = NewList; } void Cfg::floatConstantCSE() { // Load multiple uses of a floating point constant (between two call // instructions or block start/end) into a variable before its first use. // t1 = b + 1.0 // t2 = c + 1.0 // Gets transformed to: // t0 = 1.0 // t0_1 = t0 // t1 = b + t0_1 // t2 = c + t0_1 // Call instructions reset the procedure, but use the same variable, just in // case it got a register. We are assuming floating point registers are not // callee saved in general. Example, continuing from before: // result = call <some function> // t3 = d + 1.0 // Gets transformed to: // result = call <some function> // t0_2 = t0 // t3 = d + t0_2 // TODO(manasijm, stichnot): Figure out how to 'link' t0 to the stack slot of // 1.0. When t0 does not get a register, introducing an extra assignment // statement does not make sense. The relevant portion is marked below. TimerMarker _(TimerStack::TT_floatConstantCse, this); for (CfgNode *Node : getNodes()) { CfgUnorderedMap<Constant *, Variable *> ConstCache; auto Current = Node->getInsts().begin(); auto End = Node->getInsts().end(); while (Current != End) { CfgUnorderedMap<Constant *, CfgVector<InstList::iterator>> FloatUses; if (llvm::isa<InstCall>(iteratorToInst(Current))) { ++Current; assert(Current != End); // Block should not end with a call } while (Current != End && !llvm::isa<InstCall>(iteratorToInst(Current))) { if (!Current->isDeleted()) { for (SizeT i = 0; i < Current->getSrcSize(); ++i) { if (auto *Const = llvm::dyn_cast<Constant>(Current->getSrc(i))) { if (Const->getType() == IceType_f32 || Const->getType() == IceType_f64) { FloatUses[Const].push_back(Current); } } } } ++Current; } for (auto &Pair : FloatUses) { static constexpr SizeT MinUseThreshold = 3; if (Pair.second.size() < MinUseThreshold) continue; // Only consider constants with at least `MinUseThreshold` uses auto &Insts = Node->getInsts(); if (ConstCache.find(Pair.first) == ConstCache.end()) { // Saw a constant (which is used at least twice) for the first time auto *NewVar = makeVariable(Pair.first->getType()); // NewVar->setLinkedTo(Pair.first); // TODO(manasijm): Plumbing for linking to an Operand. auto *Assign = InstAssign::create(Node->getCfg(), NewVar, Pair.first); Insts.insert(Pair.second[0], Assign); ConstCache[Pair.first] = NewVar; } auto *NewVar = makeVariable(Pair.first->getType()); NewVar->setLinkedTo(ConstCache[Pair.first]); auto *Assign = InstAssign::create(Node->getCfg(), NewVar, ConstCache[Pair.first]); Insts.insert(Pair.second[0], Assign); for (auto InstUse : Pair.second) { for (SizeT i = 0; i < InstUse->getSrcSize(); ++i) { if (auto *Const = llvm::dyn_cast<Constant>(InstUse->getSrc(i))) { if (Const == Pair.first) { InstUse->replaceSource(i, NewVar); } } } } } } } } void Cfg::doArgLowering() { TimerMarker T(TimerStack::TT_doArgLowering, this); getTarget()->lowerArguments(); } void Cfg::sortAndCombineAllocas(CfgVector<InstAlloca *> &Allocas, uint32_t CombinedAlignment, InstList &Insts, AllocaBaseVariableType BaseVariableType) { if (Allocas.empty()) return; // Sort by decreasing alignment. std::sort(Allocas.begin(), Allocas.end(), [](InstAlloca *A1, InstAlloca *A2) { uint32_t Align1 = A1->getAlignInBytes(); uint32_t Align2 = A2->getAlignInBytes(); if (Align1 == Align2) return A1->getNumber() < A2->getNumber(); else return Align1 > Align2; }); // Process the allocas in order of decreasing stack alignment. This allows // us to pack less-aligned pieces after more-aligned ones, resulting in less // stack growth. It also allows there to be at most one stack alignment "and" // instruction for a whole list of allocas. uint32_t CurrentOffset = 0; CfgVector<int32_t> Offsets; for (Inst *Instr : Allocas) { auto *Alloca = llvm::cast<InstAlloca>(Instr); // Adjust the size of the allocation up to the next multiple of the // object's alignment. uint32_t Alignment = std::max(Alloca->getAlignInBytes(), 1u); auto *ConstSize = llvm::dyn_cast<ConstantInteger32>(Alloca->getSizeInBytes()); uint32_t Size = Utils::applyAlignment(ConstSize->getValue(), Alignment); if (BaseVariableType == BVT_FramePointer) { // Addressing is relative to the frame pointer. Subtract the offset after // adding the size of the alloca, because it grows downwards from the // frame pointer. Offsets.push_back(Target->getFramePointerOffset(CurrentOffset, Size)); } else { // Addressing is relative to the stack pointer or to a user pointer. Add // the offset before adding the size of the object, because it grows // upwards from the stack pointer. In addition, if the addressing is // relative to the stack pointer, we need to add the pre-computed max out // args size bytes. const uint32_t OutArgsOffsetOrZero = (BaseVariableType == BVT_StackPointer) ? getTarget()->maxOutArgsSizeBytes() : 0; Offsets.push_back(CurrentOffset + OutArgsOffsetOrZero); } // Update the running offset of the fused alloca region. CurrentOffset += Size; } // Round the offset up to the alignment granularity to use as the size. uint32_t TotalSize = Utils::applyAlignment(CurrentOffset, CombinedAlignment); // Ensure every alloca was assigned an offset. assert(Allocas.size() == Offsets.size()); switch (BaseVariableType) { case BVT_UserPointer: { Variable *BaseVariable = makeVariable(IceType_i32); for (SizeT i = 0; i < Allocas.size(); ++i) { auto *Alloca = llvm::cast<InstAlloca>(Allocas[i]); // Emit a new addition operation to replace the alloca. Operand *AllocaOffset = Ctx->getConstantInt32(Offsets[i]); InstArithmetic *Add = InstArithmetic::create(this, InstArithmetic::Add, Alloca->getDest(), BaseVariable, AllocaOffset); Insts.push_front(Add); Alloca->setDeleted(); } Operand *AllocaSize = Ctx->getConstantInt32(TotalSize); InstAlloca *CombinedAlloca = InstAlloca::create(this, BaseVariable, AllocaSize, CombinedAlignment); CombinedAlloca->setKnownFrameOffset(); Insts.push_front(CombinedAlloca); } break; case BVT_StackPointer: case BVT_FramePointer: { for (SizeT i = 0; i < Allocas.size(); ++i) { auto *Alloca = llvm::cast<InstAlloca>(Allocas[i]); // Emit a fake definition of the rematerializable variable. Variable *Dest = Alloca->getDest(); auto *Def = InstFakeDef::create(this, Dest); if (BaseVariableType == BVT_StackPointer) Dest->setRematerializable(getTarget()->getStackReg(), Offsets[i]); else Dest->setRematerializable(getTarget()->getFrameReg(), Offsets[i]); Insts.push_front(Def); Alloca->setDeleted(); } // Allocate the fixed area in the function prolog. getTarget()->reserveFixedAllocaArea(TotalSize, CombinedAlignment); } break; } } void Cfg::processAllocas(bool SortAndCombine) { TimerMarker _(TimerStack::TT_alloca, this); const uint32_t StackAlignment = getTarget()->getStackAlignment(); CfgNode *EntryNode = getEntryNode(); assert(EntryNode); // LLVM enforces power of 2 alignment. assert(llvm::isPowerOf2_32(StackAlignment)); // If the ABI's stack alignment is smaller than the vector size (16 bytes), // conservatively use a frame pointer to allow for explicit alignment of the // stack pointer. This needs to happen before register allocation so the frame // pointer can be reserved. if (getTarget()->needsStackPointerAlignment()) { getTarget()->setHasFramePointer(); } // Determine if there are large alignment allocations in the entry block or // dynamic allocations (variable size in the entry block). bool HasLargeAlignment = false; bool HasDynamicAllocation = false; for (Inst &Instr : EntryNode->getInsts()) { if (Instr.isDeleted()) continue; if (auto *Alloca = llvm::dyn_cast<InstAlloca>(&Instr)) { uint32_t AlignmentParam = Alloca->getAlignInBytes(); if (AlignmentParam > StackAlignment) HasLargeAlignment = true; if (llvm::isa<Constant>(Alloca->getSizeInBytes())) Alloca->setKnownFrameOffset(); else { HasDynamicAllocation = true; // If Allocas are not sorted, the first dynamic allocation causes // later Allocas to be at unknown offsets relative to the stack/frame. if (!SortAndCombine) break; } } } // Don't do the heavyweight sorting and layout for low optimization levels. if (!SortAndCombine) return; // Any alloca outside the entry block is a dynamic allocation. for (CfgNode *Node : Nodes) { if (Node == EntryNode) continue; for (Inst &Instr : Node->getInsts()) { if (Instr.isDeleted()) continue; if (llvm::isa<InstAlloca>(&Instr)) { // Allocations outside the entry block require a frame pointer. HasDynamicAllocation = true; break; } } if (HasDynamicAllocation) break; } // Mark the target as requiring a frame pointer. if (HasLargeAlignment || HasDynamicAllocation) getTarget()->setHasFramePointer(); // Collect the Allocas into the two vectors. // Allocas in the entry block that have constant size and alignment less // than or equal to the function's stack alignment. CfgVector<InstAlloca *> FixedAllocas; // Allocas in the entry block that have constant size and alignment greater // than the function's stack alignment. CfgVector<InstAlloca *> AlignedAllocas; // Maximum alignment used by any alloca. uint32_t MaxAlignment = StackAlignment; for (Inst &Instr : EntryNode->getInsts()) { if (Instr.isDeleted()) continue; if (auto *Alloca = llvm::dyn_cast<InstAlloca>(&Instr)) { if (!llvm::isa<Constant>(Alloca->getSizeInBytes())) continue; uint32_t AlignmentParam = Alloca->getAlignInBytes(); // For default align=0, set it to the real value 1, to avoid any // bit-manipulation problems below. AlignmentParam = std::max(AlignmentParam, 1u); assert(llvm::isPowerOf2_32(AlignmentParam)); if (HasDynamicAllocation && AlignmentParam > StackAlignment) { // If we have both dynamic allocations and large stack alignments, // high-alignment allocations are pulled out with their own base. AlignedAllocas.push_back(Alloca); } else { FixedAllocas.push_back(Alloca); } MaxAlignment = std::max(AlignmentParam, MaxAlignment); } } // Add instructions to the head of the entry block in reverse order. InstList &Insts = getEntryNode()->getInsts(); if (HasDynamicAllocation && HasLargeAlignment) { // We are using a frame pointer, but fixed large-alignment alloca addresses // do not have a known offset from either the stack or frame pointer. // They grow up from a user pointer from an alloca. sortAndCombineAllocas(AlignedAllocas, MaxAlignment, Insts, BVT_UserPointer); // Fixed size allocas are addressed relative to the frame pointer. sortAndCombineAllocas(FixedAllocas, StackAlignment, Insts, BVT_FramePointer); } else { // Otherwise, fixed size allocas are addressed relative to the stack unless // there are dynamic allocas. const AllocaBaseVariableType BasePointerType = (HasDynamicAllocation ? BVT_FramePointer : BVT_StackPointer); sortAndCombineAllocas(FixedAllocas, MaxAlignment, Insts, BasePointerType); } if (!FixedAllocas.empty() || !AlignedAllocas.empty()) // No use calling findRematerializable() unless there is some // rematerializable alloca instruction to seed it. findRematerializable(); } namespace { // Helpers for findRematerializable(). For each of them, if a suitable // rematerialization is found, the instruction's Dest variable is set to be // rematerializable and it returns true, otherwise it returns false. bool rematerializeArithmetic(const Inst *Instr) { // Check that it's an Arithmetic instruction with an Add operation. auto *Arith = llvm::dyn_cast<InstArithmetic>(Instr); if (Arith == nullptr || Arith->getOp() != InstArithmetic::Add) return false; // Check that Src(0) is rematerializable. auto *Src0Var = llvm::dyn_cast<Variable>(Arith->getSrc(0)); if (Src0Var == nullptr || !Src0Var->isRematerializable()) return false; // Check that Src(1) is an immediate. auto *Src1Imm = llvm::dyn_cast<ConstantInteger32>(Arith->getSrc(1)); if (Src1Imm == nullptr) return false; Arith->getDest()->setRematerializable( Src0Var->getRegNum(), Src0Var->getStackOffset() + Src1Imm->getValue()); return true; } bool rematerializeAssign(const Inst *Instr) { // An InstAssign only originates from an inttoptr or ptrtoint instruction, // which never occurs in a MINIMAL build. if (BuildDefs::minimal()) return false; // Check that it's an Assign instruction. if (!llvm::isa<InstAssign>(Instr)) return false; // Check that Src(0) is rematerializable. auto *Src0Var = llvm::dyn_cast<Variable>(Instr->getSrc(0)); if (Src0Var == nullptr || !Src0Var->isRematerializable()) return false; Instr->getDest()->setRematerializable(Src0Var->getRegNum(), Src0Var->getStackOffset()); return true; } bool rematerializeCast(const Inst *Instr) { // An pointer-type bitcast never occurs in a MINIMAL build. if (BuildDefs::minimal()) return false; // Check that it's a Cast instruction with a Bitcast operation. auto *Cast = llvm::dyn_cast<InstCast>(Instr); if (Cast == nullptr || Cast->getCastKind() != InstCast::Bitcast) return false; // Check that Src(0) is rematerializable. auto *Src0Var = llvm::dyn_cast<Variable>(Cast->getSrc(0)); if (Src0Var == nullptr || !Src0Var->isRematerializable()) return false; // Check that Dest and Src(0) have the same type. Variable *Dest = Cast->getDest(); if (Dest->getType() != Src0Var->getType()) return false; Dest->setRematerializable(Src0Var->getRegNum(), Src0Var->getStackOffset()); return true; } } // end of anonymous namespace /// Scan the function to find additional rematerializable variables. This is /// possible when the source operand of an InstAssignment is a rematerializable /// variable, or the same for a pointer-type InstCast::Bitcast, or when an /// InstArithmetic is an add of a rematerializable variable and an immediate. /// Note that InstAssignment instructions and pointer-type InstCast::Bitcast /// instructions generally only come about from the IceConverter's treatment of /// inttoptr, ptrtoint, and bitcast instructions. TODO(stichnot): Consider /// other possibilities, however unlikely, such as InstArithmetic::Sub, or /// commutativity. void Cfg::findRematerializable() { // Scan the instructions in order, and repeat until no new opportunities are // found. It may take more than one iteration because a variable's defining // block may happen to come after a block where it is used, depending on the // CfgNode linearization order. bool FoundNewAssignment; do { FoundNewAssignment = false; for (CfgNode *Node : getNodes()) { // No need to process Phi instructions. for (Inst &Instr : Node->getInsts()) { if (Instr.isDeleted()) continue; Variable *Dest = Instr.getDest(); if (Dest == nullptr || Dest->isRematerializable()) continue; if (rematerializeArithmetic(&Instr) || rematerializeAssign(&Instr) || rematerializeCast(&Instr)) { FoundNewAssignment = true; } } } } while (FoundNewAssignment); } void Cfg::doAddressOpt() { TimerMarker T(TimerStack::TT_doAddressOpt, this); for (CfgNode *Node : Nodes) Node->doAddressOpt(); } namespace { // ShuffleVectorUtils implements helper functions for rematerializing // shufflevector instructions from a sequence of extractelement/insertelement // instructions. It looks for the following pattern: // // %t0 = extractelement A, %n0 // %t1 = extractelement B, %n1 // %t2 = extractelement C, %n2 // ... // %tN = extractelement N, %nN // %d0 = insertelement undef, %t0, 0 // %d1 = insertelement %d0, %t1, 1 // %d2 = insertelement %d1, %t2, 2 // ... // %dest = insertelement %d_N-1, %tN, N // // where N is num_element(typeof(%dest)), and A, B, C, ... N are at most two // distinct variables. namespace ShuffleVectorUtils { // findAllInserts is used when searching for all the insertelements that are // used in a shufflevector operation. This function works recursively, when // invoked with I = i, the function assumes Insts[i] is the last found // insertelement in the chain. The next insertelement insertruction is saved in // Insts[i+1]. bool findAllInserts(Cfg *Func, GlobalContext *Ctx, VariablesMetadata *VM, CfgVector<const Inst *> *Insts, SizeT I = 0) { const bool Verbose = BuildDefs::dump() && Func->isVerbose(IceV_ShufMat); if (I > Insts->size()) { if (Verbose) { Ctx->getStrDump() << "\tToo many inserts.\n"; } return false; } const auto *LastInsert = Insts->at(I); assert(llvm::isa<InstInsertElement>(LastInsert)); if (I == Insts->size() - 1) { // Matching against undef is not really needed because the value in Src(0) // will be totally overwritten. We still enforce it anyways because the // PNaCl toolchain generates the bitcode with it. if (!llvm::isa<ConstantUndef>(LastInsert->getSrc(0))) { if (Verbose) { Ctx->getStrDump() << "\tSrc0 is not undef: " << I << " " << Insts->size(); LastInsert->dump(Func); Ctx->getStrDump() << "\n"; } return false; } // The following loop ensures that the insertelements are sorted. In theory, // we could relax this restriction and allow any order. As long as each // index appears exactly once, this chain is still a candidate for becoming // a shufflevector. The Insts vector is traversed backwards because the // instructions are "enqueued" in reverse order. int32_t ExpectedElement = 0; for (const auto *I : reverse_range(*Insts)) { if (llvm::cast<ConstantInteger32>(I->getSrc(2))->getValue() != ExpectedElement) { return false; } ++ExpectedElement; } return true; } const auto *Src0V = llvm::cast<Variable>(LastInsert->getSrc(0)); const auto *Def = VM->getSingleDefinition(Src0V); // Only optimize if the first operand in // // Dest = insertelement A, B, 10 // // is singly-def'ed. if (Def == nullptr) { if (Verbose) { Ctx->getStrDump() << "\tmulti-def: "; (*Insts)[I]->dump(Func); Ctx->getStrDump() << "\n"; } return false; } // We also require the (single) definition to come from an insertelement // instruction. if (!llvm::isa<InstInsertElement>(Def)) { if (Verbose) { Ctx->getStrDump() << "\tnot insert element: "; Def->dump(Func); Ctx->getStrDump() << "\n"; } return false; } // Everything seems fine, so we save Def in Insts, and delegate the decision // to findAllInserts. (*Insts)[I + 1] = Def; return findAllInserts(Func, Ctx, VM, Insts, I + 1); } // insertsLastElement returns true if Insert is inserting an element in the last // position of a vector. bool insertsLastElement(const Inst &Insert) { const Type DestTy = Insert.getDest()->getType(); assert(isVectorType(DestTy)); const SizeT Elem = llvm::cast<ConstantInteger32>(Insert.getSrc(2))->getValue(); return Elem == typeNumElements(DestTy) - 1; } // findAllExtracts goes over all the insertelement instructions that are // candidates to be replaced by a shufflevector, and searches for all the // definitions of the elements being inserted. If all of the elements are the // result of an extractelement instruction, and all of the extractelements // operate on at most two different sources, than the instructions can be // replaced by a shufflevector. bool findAllExtracts(Cfg *Func, GlobalContext *Ctx, VariablesMetadata *VM, const CfgVector<const Inst *> &Insts, Variable **Src0, Variable **Src1, CfgVector<const Inst *> *Extracts) { const bool Verbose = BuildDefs::dump() && Func->isVerbose(IceV_ShufMat); *Src0 = nullptr; *Src1 = nullptr; assert(Insts.size() > 0); for (SizeT I = 0; I < Insts.size(); ++I) { const auto *Insert = Insts.at(I); const auto *Src1V = llvm::dyn_cast<Variable>(Insert->getSrc(1)); if (Src1V == nullptr) { if (Verbose) { Ctx->getStrDump() << "src(1) is not a variable: "; Insert->dump(Func); Ctx->getStrDump() << "\n"; } return false; } const auto *Def = VM->getSingleDefinition(Src1V); if (Def == nullptr) { if (Verbose) { Ctx->getStrDump() << "multi-def src(1): "; Insert->dump(Func); Ctx->getStrDump() << "\n"; } return false; } if (!llvm::isa<InstExtractElement>(Def)) { if (Verbose) { Ctx->getStrDump() << "not extractelement: "; Def->dump(Func); Ctx->getStrDump() << "\n"; } return false; } auto *Src = llvm::cast<Variable>(Def->getSrc(0)); if (*Src0 == nullptr) { // No sources yet. Save Src to Src0. *Src0 = Src; } else if (*Src1 == nullptr) { // We already have a source, so we might save Src in Src1 -- but only if // Src0 is not Src. if (*Src0 != Src) { *Src1 = Src; } } else if (Src != *Src0 && Src != *Src1) { // More than two sources, so we can't rematerialize the shufflevector // instruction. if (Verbose) { Ctx->getStrDump() << "Can't shuffle more than two sources.\n"; } return false; } (*Extracts)[I] = Def; } // We should have seen at least one source operand. assert(*Src0 != nullptr); // If a second source was not seen, then we just make Src1 = Src0 to simplify // things down stream. This should not matter, as all of the indexes in the // shufflevector instruction will point to Src0. if (*Src1 == nullptr) { *Src1 = *Src0; } return true; } } // end of namespace ShuffleVectorUtils } // end of anonymous namespace void Cfg::materializeVectorShuffles() { const bool Verbose = BuildDefs::dump() && isVerbose(IceV_ShufMat); std::unique_ptr<OstreamLocker> L; if (Verbose) { L.reset(new OstreamLocker(getContext())); getContext()->getStrDump() << "\nShuffle materialization:\n"; } // MaxVectorElements is the maximum number of elements in the vector types // handled by Subzero. We use it to create the Inserts and Extracts vectors // with the appropriate size, thus avoiding resize() calls. const SizeT MaxVectorElements = typeNumElements(IceType_v16i8); CfgVector<const Inst *> Inserts(MaxVectorElements); CfgVector<const Inst *> Extracts(MaxVectorElements); TimerMarker T(TimerStack::TT_materializeVectorShuffles, this); for (CfgNode *Node : Nodes) { for (auto &Instr : Node->getInsts()) { if (!llvm::isa<InstInsertElement>(Instr)) { continue; } if (!ShuffleVectorUtils::insertsLastElement(Instr)) { // To avoid wasting time, we only start the pattern match at the last // insertelement instruction -- and go backwards from there. continue; } if (Verbose) { getContext()->getStrDump() << "\tCandidate: "; Instr.dump(this); getContext()->getStrDump() << "\n"; } Inserts.resize(typeNumElements(Instr.getDest()->getType())); Inserts[0] = &Instr; if (!ShuffleVectorUtils::findAllInserts(this, getContext(), VMetadata.get(), &Inserts)) { // If we fail to find a sequence of insertelements, we stop the // optimization. if (Verbose) { getContext()->getStrDump() << "\tFalse alarm.\n"; } continue; } if (Verbose) { getContext()->getStrDump() << "\tFound the following insertelement: \n"; for (auto *I : reverse_range(Inserts)) { getContext()->getStrDump() << "\t\t"; I->dump(this); getContext()->getStrDump() << "\n"; } } Extracts.resize(Inserts.size()); Variable *Src0; Variable *Src1; if (!ShuffleVectorUtils::findAllExtracts(this, getContext(), VMetadata.get(), Inserts, &Src0, &Src1, &Extracts)) { // If we fail to match the definitions of the insertelements' sources // with extractelement instructions -- or if those instructions operate // on more than two different variables -- we stop the optimization. if (Verbose) { getContext()->getStrDump() << "\tFailed to match extractelements.\n"; } continue; } if (Verbose) { getContext()->getStrDump() << "\tFound the following insert/extract element pairs: \n"; for (SizeT I = 0; I < Inserts.size(); ++I) { const SizeT Pos = Inserts.size() - I - 1; getContext()->getStrDump() << "\t\tInsert : "; Inserts[Pos]->dump(this); getContext()->getStrDump() << "\n\t\tExtract: "; Extracts[Pos]->dump(this); getContext()->getStrDump() << "\n"; } } assert(Src0 != nullptr); assert(Src1 != nullptr); auto *ShuffleVector = InstShuffleVector::create(this, Instr.getDest(), Src0, Src1); assert(ShuffleVector->getSrc(0) == Src0); assert(ShuffleVector->getSrc(1) == Src1); for (SizeT I = 0; I < Extracts.size(); ++I) { const SizeT Pos = Extracts.size() - I - 1; auto *Index = llvm::cast<ConstantInteger32>(Extracts[Pos]->getSrc(1)); if (Src0 == Extracts[Pos]->getSrc(0)) { ShuffleVector->addIndex(Index); } else { ShuffleVector->addIndex(llvm::cast<ConstantInteger32>( Ctx->getConstantInt32(Index->getValue() + Extracts.size()))); } } if (Verbose) { getContext()->getStrDump() << "Created: "; ShuffleVector->dump(this); getContext()->getStrDump() << "\n"; } Instr.setDeleted(); auto &LoweringContext = getTarget()->getContext(); LoweringContext.setInsertPoint(instToIterator(&Instr)); LoweringContext.insert(ShuffleVector); } } } void Cfg::doNopInsertion() { if (!getFlags().getShouldDoNopInsertion()) return; TimerMarker T(TimerStack::TT_doNopInsertion, this); RandomNumberGenerator RNG(getFlags().getRandomSeed(), RPE_NopInsertion, SequenceNumber); for (CfgNode *Node : Nodes) Node->doNopInsertion(RNG); } void Cfg::genCode() { TimerMarker T(TimerStack::TT_genCode, this); for (CfgNode *Node : Nodes) Node->genCode(); } // Compute the stack frame layout. void Cfg::genFrame() { TimerMarker T(TimerStack::TT_genFrame, this); getTarget()->addProlog(Entry); for (CfgNode *Node : Nodes) if (Node->getHasReturn()) getTarget()->addEpilog(Node); } void Cfg::generateLoopInfo() { TimerMarker T(TimerStack::TT_computeLoopNestDepth, this); LoopInfo = ComputeLoopInfo(this); } // This is a lightweight version of live-range-end calculation. Marks the last // use of only those variables whose definition and uses are completely with a // single block. It is a quick single pass and doesn't need to iterate until // convergence. void Cfg::livenessLightweight() { TimerMarker T(TimerStack::TT_livenessLightweight, this); getVMetadata()->init(VMK_Uses); for (CfgNode *Node : Nodes) Node->livenessLightweight(); } void Cfg::liveness(LivenessMode Mode) { TimerMarker T(TimerStack::TT_liveness, this); // Destroying the previous (if any) Liveness information clears the Liveness // allocator TLS pointer. Live = nullptr; Live = Liveness::create(this, Mode); getVMetadata()->init(VMK_Uses); Live->init(); // Initialize with all nodes needing to be processed. BitVector NeedToProcess(Nodes.size(), true); while (NeedToProcess.any()) { // Iterate in reverse topological order to speed up convergence. for (CfgNode *Node : reverse_range(Nodes)) { if (NeedToProcess[Node->getIndex()]) { NeedToProcess[Node->getIndex()] = false; bool Changed = Node->liveness(getLiveness()); if (Changed) { // If the beginning-of-block liveness changed since the last // iteration, mark all in-edges as needing to be processed. for (CfgNode *Pred : Node->getInEdges()) NeedToProcess[Pred->getIndex()] = true; } } } } if (Mode == Liveness_Intervals) { // Reset each variable's live range. for (Variable *Var : Variables) Var->resetLiveRange(); } // Make a final pass over each node to delete dead instructions, collect the // first and last instruction numbers, and add live range segments for that // node. for (CfgNode *Node : Nodes) { InstNumberT FirstInstNum = Inst::NumberSentinel; InstNumberT LastInstNum = Inst::NumberSentinel; for (Inst &I : Node->getPhis()) { I.deleteIfDead(); if (Mode == Liveness_Intervals && !I.isDeleted()) { if (FirstInstNum == Inst::NumberSentinel) FirstInstNum = I.getNumber(); assert(I.getNumber() > LastInstNum); LastInstNum = I.getNumber(); } } for (Inst &I : Node->getInsts()) { I.deleteIfDead(); if (Mode == Liveness_Intervals && !I.isDeleted()) { if (FirstInstNum == Inst::NumberSentinel) FirstInstNum = I.getNumber(); assert(I.getNumber() > LastInstNum); LastInstNum = I.getNumber(); } } if (Mode == Liveness_Intervals) { // Special treatment for live in-args. Their liveness needs to extend // beyond the beginning of the function, otherwise an arg whose only use // is in the first instruction will end up having the trivial live range // [2,2) and will *not* interfere with other arguments. So if the first // instruction of the method is "r=arg1+arg2", both args may be assigned // the same register. This is accomplished by extending the entry block's // instruction range from [2,n) to [1,n) which will transform the // problematic [2,2) live ranges into [1,2). This extension works because // the entry node is guaranteed to have the lowest instruction numbers. if (Node == getEntryNode()) { FirstInstNum = Inst::NumberExtended; // Just in case the entry node somehow contains no instructions... if (LastInstNum == Inst::NumberSentinel) LastInstNum = FirstInstNum; } // If this node somehow contains no instructions, don't bother trying to // add liveness intervals for it, because variables that are live-in and // live-out will have a bogus interval added. if (FirstInstNum != Inst::NumberSentinel) Node->livenessAddIntervals(getLiveness(), FirstInstNum, LastInstNum); } } } // Traverse every Variable of every Inst and verify that it appears within the // Variable's computed live range. bool Cfg::validateLiveness() const { TimerMarker T(TimerStack::TT_validateLiveness, this); bool Valid = true; OstreamLocker L(Ctx); Ostream &Str = Ctx->getStrDump(); for (CfgNode *Node : Nodes) { Inst *FirstInst = nullptr; for (Inst &Instr : Node->getInsts()) { if (Instr.isDeleted()) continue; if (FirstInst == nullptr) FirstInst = &Instr; InstNumberT InstNumber = Instr.getNumber(); if (Variable *Dest = Instr.getDest()) { if (!Dest->getIgnoreLiveness()) { bool Invalid = false; constexpr bool IsDest = true; if (!Dest->getLiveRange().containsValue(InstNumber, IsDest)) Invalid = true; // Check that this instruction actually *begins* Dest's live range, // by checking that Dest is not live in the previous instruction. As // a special exception, we don't check this for the first instruction // of the block, because a Phi temporary may be live at the end of // the previous block, and if it is also assigned in the first // instruction of this block, the adjacent live ranges get merged. if (&Instr != FirstInst && !Instr.isDestRedefined() && Dest->getLiveRange().containsValue(InstNumber - 1, IsDest)) Invalid = true; if (Invalid) { Valid = false; Str << "Liveness error: inst " << Instr.getNumber() << " dest "; Dest->dump(this); Str << " live range " << Dest->getLiveRange() << "\n"; } } } FOREACH_VAR_IN_INST(Var, Instr) { static constexpr bool IsDest = false; if (!Var->getIgnoreLiveness() && !Var->getLiveRange().containsValue(InstNumber, IsDest)) { Valid = false; Str << "Liveness error: inst " << Instr.getNumber() << " var "; Var->dump(this); Str << " live range " << Var->getLiveRange() << "\n"; } } } } return Valid; } void Cfg::contractEmptyNodes() { // If we're decorating the asm output with register liveness info, this // information may become corrupted or incorrect after contracting nodes that // contain only redundant assignments. As such, we disable this pass when // DecorateAsm is specified. This may make the resulting code look more // branchy, but it should have no effect on the register assignments. if (getFlags().getDecorateAsm()) return; for (CfgNode *Node : Nodes) { Node->contractIfEmpty(); } } void Cfg::doBranchOpt() { TimerMarker T(TimerStack::TT_doBranchOpt, this); for (auto I = Nodes.begin(), E = Nodes.end(); I != E; ++I) { auto NextNode = I + 1; (*I)->doBranchOpt(NextNode == E ? nullptr : *NextNode); } } void Cfg::markNodesForSandboxing() { for (const InstJumpTable *JT : JumpTables) for (SizeT I = 0; I < JT->getNumTargets(); ++I) JT->getTarget(I)->setNeedsAlignment(); } // ======================== Dump routines ======================== // // emitTextHeader() is not target-specific (apart from what is abstracted by // the Assembler), so it is defined here rather than in the target lowering // class. void Cfg::emitTextHeader(GlobalString Name, GlobalContext *Ctx, const Assembler *Asm) { if (!BuildDefs::dump()) return; Ostream &Str = Ctx->getStrEmit(); Str << "\t.text\n"; if (getFlags().getFunctionSections()) Str << "\t.section\t.text." << Name << ",\"ax\",%progbits\n"; if (!Asm->getInternal() || getFlags().getDisableInternal()) { Str << "\t.globl\t" << Name << "\n"; Str << "\t.type\t" << Name << ",%function\n"; } Str << "\t" << Asm->getAlignDirective() << " " << Asm->getBundleAlignLog2Bytes() << ",0x"; for (uint8_t I : Asm->getNonExecBundlePadding()) Str.write_hex(I); Str << "\n"; Str << Name << ":\n"; } void Cfg::emitJumpTables() { switch (getFlags().getOutFileType()) { case FT_Elf: case FT_Iasm: { // The emission needs to be delayed until the after the text section so // save the offsets in the global context. for (const InstJumpTable *JumpTable : JumpTables) { Ctx->addJumpTableData(JumpTable->toJumpTableData(getAssembler())); } } break; case FT_Asm: { // Emit the assembly directly so we don't need to hang on to all the names for (const InstJumpTable *JumpTable : JumpTables) getTarget()->emitJumpTable(this, JumpTable); } break; } } void Cfg::emit() { if (!BuildDefs::dump()) return; TimerMarker T(TimerStack::TT_emitAsm, this); if (getFlags().getDecorateAsm()) { renumberInstructions(); getVMetadata()->init(VMK_Uses); liveness(Liveness_Basic); dump("After recomputing liveness for -decorate-asm"); } OstreamLocker L(Ctx); Ostream &Str = Ctx->getStrEmit(); const Assembler *Asm = getAssembler<>(); const bool NeedSandboxing = getFlags().getUseSandboxing(); emitTextHeader(FunctionName, Ctx, Asm); if (getFlags().getDecorateAsm()) { for (Variable *Var : getVariables()) { if (Var->hasKnownStackOffset() && !Var->isRematerializable()) { Str << "\t" << Var->getSymbolicStackOffset() << " = " << Var->getStackOffset() << "\n"; } } } for (CfgNode *Node : Nodes) { if (NeedSandboxing && Node->needsAlignment()) { Str << "\t" << Asm->getAlignDirective() << " " << Asm->getBundleAlignLog2Bytes() << "\n"; } Node->emit(this); } emitJumpTables(); Str << "\n"; } void Cfg::emitIAS() { TimerMarker T(TimerStack::TT_emitAsm, this); // The emitIAS() routines emit into the internal assembler buffer, so there's // no need to lock the streams. const bool NeedSandboxing = getFlags().getUseSandboxing(); for (CfgNode *Node : Nodes) { if (NeedSandboxing && Node->needsAlignment()) getAssembler()->alignCfgNode(); Node->emitIAS(this); } emitJumpTables(); } size_t Cfg::getTotalMemoryMB() const { constexpr size_t _1MB = 1024 * 1024; assert(Allocator != nullptr); assert(CfgAllocatorTraits::current() == Allocator.get()); return Allocator->getTotalMemory() / _1MB; } size_t Cfg::getLivenessMemoryMB() const { constexpr size_t _1MB = 1024 * 1024; if (Live == nullptr) { return 0; } return Live->getAllocator()->getTotalMemory() / _1MB; } // Dumps the IR with an optional introductory message. void Cfg::dump(const char *Message) { if (!BuildDefs::dump()) return; if (!isVerbose()) return; OstreamLocker L(Ctx); Ostream &Str = Ctx->getStrDump(); if (Message[0]) Str << "================ " << Message << " ================\n"; if (isVerbose(IceV_Mem)) { Str << "Memory size = " << getTotalMemoryMB() << " MB\n"; } setCurrentNode(getEntryNode()); // Print function name+args if (isVerbose(IceV_Instructions)) { Str << "define "; if (getInternal() && !getFlags().getDisableInternal()) Str << "internal "; Str << ReturnType << " @" << getFunctionName() << "("; for (SizeT i = 0; i < Args.size(); ++i) { if (i > 0) Str << ", "; Str << Args[i]->getType() << " "; Args[i]->dump(this); } // Append an extra copy of the function name here, in order to print its // size stats but not mess up lit tests. Str << ") { # " << getFunctionNameAndSize() << "\n"; } resetCurrentNode(); if (isVerbose(IceV_Liveness)) { // Print summary info about variables for (Variable *Var : Variables) { Str << "// multiblock="; if (getVMetadata()->isTracked(Var)) Str << getVMetadata()->isMultiBlock(Var); else Str << "?"; Str << " defs="; bool FirstPrint = true; if (VMetadata->getKind() != VMK_Uses) { if (const Inst *FirstDef = VMetadata->getFirstDefinition(Var)) { Str << FirstDef->getNumber(); FirstPrint = false; } } if (VMetadata->getKind() == VMK_All) { for (const Inst *Instr : VMetadata->getLatterDefinitions(Var)) { if (!FirstPrint) Str << ","; Str << Instr->getNumber(); FirstPrint = false; } } Str << " weight=" << Var->getWeight(this) << " "; Var->dump(this); Str << " LIVE=" << Var->getLiveRange() << "\n"; } } // Print each basic block for (CfgNode *Node : Nodes) Node->dump(this); if (isVerbose(IceV_Instructions)) Str << "}\n"; } } // end of namespace Ice
36.324025
80
0.640152
[ "object", "vector", "model", "transform" ]
ce0c0b804d1caa70d443ba4bffce0a192822a5f7
35,509
cpp
C++
localization/ndt_scan_matcher/src/ndt_scan_matcher_core.cpp
goktugyildirim/autoware.universe
b2f90a0952bf37969517f72ccd5a1ea86f253ce5
[ "Apache-2.0" ]
null
null
null
localization/ndt_scan_matcher/src/ndt_scan_matcher_core.cpp
goktugyildirim/autoware.universe
b2f90a0952bf37969517f72ccd5a1ea86f253ce5
[ "Apache-2.0" ]
11
2022-01-24T10:26:37.000Z
2022-03-22T08:19:01.000Z
localization/ndt_scan_matcher/src/ndt_scan_matcher_core.cpp
KeisukeShima/autoware.universe
21d5453dfa2bf75716b8737fb7b58f3b45483e29
[ "Apache-2.0" ]
null
null
null
// Copyright 2015-2019 Autoware Foundation // // 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 "ndt_scan_matcher/ndt_scan_matcher_core.hpp" #include "ndt_scan_matcher/debug.hpp" #include "ndt_scan_matcher/matrix_type.hpp" #include "ndt_scan_matcher/particle.hpp" #include "ndt_scan_matcher/util_func.hpp" #include <tier4_autoware_utils/geometry/geometry.hpp> #include <tier4_autoware_utils/ros/marker_helper.hpp> #include <boost/shared_ptr.hpp> #include <pcl_conversions/pcl_conversions.h> #include <tf2_eigen/tf2_eigen.h> #include <algorithm> #include <cmath> #include <functional> #include <iomanip> #include <thread> tier4_debug_msgs::msg::Float32Stamped makeFloat32Stamped( const builtin_interfaces::msg::Time & stamp, const float data) { using T = tier4_debug_msgs::msg::Float32Stamped; return tier4_debug_msgs::build<T>().stamp(stamp).data(data); } tier4_debug_msgs::msg::Int32Stamped makeInt32Stamped( const builtin_interfaces::msg::Time & stamp, const int32_t data) { using T = tier4_debug_msgs::msg::Int32Stamped; return tier4_debug_msgs::build<T>().stamp(stamp).data(data); } geometry_msgs::msg::TransformStamped identityTransformStamped( const builtin_interfaces::msg::Time & timestamp, const std::string & header_frame_id, const std::string & child_frame_id) { geometry_msgs::msg::TransformStamped transform; transform.header.stamp = timestamp; transform.header.frame_id = header_frame_id; transform.child_frame_id = child_frame_id; transform.transform.rotation = tier4_autoware_utils::createQuaternion(0.0, 0.0, 0.0, 1.0); transform.transform.translation = tier4_autoware_utils::createTranslation(0.0, 0.0, 0.0); return transform; } double norm(const geometry_msgs::msg::Point & p1, const geometry_msgs::msg::Point & p2) { return std::sqrt( std::pow(p1.x - p2.x, 2.0) + std::pow(p1.y - p2.y, 2.0) + std::pow(p1.z - p2.z, 2.0)); } bool isLocalOptimalSolutionOscillation( const std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f>> & result_pose_matrix_array, const float oscillation_threshold, const float inversion_vector_threshold) { bool prev_oscillation = false; int oscillation_cnt = 0; for (size_t i = 2; i < result_pose_matrix_array.size(); ++i) { const Eigen::Vector3f current_pose = result_pose_matrix_array.at(i).block(0, 3, 3, 1); const Eigen::Vector3f prev_pose = result_pose_matrix_array.at(i - 1).block(0, 3, 3, 1); const Eigen::Vector3f prev_prev_pose = result_pose_matrix_array.at(i - 2).block(0, 3, 3, 1); const auto current_vec = (current_pose - prev_pose).normalized(); const auto prev_vec = (prev_pose - prev_prev_pose).normalized(); const bool oscillation = prev_vec.dot(current_vec) < inversion_vector_threshold; if (prev_oscillation && oscillation) { if (oscillation_cnt > oscillation_threshold) { return true; } ++oscillation_cnt; } else { oscillation_cnt = 0; } prev_oscillation = oscillation; } return false; } NDTScanMatcher::NDTScanMatcher() : Node("ndt_scan_matcher"), tf2_buffer_(this->get_clock()), tf2_listener_(tf2_buffer_), tf2_broadcaster_(*this), ndt_implement_type_(NDTImplementType::PCL_GENERIC), base_frame_("base_link"), ndt_base_frame_("ndt_base_link"), map_frame_("map"), converged_param_type_(ConvergedParamType::TRANSFORM_PROBABILITY), converged_param_transform_probability_(4.5), converged_param_nearest_voxel_transformation_likelihood_(2.3), initial_estimate_particles_num_(100), initial_pose_timeout_sec_(1.0), initial_pose_distance_tolerance_m_(10.0), inversion_vector_threshold_(-0.9), oscillation_threshold_(10) { key_value_stdmap_["state"] = "Initializing"; int ndt_implement_type_tmp = this->declare_parameter("ndt_implement_type", 0); ndt_implement_type_ = static_cast<NDTImplementType>(ndt_implement_type_tmp); RCLCPP_INFO(get_logger(), "NDT Implement Type is %d", ndt_implement_type_tmp); try { ndt_ptr_ = getNDT<PointSource, PointTarget>(ndt_implement_type_); } catch (std::exception & e) { RCLCPP_ERROR(get_logger(), "%s", e.what()); return; } if (ndt_implement_type_ == NDTImplementType::OMP) { using T = NormalDistributionsTransformOMP<PointSource, PointTarget>; // FIXME(IshitaTakeshi) Not sure if this is safe std::shared_ptr<T> ndt_omp_ptr = std::dynamic_pointer_cast<T>(ndt_ptr_); int search_method = static_cast<int>(omp_params_.search_method); search_method = this->declare_parameter("omp_neighborhood_search_method", search_method); omp_params_.search_method = static_cast<pclomp::NeighborSearchMethod>(search_method); // TODO(Tier IV): check search_method is valid value. ndt_omp_ptr->setNeighborhoodSearchMethod(omp_params_.search_method); omp_params_.num_threads = this->declare_parameter("omp_num_threads", omp_params_.num_threads); omp_params_.num_threads = std::max(omp_params_.num_threads, 1); ndt_omp_ptr->setNumThreads(omp_params_.num_threads); ndt_ptr_ = ndt_omp_ptr; } int points_queue_size = this->declare_parameter("input_sensor_points_queue_size", 0); points_queue_size = std::max(points_queue_size, 0); RCLCPP_INFO(get_logger(), "points_queue_size: %d", points_queue_size); base_frame_ = this->declare_parameter("base_frame", base_frame_); RCLCPP_INFO(get_logger(), "base_frame_id: %s", base_frame_.c_str()); ndt_base_frame_ = this->declare_parameter("ndt_base_frame", ndt_base_frame_); RCLCPP_INFO(get_logger(), "ndt_base_frame_id: %s", ndt_base_frame_.c_str()); double trans_epsilon = ndt_ptr_->getTransformationEpsilon(); double step_size = ndt_ptr_->getStepSize(); double resolution = ndt_ptr_->getResolution(); int max_iterations = ndt_ptr_->getMaximumIterations(); trans_epsilon = this->declare_parameter("trans_epsilon", trans_epsilon); step_size = this->declare_parameter("step_size", step_size); resolution = this->declare_parameter("resolution", resolution); max_iterations = this->declare_parameter("max_iterations", max_iterations); ndt_ptr_->setTransformationEpsilon(trans_epsilon); ndt_ptr_->setStepSize(step_size); ndt_ptr_->setResolution(resolution); ndt_ptr_->setMaximumIterations(max_iterations); RCLCPP_INFO( get_logger(), "trans_epsilon: %lf, step_size: %lf, resolution: %lf, max_iterations: %d", trans_epsilon, step_size, resolution, max_iterations); int converged_param_type_tmp = this->declare_parameter("converged_param_type", 0); converged_param_type_ = static_cast<ConvergedParamType>(converged_param_type_tmp); if ( ndt_implement_type_ != NDTImplementType::OMP && converged_param_type_ == ConvergedParamType::NEAREST_VOXEL_TRANSFORMATION_LIKELIHOOD) { RCLCPP_ERROR( get_logger(), "ConvergedParamType::NEAREST_VOXEL_TRANSFORMATION_LIKELIHOOD is only available when " "NDTImplementType::OMP is selected."); return; } converged_param_transform_probability_ = this->declare_parameter( "converged_param_transform_probability", converged_param_transform_probability_); converged_param_nearest_voxel_transformation_likelihood_ = this->declare_parameter( "converged_param_nearest_voxel_transformation_likelihood", converged_param_nearest_voxel_transformation_likelihood_); initial_estimate_particles_num_ = this->declare_parameter("initial_estimate_particles_num", initial_estimate_particles_num_); initial_pose_timeout_sec_ = this->declare_parameter("initial_pose_timeout_sec", initial_pose_timeout_sec_); initial_pose_distance_tolerance_m_ = this->declare_parameter( "initial_pose_distance_tolerance_m", initial_pose_distance_tolerance_m_); std::vector<double> output_pose_covariance = this->declare_parameter<std::vector<double>>("output_pose_covariance"); for (std::size_t i = 0; i < output_pose_covariance.size(); ++i) { output_pose_covariance_[i] = output_pose_covariance[i]; } rclcpp::CallbackGroup::SharedPtr initial_pose_callback_group; initial_pose_callback_group = this->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); rclcpp::CallbackGroup::SharedPtr main_callback_group; main_callback_group = this->create_callback_group(rclcpp::CallbackGroupType::MutuallyExclusive); auto initial_pose_sub_opt = rclcpp::SubscriptionOptions(); initial_pose_sub_opt.callback_group = initial_pose_callback_group; auto main_sub_opt = rclcpp::SubscriptionOptions(); main_sub_opt.callback_group = main_callback_group; initial_pose_sub_ = this->create_subscription<geometry_msgs::msg::PoseWithCovarianceStamped>( "ekf_pose_with_covariance", 100, std::bind(&NDTScanMatcher::callbackInitialPose, this, std::placeholders::_1), initial_pose_sub_opt); map_points_sub_ = this->create_subscription<sensor_msgs::msg::PointCloud2>( "pointcloud_map", rclcpp::QoS{1}.transient_local(), std::bind(&NDTScanMatcher::callbackMapPoints, this, std::placeholders::_1), main_sub_opt); sensor_points_sub_ = this->create_subscription<sensor_msgs::msg::PointCloud2>( "points_raw", rclcpp::SensorDataQoS().keep_last(points_queue_size), std::bind(&NDTScanMatcher::callbackSensorPoints, this, std::placeholders::_1), main_sub_opt); sensor_aligned_pose_pub_ = this->create_publisher<sensor_msgs::msg::PointCloud2>("points_aligned", 10); ndt_pose_pub_ = this->create_publisher<geometry_msgs::msg::PoseStamped>("ndt_pose", 10); ndt_pose_with_covariance_pub_ = this->create_publisher<geometry_msgs::msg::PoseWithCovarianceStamped>( "ndt_pose_with_covariance", 10); initial_pose_with_covariance_pub_ = this->create_publisher<geometry_msgs::msg::PoseWithCovarianceStamped>( "initial_pose_with_covariance", 10); exe_time_pub_ = this->create_publisher<tier4_debug_msgs::msg::Float32Stamped>("exe_time_ms", 10); transform_probability_pub_ = this->create_publisher<tier4_debug_msgs::msg::Float32Stamped>("transform_probability", 10); nearest_voxel_transformation_likelihood_pub_ = this->create_publisher<tier4_debug_msgs::msg::Float32Stamped>( "nearest_voxel_transformation_likelihood", 10); iteration_num_pub_ = this->create_publisher<tier4_debug_msgs::msg::Int32Stamped>("iteration_num", 10); initial_to_result_distance_pub_ = this->create_publisher<tier4_debug_msgs::msg::Float32Stamped>("initial_to_result_distance", 10); initial_to_result_distance_old_pub_ = this->create_publisher<tier4_debug_msgs::msg::Float32Stamped>( "initial_to_result_distance_old", 10); initial_to_result_distance_new_pub_ = this->create_publisher<tier4_debug_msgs::msg::Float32Stamped>( "initial_to_result_distance_new", 10); ndt_marker_pub_ = this->create_publisher<visualization_msgs::msg::MarkerArray>("ndt_marker", 10); ndt_monte_carlo_initial_pose_marker_pub_ = this->create_publisher<visualization_msgs::msg::MarkerArray>( "monte_carlo_initial_pose_marker", 10); diagnostics_pub_ = this->create_publisher<diagnostic_msgs::msg::DiagnosticArray>("/diagnostics", 10); service_ = this->create_service<tier4_localization_msgs::srv::PoseWithCovarianceStamped>( "ndt_align_srv", std::bind(&NDTScanMatcher::serviceNDTAlign, this, std::placeholders::_1, std::placeholders::_2), rclcpp::ServicesQoS().get_rmw_qos_profile(), main_callback_group); diagnostic_thread_ = std::thread(&NDTScanMatcher::timerDiagnostic, this); diagnostic_thread_.detach(); } void NDTScanMatcher::timerDiagnostic() { rclcpp::Rate rate(100); while (rclcpp::ok()) { diagnostic_msgs::msg::DiagnosticStatus diag_status_msg; diag_status_msg.name = "ndt_scan_matcher"; diag_status_msg.hardware_id = ""; for (const auto & key_value : key_value_stdmap_) { diagnostic_msgs::msg::KeyValue key_value_msg; key_value_msg.key = key_value.first; key_value_msg.value = key_value.second; diag_status_msg.values.push_back(key_value_msg); } diag_status_msg.level = diagnostic_msgs::msg::DiagnosticStatus::OK; diag_status_msg.message = ""; if (key_value_stdmap_.count("state") && key_value_stdmap_["state"] == "Initializing") { diag_status_msg.level = diagnostic_msgs::msg::DiagnosticStatus::WARN; diag_status_msg.message += "Initializing State. "; } if ( key_value_stdmap_.count("skipping_publish_num") && std::stoi(key_value_stdmap_["skipping_publish_num"]) > 1) { diag_status_msg.level = diagnostic_msgs::msg::DiagnosticStatus::WARN; diag_status_msg.message += "skipping_publish_num > 1. "; } if ( key_value_stdmap_.count("skipping_publish_num") && std::stoi(key_value_stdmap_["skipping_publish_num"]) >= 5) { diag_status_msg.level = diagnostic_msgs::msg::DiagnosticStatus::ERROR; diag_status_msg.message += "skipping_publish_num exceed limit. "; } // Ignore local optimal solution if ( key_value_stdmap_.count("is_local_optimal_solution_oscillation") && std::stoi(key_value_stdmap_["is_local_optimal_solution_oscillation"])) { diag_status_msg.level = diagnostic_msgs::msg::DiagnosticStatus::OK; diag_status_msg.message = "local optimal solution oscillation occurred"; } diagnostic_msgs::msg::DiagnosticArray diag_msg; diag_msg.header.stamp = this->now(); diag_msg.status.push_back(diag_status_msg); diagnostics_pub_->publish(diag_msg); rate.sleep(); } } void NDTScanMatcher::serviceNDTAlign( const tier4_localization_msgs::srv::PoseWithCovarianceStamped::Request::SharedPtr req, tier4_localization_msgs::srv::PoseWithCovarianceStamped::Response::SharedPtr res) { // get TF from pose_frame to map_frame auto TF_pose_to_map_ptr = std::make_shared<geometry_msgs::msg::TransformStamped>(); getTransform(map_frame_, req->pose_with_covariance.header.frame_id, TF_pose_to_map_ptr); // transform pose_frame to map_frame const auto mapTF_initial_pose_msg = transform(req->pose_with_covariance, *TF_pose_to_map_ptr); if (ndt_ptr_->getInputTarget() == nullptr) { res->success = false; res->seq = req->seq; RCLCPP_WARN(get_logger(), "No InputTarget"); return; } if (ndt_ptr_->getInputSource() == nullptr) { res->success = false; res->seq = req->seq; RCLCPP_WARN(get_logger(), "No InputSource"); return; } // mutex Map std::lock_guard<std::mutex> lock(ndt_map_mtx_); key_value_stdmap_["state"] = "Aligning"; res->pose_with_covariance = alignUsingMonteCarlo(ndt_ptr_, mapTF_initial_pose_msg); key_value_stdmap_["state"] = "Sleeping"; res->success = true; res->seq = req->seq; res->pose_with_covariance.pose.covariance = req->pose_with_covariance.pose.covariance; } void NDTScanMatcher::callbackInitialPose( const geometry_msgs::msg::PoseWithCovarianceStamped::ConstSharedPtr initial_pose_msg_ptr) { // lock mutex for initial pose std::lock_guard<std::mutex> initial_pose_array_lock(initial_pose_array_mtx_); // if rosbag restart, clear buffer if (!initial_pose_msg_ptr_array_.empty()) { const builtin_interfaces::msg::Time & t_front = initial_pose_msg_ptr_array_.front()->header.stamp; const builtin_interfaces::msg::Time & t_msg = initial_pose_msg_ptr->header.stamp; if (t_front.sec > t_msg.sec || (t_front.sec == t_msg.sec && t_front.nanosec > t_msg.nanosec)) { initial_pose_msg_ptr_array_.clear(); } } if (initial_pose_msg_ptr->header.frame_id == map_frame_) { initial_pose_msg_ptr_array_.push_back(initial_pose_msg_ptr); } else { // get TF from pose_frame to map_frame auto TF_pose_to_map_ptr = std::make_shared<geometry_msgs::msg::TransformStamped>(); getTransform(map_frame_, initial_pose_msg_ptr->header.frame_id, TF_pose_to_map_ptr); // transform pose_frame to map_frame auto mapTF_initial_pose_msg_ptr = std::make_shared<geometry_msgs::msg::PoseWithCovarianceStamped>(); // mapTF_initial_pose_msg_ptr->header.stamp = initial_pose_msg_ptr->header.stamp; *mapTF_initial_pose_msg_ptr = transform(*initial_pose_msg_ptr, *TF_pose_to_map_ptr); initial_pose_msg_ptr_array_.push_back(mapTF_initial_pose_msg_ptr); } } void NDTScanMatcher::callbackMapPoints( sensor_msgs::msg::PointCloud2::ConstSharedPtr map_points_msg_ptr) { const auto trans_epsilon = ndt_ptr_->getTransformationEpsilon(); const auto step_size = ndt_ptr_->getStepSize(); const auto resolution = ndt_ptr_->getResolution(); const auto max_iterations = ndt_ptr_->getMaximumIterations(); using NDTBase = NormalDistributionsTransformBase<PointSource, PointTarget>; std::shared_ptr<NDTBase> new_ndt_ptr_ = getNDT<PointSource, PointTarget>(ndt_implement_type_); if (ndt_implement_type_ == NDTImplementType::OMP) { using T = NormalDistributionsTransformOMP<PointSource, PointTarget>; // FIXME(IshitaTakeshi) Not sure if this is safe std::shared_ptr<T> ndt_omp_ptr = std::dynamic_pointer_cast<T>(ndt_ptr_); ndt_omp_ptr->setNeighborhoodSearchMethod(omp_params_.search_method); ndt_omp_ptr->setNumThreads(omp_params_.num_threads); new_ndt_ptr_ = ndt_omp_ptr; } new_ndt_ptr_->setTransformationEpsilon(trans_epsilon); new_ndt_ptr_->setStepSize(step_size); new_ndt_ptr_->setResolution(resolution); new_ndt_ptr_->setMaximumIterations(max_iterations); boost::shared_ptr<pcl::PointCloud<PointTarget>> map_points_ptr(new pcl::PointCloud<PointTarget>); pcl::fromROSMsg(*map_points_msg_ptr, *map_points_ptr); new_ndt_ptr_->setInputTarget(map_points_ptr); // create Thread // detach auto output_cloud = std::make_shared<pcl::PointCloud<PointSource>>(); new_ndt_ptr_->align(*output_cloud, Eigen::Matrix4f::Identity()); // swap ndt_map_mtx_.lock(); ndt_ptr_ = new_ndt_ptr_; ndt_map_mtx_.unlock(); } void NDTScanMatcher::callbackSensorPoints( sensor_msgs::msg::PointCloud2::ConstSharedPtr sensor_points_sensorTF_msg_ptr) { const auto exe_start_time = std::chrono::system_clock::now(); // mutex Map std::lock_guard<std::mutex> lock(ndt_map_mtx_); const std::string & sensor_frame = sensor_points_sensorTF_msg_ptr->header.frame_id; const rclcpp::Time sensor_ros_time = sensor_points_sensorTF_msg_ptr->header.stamp; boost::shared_ptr<pcl::PointCloud<PointSource>> sensor_points_sensorTF_ptr( new pcl::PointCloud<PointSource>); pcl::fromROSMsg(*sensor_points_sensorTF_msg_ptr, *sensor_points_sensorTF_ptr); // get TF base to sensor auto TF_base_to_sensor_ptr = std::make_shared<geometry_msgs::msg::TransformStamped>(); getTransform(base_frame_, sensor_frame, TF_base_to_sensor_ptr); const Eigen::Affine3d base_to_sensor_affine = tf2::transformToEigen(*TF_base_to_sensor_ptr); const Eigen::Matrix4f base_to_sensor_matrix = base_to_sensor_affine.matrix().cast<float>(); boost::shared_ptr<pcl::PointCloud<PointSource>> sensor_points_baselinkTF_ptr( new pcl::PointCloud<PointSource>); pcl::transformPointCloud( *sensor_points_sensorTF_ptr, *sensor_points_baselinkTF_ptr, base_to_sensor_matrix); ndt_ptr_->setInputSource(sensor_points_baselinkTF_ptr); // start of critical section for initial_pose_msg_ptr_array_ std::unique_lock<std::mutex> initial_pose_array_lock(initial_pose_array_mtx_); // check if (initial_pose_msg_ptr_array_.size() <= 1) { RCLCPP_WARN_STREAM_THROTTLE(this->get_logger(), *this->get_clock(), 1, "No Pose!"); return; } // searchNNPose using timestamp auto initial_pose_old_msg_ptr = std::make_shared<geometry_msgs::msg::PoseWithCovarianceStamped>(); auto initial_pose_new_msg_ptr = std::make_shared<geometry_msgs::msg::PoseWithCovarianceStamped>(); getNearestTimeStampPose( initial_pose_msg_ptr_array_, sensor_ros_time, initial_pose_old_msg_ptr, initial_pose_new_msg_ptr); popOldPose(initial_pose_msg_ptr_array_, sensor_ros_time); // check the time stamp bool valid_old_timestamp = validateTimeStampDifference( initial_pose_old_msg_ptr->header.stamp, sensor_ros_time, initial_pose_timeout_sec_); bool valid_new_timestamp = validateTimeStampDifference( initial_pose_new_msg_ptr->header.stamp, sensor_ros_time, initial_pose_timeout_sec_); // check the position jumping (ex. immediately after the initial pose estimation) bool valid_new_to_old_distance = validatePositionDifference( initial_pose_old_msg_ptr->pose.pose.position, initial_pose_new_msg_ptr->pose.pose.position, initial_pose_distance_tolerance_m_); // must all validations are true if (!(valid_old_timestamp && valid_new_timestamp && valid_new_to_old_distance)) { RCLCPP_WARN(get_logger(), "Validation error."); return; } const auto initial_pose_msg = interpolatePose(*initial_pose_old_msg_ptr, *initial_pose_new_msg_ptr, sensor_ros_time); // enf of critical section for initial_pose_msg_ptr_array_ initial_pose_array_lock.unlock(); geometry_msgs::msg::PoseWithCovarianceStamped initial_pose_cov_msg; initial_pose_cov_msg.header = initial_pose_msg.header; initial_pose_cov_msg.pose.pose = initial_pose_msg.pose; if (ndt_ptr_->getInputTarget() == nullptr) { RCLCPP_WARN_STREAM_THROTTLE(this->get_logger(), *this->get_clock(), 1, "No MAP!"); return; } // align const Eigen::Affine3d initial_pose_affine = fromRosPoseToEigen(initial_pose_cov_msg.pose.pose); const Eigen::Matrix4f initial_pose_matrix = initial_pose_affine.matrix().cast<float>(); auto output_cloud = std::make_shared<pcl::PointCloud<PointSource>>(); key_value_stdmap_["state"] = "Aligning"; ndt_ptr_->align(*output_cloud, initial_pose_matrix); key_value_stdmap_["state"] = "Sleeping"; const Eigen::Matrix4f result_pose_matrix = ndt_ptr_->getFinalTransformation(); Eigen::Affine3d result_pose_affine; result_pose_affine.matrix() = result_pose_matrix.cast<double>(); const geometry_msgs::msg::Pose result_pose_msg = tf2::toMsg(result_pose_affine); const std::vector<Eigen::Matrix4f, Eigen::aligned_allocator<Eigen::Matrix4f>> result_pose_matrix_array = ndt_ptr_->getFinalTransformationArray(); std::vector<geometry_msgs::msg::Pose> result_pose_msg_array; for (const auto & pose_matrix : result_pose_matrix_array) { Eigen::Affine3d pose_affine; pose_affine.matrix() = pose_matrix.cast<double>(); const geometry_msgs::msg::Pose pose_msg = tf2::toMsg(pose_affine); result_pose_msg_array.push_back(pose_msg); } const auto exe_end_time = std::chrono::system_clock::now(); const double exe_time = std::chrono::duration_cast<std::chrono::microseconds>(exe_end_time - exe_start_time).count() / 1000.0; const float transform_probability = ndt_ptr_->getTransformationProbability(); const float nearest_voxel_transformation_likelihood = ndt_ptr_->getNearestVoxelTransformationLikelihood(); const int iteration_num = ndt_ptr_->getFinalNumIteration(); /***************************************************************************** The reason the add 2 to the ndt_ptr_->getMaximumIterations() is that there are bugs in implementation of ndt. 1. gradient descent method ends when the iteration is greater than max_iteration if it does not converge (be careful it's 'greater than' instead of 'greater equal than'.) https://github.com/tier4/autoware.iv/blob/2323e5baa0b680d43a9219f5fb3b7a11dd9edc82/localization/pose_estimator/ndt_scan_matcher/ndt_omp/include/ndt_omp/ndt_omp_impl.hpp#L212 2. iterate iteration count when end of gradient descent function. https://github.com/tier4/autoware.iv/blob/2323e5baa0b680d43a9219f5fb3b7a11dd9edc82/localization/pose_estimator/ndt_scan_matcher/ndt_omp/include/ndt_omp/ndt_omp_impl.hpp#L217 These bugs are now resolved in original pcl implementation. https://github.com/PointCloudLibrary/pcl/blob/424c1c6a0ca97d94ca63e5daff4b183a4db8aae4/registration/include/pcl/registration/impl/ndt.hpp#L73-L180 *****************************************************************************/ bool is_ok_iteration_num = iteration_num < ndt_ptr_->getMaximumIterations() + 2; if (!is_ok_iteration_num) { RCLCPP_WARN( get_logger(), "The number of iterations has reached its upper limit. The number of iterations: %d, Limit: " "%d", iteration_num, ndt_ptr_->getMaximumIterations() + 2); } bool is_local_optimal_solution_oscillation = false; if (!is_ok_iteration_num) { is_local_optimal_solution_oscillation = isLocalOptimalSolutionOscillation( result_pose_matrix_array, oscillation_threshold_, inversion_vector_threshold_); } bool is_ok_converged_param = false; if (converged_param_type_ == ConvergedParamType::TRANSFORM_PROBABILITY) { is_ok_converged_param = transform_probability > converged_param_transform_probability_; if (!is_ok_converged_param) { RCLCPP_WARN( get_logger(), "Transform Probability is below the threshold. Score: %lf, Threshold: %lf", transform_probability, converged_param_transform_probability_); } } else if (converged_param_type_ == ConvergedParamType::NEAREST_VOXEL_TRANSFORMATION_LIKELIHOOD) { is_ok_converged_param = nearest_voxel_transformation_likelihood > converged_param_nearest_voxel_transformation_likelihood_; if (!is_ok_converged_param) { RCLCPP_WARN( get_logger(), "Nearest Voxel Transform Probability is below the threshold. Score: %lf, Threshold: %lf", nearest_voxel_transformation_likelihood, converged_param_nearest_voxel_transformation_likelihood_); } } else { is_ok_converged_param = false; RCLCPP_ERROR_STREAM_THROTTLE( this->get_logger(), *this->get_clock(), 1, "Unknown converged param type."); } bool is_converged = false; static size_t skipping_publish_num = 0; if (is_ok_iteration_num && is_ok_converged_param) { is_converged = true; skipping_publish_num = 0; } else { is_converged = false; ++skipping_publish_num; RCLCPP_WARN(get_logger(), "Not Converged"); } // publish geometry_msgs::msg::PoseStamped result_pose_stamped_msg; result_pose_stamped_msg.header.stamp = sensor_ros_time; result_pose_stamped_msg.header.frame_id = map_frame_; result_pose_stamped_msg.pose = result_pose_msg; geometry_msgs::msg::PoseWithCovarianceStamped result_pose_with_cov_msg; result_pose_with_cov_msg.header.stamp = sensor_ros_time; result_pose_with_cov_msg.header.frame_id = map_frame_; result_pose_with_cov_msg.pose.pose = result_pose_msg; result_pose_with_cov_msg.pose.covariance = output_pose_covariance_; if (is_converged) { ndt_pose_pub_->publish(result_pose_stamped_msg); ndt_pose_with_covariance_pub_->publish(result_pose_with_cov_msg); } publishTF(ndt_base_frame_, result_pose_stamped_msg); auto sensor_points_mapTF_ptr = std::make_shared<pcl::PointCloud<PointSource>>(); pcl::transformPointCloud( *sensor_points_baselinkTF_ptr, *sensor_points_mapTF_ptr, result_pose_matrix); sensor_msgs::msg::PointCloud2 sensor_points_mapTF_msg; pcl::toROSMsg(*sensor_points_mapTF_ptr, sensor_points_mapTF_msg); sensor_points_mapTF_msg.header.stamp = sensor_ros_time; sensor_points_mapTF_msg.header.frame_id = map_frame_; sensor_aligned_pose_pub_->publish(sensor_points_mapTF_msg); initial_pose_with_covariance_pub_->publish(initial_pose_cov_msg); visualization_msgs::msg::MarkerArray marker_array; visualization_msgs::msg::Marker marker; marker.header.stamp = sensor_ros_time; marker.header.frame_id = map_frame_; marker.type = visualization_msgs::msg::Marker::ARROW; marker.action = visualization_msgs::msg::Marker::ADD; marker.scale = tier4_autoware_utils::createMarkerScale(0.3, 0.1, 0.1); int i = 0; marker.ns = "result_pose_matrix_array"; marker.action = visualization_msgs::msg::Marker::ADD; for (const auto & pose_msg : result_pose_msg_array) { marker.id = i++; marker.pose = pose_msg; marker.color = ExchangeColorCrc((1.0 * i) / 15.0); marker_array.markers.push_back(marker); } // TODO(Tier IV): delete old marker for (; i < ndt_ptr_->getMaximumIterations() + 2;) { marker.id = i++; marker.pose = geometry_msgs::msg::Pose(); marker.color = ExchangeColorCrc(0); marker_array.markers.push_back(marker); } ndt_marker_pub_->publish(marker_array); exe_time_pub_->publish(makeFloat32Stamped(sensor_ros_time, exe_time)); transform_probability_pub_->publish(makeFloat32Stamped(sensor_ros_time, transform_probability)); nearest_voxel_transformation_likelihood_pub_->publish( makeFloat32Stamped(sensor_ros_time, nearest_voxel_transformation_likelihood)); iteration_num_pub_->publish(makeInt32Stamped(sensor_ros_time, iteration_num)); const float initial_to_result_distance = norm(initial_pose_cov_msg.pose.pose.position, result_pose_with_cov_msg.pose.pose.position); initial_to_result_distance_pub_->publish( makeFloat32Stamped(sensor_ros_time, initial_to_result_distance)); const float initial_to_result_distance_old = norm(initial_pose_old_msg_ptr->pose.pose.position, result_pose_with_cov_msg.pose.pose.position); initial_to_result_distance_old_pub_->publish( makeFloat32Stamped(sensor_ros_time, initial_to_result_distance_old)); const float initial_to_result_distance_new = norm(initial_pose_new_msg_ptr->pose.pose.position, result_pose_with_cov_msg.pose.pose.position); initial_to_result_distance_new_pub_->publish( makeFloat32Stamped(sensor_ros_time, initial_to_result_distance_new)); key_value_stdmap_["transform_probability"] = std::to_string(transform_probability); key_value_stdmap_["nearest_voxel_transformation_likelihood"] = std::to_string(nearest_voxel_transformation_likelihood); key_value_stdmap_["iteration_num"] = std::to_string(iteration_num); key_value_stdmap_["skipping_publish_num"] = std::to_string(skipping_publish_num); if (is_local_optimal_solution_oscillation) { key_value_stdmap_["is_local_optimal_solution_oscillation"] = "1"; } else { key_value_stdmap_["is_local_optimal_solution_oscillation"] = "0"; } } geometry_msgs::msg::PoseWithCovarianceStamped NDTScanMatcher::alignUsingMonteCarlo( const std::shared_ptr<NormalDistributionsTransformBase<PointSource, PointTarget>> & ndt_ptr, const geometry_msgs::msg::PoseWithCovarianceStamped & initial_pose_with_cov) { if (ndt_ptr->getInputTarget() == nullptr || ndt_ptr->getInputSource() == nullptr) { RCLCPP_WARN(get_logger(), "No Map or Sensor PointCloud"); return geometry_msgs::msg::PoseWithCovarianceStamped(); } // generateParticle const auto initial_poses = createRandomPoseArray(initial_pose_with_cov, initial_estimate_particles_num_); std::vector<Particle> particle_array; auto output_cloud = std::make_shared<pcl::PointCloud<PointSource>>(); for (unsigned int i = 0; i < initial_poses.size(); i++) { const auto & initial_pose = initial_poses[i]; const Eigen::Affine3d initial_pose_affine = fromRosPoseToEigen(initial_pose); const Eigen::Matrix4f initial_pose_matrix = initial_pose_affine.matrix().cast<float>(); ndt_ptr->align(*output_cloud, initial_pose_matrix); const Eigen::Matrix4f result_pose_matrix = ndt_ptr->getFinalTransformation(); Eigen::Affine3d result_pose_affine; result_pose_affine.matrix() = result_pose_matrix.cast<double>(); const geometry_msgs::msg::Pose result_pose = tf2::toMsg(result_pose_affine); const auto transform_probability = ndt_ptr->getTransformationProbability(); const auto num_iteration = ndt_ptr->getFinalNumIteration(); Particle particle(initial_pose, result_pose, transform_probability, num_iteration); particle_array.push_back(particle); const auto marker_array = makeDebugMarkers( this->now(), map_frame_, tier4_autoware_utils::createMarkerScale(0.3, 0.1, 0.1), particle, i); ndt_monte_carlo_initial_pose_marker_pub_->publish(marker_array); auto sensor_points_mapTF_ptr = std::make_shared<pcl::PointCloud<PointSource>>(); const auto sensor_points_baselinkTF_ptr = ndt_ptr->getInputSource(); pcl::transformPointCloud( *sensor_points_baselinkTF_ptr, *sensor_points_mapTF_ptr, result_pose_matrix); sensor_msgs::msg::PointCloud2 sensor_points_mapTF_msg; pcl::toROSMsg(*sensor_points_mapTF_ptr, sensor_points_mapTF_msg); sensor_points_mapTF_msg.header.stamp = initial_pose_with_cov.header.stamp; sensor_points_mapTF_msg.header.frame_id = map_frame_; sensor_aligned_pose_pub_->publish(sensor_points_mapTF_msg); } auto best_particle_ptr = std::max_element( std::begin(particle_array), std::end(particle_array), [](const Particle & lhs, const Particle & rhs) { return lhs.score < rhs.score; }); geometry_msgs::msg::PoseWithCovarianceStamped result_pose_with_cov_msg; result_pose_with_cov_msg.header.frame_id = map_frame_; result_pose_with_cov_msg.pose.pose = best_particle_ptr->result_pose; // ndt_pose_with_covariance_pub_->publish(result_pose_with_cov_msg); return result_pose_with_cov_msg; } void NDTScanMatcher::publishTF( const std::string & child_frame_id, const geometry_msgs::msg::PoseStamped & pose_msg) { tf2_broadcaster_.sendTransform(tier4_autoware_utils::pose2transform(pose_msg, child_frame_id)); } bool NDTScanMatcher::getTransform( const std::string & target_frame, const std::string & source_frame, const geometry_msgs::msg::TransformStamped::SharedPtr & transform_stamped_ptr) { const geometry_msgs::msg::TransformStamped identity = identityTransformStamped(this->now(), target_frame, source_frame); if (target_frame == source_frame) { *transform_stamped_ptr = identity; return true; } try { *transform_stamped_ptr = tf2_buffer_.lookupTransform(target_frame, source_frame, tf2::TimePointZero); } catch (tf2::TransformException & ex) { RCLCPP_WARN(get_logger(), "%s", ex.what()); RCLCPP_ERROR( get_logger(), "Please publish TF %s to %s", target_frame.c_str(), source_frame.c_str()); *transform_stamped_ptr = identity; return false; } return true; } bool NDTScanMatcher::validateTimeStampDifference( const rclcpp::Time & target_time, const rclcpp::Time & reference_time, const double time_tolerance_sec) { const double dt = std::abs((target_time - reference_time).seconds()); if (dt > time_tolerance_sec) { RCLCPP_WARN( get_logger(), "Validation error. The reference time is %lf[sec], but the target time is %lf[sec]. The " "difference is %lf[sec] (the tolerance is %lf[sec]).", reference_time.seconds(), target_time.seconds(), dt, time_tolerance_sec); return false; } return true; } bool NDTScanMatcher::validatePositionDifference( const geometry_msgs::msg::Point & target_point, const geometry_msgs::msg::Point & reference_point, const double distance_tolerance_m_) { double distance = norm(target_point, reference_point); if (distance > distance_tolerance_m_) { RCLCPP_WARN( get_logger(), "Validation error. The distance from reference position to target position is %lf[m] (the " "tolerance is %lf[m]).", distance, distance_tolerance_m_); return false; } return true; }
43.946782
178
0.766848
[ "geometry", "vector", "transform" ]
ce132a2a7c5e906667dbf76a188c40e947465c46
1,877
hpp
C++
include/caffe/layers/mapping_by_similarity_layer.hpp
goodluckcwl/custom-caffe
aa5345b9d659622a8efbb89d00282389ef0db666
[ "BSD-2-Clause" ]
2
2019-05-27T13:03:21.000Z
2021-09-07T03:11:21.000Z
include/caffe/layers/mapping_by_similarity_layer.hpp
goodluckcwl/custom-caffe
aa5345b9d659622a8efbb89d00282389ef0db666
[ "BSD-2-Clause" ]
1
2019-03-08T01:36:50.000Z
2019-03-13T05:09:05.000Z
include/caffe/layers/mapping_by_similarity_layer.hpp
goodluckcwl/custom-caffe
aa5345b9d659622a8efbb89d00282389ef0db666
[ "BSD-2-Clause" ]
5
2018-07-26T15:29:24.000Z
2020-04-02T06:27:20.000Z
#ifndef CAFFE_MAPPING_BY_SIMILARITY_LAYER_HPP_ #define CAFFE_MAPPING_BY_SIMILARITY_LAYER_HPP_ #include <vector> #include "caffe/blob.hpp" #include "caffe/layer.hpp" #include "caffe/proto/caffe.pb.h" namespace caffe { /** * @brief MappingBySimilarity @f$ y_1 = (x_1 + (1-\alpha)*x_2)/(2-\alpha), * y_2 = (x_2 + (1-\alpha)*x_1)/(2-\alpha) @f$. * */ template <typename Dtype> class MappingBySimilarityLayer : public Layer<Dtype> { public: explicit MappingBySimilarityLayer(const LayerParameter& param) : Layer<Dtype>(param) {} virtual void LayerSetUp(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Reshape(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual inline const char* type() const { return "MappingBySimilarity"; } virtual inline int ExactNumBottomBlobs() const { return 2; } virtual inline int ExactNumTopBlobs() const { return 1; } protected: /** * * @param bottom bottom[0] is the input image blob of size (n, c, h, w), which means * it contains n/2 pairs of images exactly. * bottom[1] is the similarity map of size (n/2, 1, h, w). * @param top. The output image blob of size (n, c, h, w). */ virtual void Forward_cpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top); virtual void Backward_cpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); virtual void Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom); private: Dtype alpha_; }; } // namespace caffe #endif // CAFFE_MAPPING_BY_SIMILARITY_LAYER_HPP_
32.929825
87
0.672882
[ "vector" ]
ce14f6324d67a85a4e4a2f66f7cd7f0f1c9ccae6
12,532
cc
C++
wrappers/7.0.0/vtkLogoRepresentationWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
6
2016-02-03T12:48:36.000Z
2020-09-16T15:07:51.000Z
wrappers/7.0.0/vtkLogoRepresentationWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
4
2016-02-13T01:30:43.000Z
2020-03-30T16:59:32.000Z
wrappers/7.0.0/vtkLogoRepresentationWrap.cc
axkibe/node-vtk
900ad7b5500f672519da5aa24c99aa5a96466ef3
[ "BSD-3-Clause" ]
null
null
null
/* this file has been autogenerated by vtkNodeJsWrap */ /* editing this might proof futile */ #define VTK_WRAPPING_CXX #define VTK_STREAMS_FWD_ONLY #include <nan.h> #include "vtkBorderRepresentationWrap.h" #include "vtkLogoRepresentationWrap.h" #include "vtkObjectWrap.h" #include "vtkImageDataWrap.h" #include "vtkProperty2DWrap.h" #include "vtkPropCollectionWrap.h" #include "vtkWindowWrap.h" #include "vtkViewportWrap.h" #include "../../plus/plus.h" using namespace v8; extern Nan::Persistent<v8::Object> vtkNodeJsNoWrap; Nan::Persistent<v8::FunctionTemplate> VtkLogoRepresentationWrap::ptpl; VtkLogoRepresentationWrap::VtkLogoRepresentationWrap() { } VtkLogoRepresentationWrap::VtkLogoRepresentationWrap(vtkSmartPointer<vtkLogoRepresentation> _native) { native = _native; } VtkLogoRepresentationWrap::~VtkLogoRepresentationWrap() { } void VtkLogoRepresentationWrap::Init(v8::Local<v8::Object> exports) { Nan::SetAccessor(exports, Nan::New("vtkLogoRepresentation").ToLocalChecked(), ConstructorGetter); Nan::SetAccessor(exports, Nan::New("LogoRepresentation").ToLocalChecked(), ConstructorGetter); } void VtkLogoRepresentationWrap::ConstructorGetter( v8::Local<v8::String> property, const Nan::PropertyCallbackInfo<v8::Value>& info) { InitPtpl(); info.GetReturnValue().Set(Nan::New(ptpl)->GetFunction()); } void VtkLogoRepresentationWrap::InitPtpl() { if (!ptpl.IsEmpty()) return; v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); VtkBorderRepresentationWrap::InitPtpl( ); tpl->Inherit(Nan::New<FunctionTemplate>(VtkBorderRepresentationWrap::ptpl)); tpl->SetClassName(Nan::New("VtkLogoRepresentationWrap").ToLocalChecked()); tpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tpl, "BuildRepresentation", BuildRepresentation); Nan::SetPrototypeMethod(tpl, "buildRepresentation", BuildRepresentation); Nan::SetPrototypeMethod(tpl, "GetActors2D", GetActors2D); Nan::SetPrototypeMethod(tpl, "getActors2D", GetActors2D); Nan::SetPrototypeMethod(tpl, "GetClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "getClassName", GetClassName); Nan::SetPrototypeMethod(tpl, "GetImage", GetImage); Nan::SetPrototypeMethod(tpl, "getImage", GetImage); Nan::SetPrototypeMethod(tpl, "GetImageProperty", GetImageProperty); Nan::SetPrototypeMethod(tpl, "getImageProperty", GetImageProperty); Nan::SetPrototypeMethod(tpl, "IsA", IsA); Nan::SetPrototypeMethod(tpl, "isA", IsA); Nan::SetPrototypeMethod(tpl, "NewInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "newInstance", NewInstance); Nan::SetPrototypeMethod(tpl, "ReleaseGraphicsResources", ReleaseGraphicsResources); Nan::SetPrototypeMethod(tpl, "releaseGraphicsResources", ReleaseGraphicsResources); Nan::SetPrototypeMethod(tpl, "RenderOverlay", RenderOverlay); Nan::SetPrototypeMethod(tpl, "renderOverlay", RenderOverlay); Nan::SetPrototypeMethod(tpl, "SafeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "safeDownCast", SafeDownCast); Nan::SetPrototypeMethod(tpl, "SetImage", SetImage); Nan::SetPrototypeMethod(tpl, "setImage", SetImage); Nan::SetPrototypeMethod(tpl, "SetImageProperty", SetImageProperty); Nan::SetPrototypeMethod(tpl, "setImageProperty", SetImageProperty); #ifdef VTK_NODE_PLUS_VTKLOGOREPRESENTATIONWRAP_INITPTPL VTK_NODE_PLUS_VTKLOGOREPRESENTATIONWRAP_INITPTPL #endif ptpl.Reset( tpl ); } void VtkLogoRepresentationWrap::New(const Nan::FunctionCallbackInfo<v8::Value>& info) { if(!info.IsConstructCall()) { Nan::ThrowError("Constructor not called in a construct call."); return; } if(info.Length() == 0) { vtkSmartPointer<vtkLogoRepresentation> native = vtkSmartPointer<vtkLogoRepresentation>::New(); VtkLogoRepresentationWrap* obj = new VtkLogoRepresentationWrap(native); obj->Wrap(info.This()); } else { if(info[0]->ToObject() != vtkNodeJsNoWrap ) { Nan::ThrowError("Parameter Error"); return; } } info.GetReturnValue().Set(info.This()); } void VtkLogoRepresentationWrap::BuildRepresentation(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkLogoRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkLogoRepresentationWrap>(info.Holder()); vtkLogoRepresentation *native = (vtkLogoRepresentation *)wrapper->native.GetPointer(); if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } native->BuildRepresentation(); } void VtkLogoRepresentationWrap::GetActors2D(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkLogoRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkLogoRepresentationWrap>(info.Holder()); vtkLogoRepresentation *native = (vtkLogoRepresentation *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkPropCollectionWrap::ptpl))->HasInstance(info[0])) { VtkPropCollectionWrap *a0 = ObjectWrap::Unwrap<VtkPropCollectionWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->GetActors2D( (vtkPropCollection *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkLogoRepresentationWrap::GetClassName(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkLogoRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkLogoRepresentationWrap>(info.Holder()); vtkLogoRepresentation *native = (vtkLogoRepresentation *)wrapper->native.GetPointer(); char const * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetClassName(); info.GetReturnValue().Set(Nan::New(r).ToLocalChecked()); } void VtkLogoRepresentationWrap::GetImage(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkLogoRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkLogoRepresentationWrap>(info.Holder()); vtkLogoRepresentation *native = (vtkLogoRepresentation *)wrapper->native.GetPointer(); vtkImageData * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetImage(); VtkImageDataWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkImageDataWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkImageDataWrap *w = new VtkImageDataWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkLogoRepresentationWrap::GetImageProperty(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkLogoRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkLogoRepresentationWrap>(info.Holder()); vtkLogoRepresentation *native = (vtkLogoRepresentation *)wrapper->native.GetPointer(); vtkProperty2D * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->GetImageProperty(); VtkProperty2DWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkProperty2DWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkProperty2DWrap *w = new VtkProperty2DWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkLogoRepresentationWrap::IsA(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkLogoRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkLogoRepresentationWrap>(info.Holder()); vtkLogoRepresentation *native = (vtkLogoRepresentation *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsString()) { Nan::Utf8String a0(info[0]); int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->IsA( *a0 ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkLogoRepresentationWrap::NewInstance(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkLogoRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkLogoRepresentationWrap>(info.Holder()); vtkLogoRepresentation *native = (vtkLogoRepresentation *)wrapper->native.GetPointer(); vtkLogoRepresentation * r; if(info.Length() != 0) { Nan::ThrowError("Too many parameters."); return; } r = native->NewInstance(); VtkLogoRepresentationWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkLogoRepresentationWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkLogoRepresentationWrap *w = new VtkLogoRepresentationWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); } void VtkLogoRepresentationWrap::ReleaseGraphicsResources(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkLogoRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkLogoRepresentationWrap>(info.Holder()); vtkLogoRepresentation *native = (vtkLogoRepresentation *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkWindowWrap::ptpl))->HasInstance(info[0])) { VtkWindowWrap *a0 = ObjectWrap::Unwrap<VtkWindowWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->ReleaseGraphicsResources( (vtkWindow *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkLogoRepresentationWrap::RenderOverlay(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkLogoRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkLogoRepresentationWrap>(info.Holder()); vtkLogoRepresentation *native = (vtkLogoRepresentation *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkViewportWrap::ptpl))->HasInstance(info[0])) { VtkViewportWrap *a0 = ObjectWrap::Unwrap<VtkViewportWrap>(info[0]->ToObject()); int r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->RenderOverlay( (vtkViewport *) a0->native.GetPointer() ); info.GetReturnValue().Set(Nan::New(r)); return; } Nan::ThrowError("Parameter mismatch"); } void VtkLogoRepresentationWrap::SafeDownCast(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkLogoRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkLogoRepresentationWrap>(info.Holder()); vtkLogoRepresentation *native = (vtkLogoRepresentation *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkObjectWrap::ptpl))->HasInstance(info[0])) { VtkObjectWrap *a0 = ObjectWrap::Unwrap<VtkObjectWrap>(info[0]->ToObject()); vtkLogoRepresentation * r; if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } r = native->SafeDownCast( (vtkObject *) a0->native.GetPointer() ); VtkLogoRepresentationWrap::InitPtpl(); v8::Local<v8::Value> argv[1] = { Nan::New(vtkNodeJsNoWrap) }; v8::Local<v8::Function> cons = Nan::New<v8::FunctionTemplate>(VtkLogoRepresentationWrap::ptpl)->GetFunction(); v8::Local<v8::Object> wo = cons->NewInstance(1, argv); VtkLogoRepresentationWrap *w = new VtkLogoRepresentationWrap(); w->native = r; w->Wrap(wo); info.GetReturnValue().Set(wo); return; } Nan::ThrowError("Parameter mismatch"); } void VtkLogoRepresentationWrap::SetImage(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkLogoRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkLogoRepresentationWrap>(info.Holder()); vtkLogoRepresentation *native = (vtkLogoRepresentation *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkImageDataWrap::ptpl))->HasInstance(info[0])) { VtkImageDataWrap *a0 = ObjectWrap::Unwrap<VtkImageDataWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetImage( (vtkImageData *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); } void VtkLogoRepresentationWrap::SetImageProperty(const Nan::FunctionCallbackInfo<v8::Value>& info) { VtkLogoRepresentationWrap *wrapper = ObjectWrap::Unwrap<VtkLogoRepresentationWrap>(info.Holder()); vtkLogoRepresentation *native = (vtkLogoRepresentation *)wrapper->native.GetPointer(); if(info.Length() > 0 && info[0]->IsObject() && (Nan::New(VtkProperty2DWrap::ptpl))->HasInstance(info[0])) { VtkProperty2DWrap *a0 = ObjectWrap::Unwrap<VtkProperty2DWrap>(info[0]->ToObject()); if(info.Length() != 1) { Nan::ThrowError("Too many parameters."); return; } native->SetImageProperty( (vtkProperty2D *) a0->native.GetPointer() ); return; } Nan::ThrowError("Parameter mismatch"); }
33.597855
110
0.737632
[ "object" ]
ce159e307ab0ec57262a2ba52c299d2f44081b6b
7,480
hpp
C++
tests/benchdnn_graph/mlp/mlp.hpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
tests/benchdnn_graph/mlp/mlp.hpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
tests/benchdnn_graph/mlp/mlp.hpp
wuxun-zhang/mkl-dnn
00a239ad2c932b967234ffb528069800ffcc0334
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright 2022 Intel Corporation * * 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. *******************************************************************************/ #ifndef MLP_HPP #define MLP_HPP #include "common.hpp" #include "dnn_types.hpp" #include "dnnl_common.hpp" #include "dnnl_debug.hpp" #include "dnnl_graph_common.hpp" #include "utils/perf_report.hpp" #include "matmul/matmul.hpp" namespace mlp { using namespace matmul; using namespace benchdnnext; using graph_dt = dnnl::graph::logical_tensor::data_type; enum tensor_desc { DATA_INT8_, //only for int8 DATA_, DATA_OUT_, //only for int8 WEI_INT8_, WEI_, BIA_, MATMUL_, ACTFUNC_GRAD_, //used for backprop - one per layer DATA_TGRAD_, //used for backprop - one per layer WEI_TGRAD_, //used for backprop - one per layer DATA_GRAD_, //used for backprop - one per layer + 1 input WEI_GRAD_, //used for backprop - one per layer BIA_GRAD_, //used for backprop - one per layer }; struct lt_info { dnnl::graph::logical_tensor lt; data_kind_t data_fill_idx; int dt_mem_idx; int fp_mem_idx; }; struct settings_t { settings_t() = default; // ctor to save certain fields from resetting settings_t(const char *perf_template) : settings_t() { this->perf_template = perf_template; } prb_dims_t prb_dims; std::vector<dir_t> dir {FWD_I}; std::vector<const dt_conf_t *> cfg {conf_f32}; std::vector<dnnl_data_type_t> bia_dt {dnnl_data_type_undef}; std::vector<std::string> stag {tag::abx}, wtag {tag::abx}, dtag {tag::abx}; std::vector<attr_t::post_ops_t> actfunc; std::vector<attr_t::scale_t> scales {attr_t::scale_t()}; std::vector<attr_t::zero_points_t> zero_points {attr_t::zero_points_t()}; const char *perf_template_csv = "perf,%engine%,%DESC%," "%-time%,%0time%"; const char *perf_template_def = "perf,%engine%,%impl%,%prb%,%-time%,%0time%"; const char *perf_template = perf_template_def; void reset() { *this = settings_t(perf_template); } }; struct mlp_graph_spec_t { mlp_graph_spec_t(const prb_dims_t &a_dims, const std::string &wtag, const std::string &dtag, const dnnl_data_type_t &bia_dt, const dt_conf_t *cfg, std::vector<attr_t::post_ops_t> actfunc, attr_t::scale_t scales, attr_t::zero_points_t zps, dir_t dir) : prb_dims(a_dims) , cfg(cfg) , actfunc(actfunc) , raw_data_tag(dtag) , raw_wei_tag(wtag) , batch_sz(a_dims.dims[0]) , dir(dir) { assert(actfunc[0].entry.size() == prb_dims.ndims - 2); num_hidden_layers = prb_dims.ndims - 2; for (int i = 1; i < prb_dims.ndims - 1; i++) { layer_dims.push_back({batch_sz, prb_dims.dims[i]}); weight_dims.push_back({prb_dims.dims[i], prb_dims.dims[i + 1]}); bias_dims.push_back({prb_dims.dims[i + 1]}); activation_func.push_back(benchdnnext::convert_alg_kind( actfunc[0].entry[i - 1].eltwise.alg)); } layer_dims.push_back({batch_sz, prb_dims.dims[prb_dims.ndims - 1]}); mlp_src_dt = benchdnnext::convert_dt(cfg[SRC].dt); mlp_wei_dt = benchdnnext::convert_dt(cfg[WEI].dt); mlp_bias_dt = benchdnnext::convert_dt(bia_dt); mlp_dst_dt = benchdnnext::convert_dt(cfg[DST].dt); assert(mlp_src_dt == mlp_dst_dt); has_bias = (mlp_bias_dt != graph_dt::undef); mlp_layer_dt = (mlp_src_dt == graph_dt::bf16) ? mlp_src_dt : graph_dt::f32; is_mlp_int8 = mlp_src_dt == graph_dt::s8 || mlp_src_dt == graph_dt::u8; attr.insert(actfunc[0]); if (is_mlp_int8) { attr.insert(scales); attr.insert(zps); } use_dst = (rand() % 2 == 1) ? true : false; is_fwd_inference = (dir & FLAG_INF); is_fwd_training = (dir & FLAG_FWD) && !(dir & FLAG_INF); is_bwd_training = (dir & FLAG_BWD); } ~mlp_graph_spec_t() {} prb_dims_t prb_dims; const dt_conf_t *cfg; std::vector<attr_t::post_ops_t> actfunc; int num_hidden_layers {0}; attr_t attr; std::string raw_data_tag; std::string raw_wei_tag; int batch_sz; dir_t dir; bool use_static_transpose {false}; bool is_fwd_inference, is_fwd_training, is_bwd_training; bool has_bias {false}; bool use_dst {false}; std::vector<dnnl::graph::logical_tensor::dims_t> layer_dims, weight_dims, bias_dims; graph_dt mlp_src_dt, mlp_wei_dt, mlp_bias_dt, mlp_dst_dt, mlp_layer_dt; bool is_mlp_int8; std::vector<dnnl::graph::op::kind> activation_func; }; std::ostream &operator<<(std::ostream &s, const mlp_graph_spec_t &spec); struct perf_report_t : public base_perf_report_t { perf_report_t(const mlp_graph_spec_t *spec, const char *perf_template) : base_perf_report_t(perf_template), spec_(spec) {} void dump_desc(std::ostream &s) const override { s << *spec_; } void dump_desc_csv(std::ostream &s) const override { dump_desc(s); } private: const mlp_graph_spec_t *spec_; }; struct mlp_graph_prb_t : public ::benchdnnext::graph_prb_t { mlp_graph_prb_t(const mlp_graph_spec_t &spec) { const auto stop_work = [](const fill_status_t s) { return s != fill_status::DONE && s != fill_status::UNHANDLED_CONFIG_OPTIONS; }; ctor_status = build_mlp_subgraph(spec); if (stop_work(ctor_status)) return; ctor_status = fill_status::DONE; }; fill_status_t ctor_status; ~mlp_graph_prb_t() {} fill_status_t build_mlp_subgraph(const mlp_graph_spec_t &spec); std::map<int, struct lt_info> ltid_desc_lut; std::map<std::string, int> desc_ltid_lut; int get_fp_mem_idx(std::string tensor_name) { auto id = desc_ltid_lut[tensor_name]; return ltid_desc_lut[id].fp_mem_idx; } private: void add_quan_dequan_op(const mlp_graph_spec_t &spec, const std::string src, const std::string dst, std::vector<float> scales, std::vector<int64_t> zps, bool isquanop); void add_matmul_op( const mlp_graph_spec_t &spec, int layer_num, bool is_fwd_pass); void add_actfunc_op( const mlp_graph_spec_t &spec, int layer_num, bool is_fwd_pass); void add_statictranspose_op(const mlp_graph_spec_t &spec, int layer_num); void add_reducesum_op(const mlp_graph_spec_t &spec, int layer_num); void add_end_op(const mlp_graph_spec_t &spec, int layer_num); void build_tensor_desc_fwd(const mlp_graph_spec_t &spec); void build_tensor_desc_bwd(const mlp_graph_spec_t &spec); }; void compute_ref_mlp( const mlp_graph_spec_t *spec, const std::vector<args_t> &args); int doit(const mlp_graph_spec_t *spec, res_t *res); int bench(int argc, char **argv); } // namespace mlp #endif
36.847291
80
0.655481
[ "vector" ]
ce1a02ad6e7451f81703e702c89e1824b87d2e87
8,644
hpp
C++
include/nall/smtp.hpp
wareya/kotareci
14c87d1364d442456f93cebe73a288f85b79ba74
[ "Libpng" ]
21
2015-04-13T03:07:12.000Z
2021-11-20T00:27:00.000Z
nall/smtp.hpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
2
2015-10-06T14:59:48.000Z
2022-01-27T08:57:57.000Z
nall/smtp.hpp
apollolux/hello-phoenix
71510b5f329804c525a9576fb0367fe8ab2487cd
[ "MIT" ]
2
2021-11-19T08:36:57.000Z
2022-03-04T16:03:16.000Z
#ifndef NALL_SMTP_HPP #define NALL_SMTP_HPP #include <nall/base64.hpp> #include <nall/stdint.hpp> #include <nall/string.hpp> #if !defined(_WIN32) #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #else #include <winsock2.h> #include <ws2tcpip.h> #include <windows.h> #endif namespace nall { struct SMTP { enum class Format : unsigned { Plain, HTML }; inline void server(string server, uint16_t port = 25); inline void from(string mail, string name = ""); inline void to(string mail, string name = ""); inline void cc(string mail, string name = ""); inline void bcc(string mail, string name = ""); inline void attachment(const uint8_t* data, unsigned size, string name); inline bool attachment(string filename, string name = ""); inline void subject(string subject); inline void body(string body, Format format = Format::Plain); inline bool send(); inline string message(); inline string response(); #ifdef _WIN32 inline int close(int); inline SMTP(); #endif private: struct Information { string server; uint16_t port; struct Contact { string mail; string name; }; Contact from; vector<Contact> to; vector<Contact> cc; vector<Contact> bcc; struct Attachment { vector<uint8_t> buffer; string name; }; string subject; string body; Format format = Format::Plain; vector<Attachment> attachments; string message; string response; } info; inline bool send(int sock, const string& text); inline string recv(int sock); inline string boundary(); inline string filename(const string& filename); inline string contact(const Information::Contact& contact); inline string contacts(const vector<Information::Contact>& contacts); inline string split(const string& text); }; void SMTP::server(string server, uint16_t port) { info.server = server; info.port = port; } void SMTP::from(string mail, string name) { info.from = {mail, name}; } void SMTP::to(string mail, string name) { info.to.append({mail, name}); } void SMTP::cc(string mail, string name) { info.cc.append({mail, name}); } void SMTP::bcc(string mail, string name) { info.bcc.append({mail, name}); } void SMTP::attachment(const uint8_t* data, unsigned size, string name) { vector<uint8_t> buffer; buffer.resize(size); memcpy(buffer.data(), data, size); info.attachments.append({std::move(buffer), name}); } bool SMTP::attachment(string filename, string name) { if(!file::exists(filename)) return false; if(name == "") name = notdir(filename); auto buffer = file::read(filename); info.attachments.append({std::move(buffer), name}); return true; } void SMTP::subject(string subject) { info.subject = subject; } void SMTP::body(string body, Format format) { info.body = body; info.format = format; } bool SMTP::send() { info.message.append("From: =?UTF-8?B?", Base64::encode(contact(info.from)), "?=\r\n"); info.message.append("To: =?UTF-8?B?", Base64::encode(contacts(info.to)), "?=\r\n"); info.message.append("Cc: =?UTF-8?B?", Base64::encode(contacts(info.cc)), "?=\r\n"); info.message.append("Subject: =?UTF-8?B?", Base64::encode(info.subject), "?=\r\n"); string uniqueID = boundary(); info.message.append("MIME-Version: 1.0\r\n"); info.message.append("Content-Type: multipart/mixed; boundary=", uniqueID, "\r\n"); info.message.append("\r\n"); string format = (info.format == Format::Plain ? "text/plain" : "text/html"); info.message.append("--", uniqueID, "\r\n"); info.message.append("Content-Type: ", format, "; charset=UTF-8\r\n"); info.message.append("Content-Transfer-Encoding: base64\r\n"); info.message.append("\r\n"); info.message.append(split(Base64::encode(info.body)), "\r\n"); info.message.append("\r\n"); for(auto& attachment : info.attachments) { info.message.append("--", uniqueID, "\r\n"); info.message.append("Content-Type: application/octet-stream\r\n"); info.message.append("Content-Transfer-Encoding: base64\r\n"); info.message.append("Content-Disposition: attachment; size=", attachment.buffer.size(), "; filename*=UTF-8''", filename(attachment.name), "\r\n"); info.message.append("\r\n"); info.message.append(split(Base64::encode(attachment.buffer)), "\r\n"); info.message.append("\r\n"); } info.message.append("--", uniqueID, "--\r\n"); addrinfo hints; memset(&hints, 0, sizeof(addrinfo)); hints.ai_family = AF_UNSPEC; hints.ai_socktype = SOCK_STREAM; hints.ai_flags = AI_PASSIVE; addrinfo* serverinfo; int status = getaddrinfo(info.server, string(info.port), &hints, &serverinfo); if(status != 0) return false; int sock = socket(serverinfo->ai_family, serverinfo->ai_socktype, serverinfo->ai_protocol); if(sock == -1) return false; int result = connect(sock, serverinfo->ai_addr, serverinfo->ai_addrlen); if(result == -1) return false; string response; info.response.append(response = recv(sock)); if(!response.beginswith("220 ")) { close(sock); return false; } send(sock, {"HELO ", info.server, "\r\n"}); info.response.append(response = recv(sock)); if(!response.beginswith("250 ")) { close(sock); return false; } send(sock, {"MAIL FROM: <", info.from.mail, ">\r\n"}); info.response.append(response = recv(sock)); if(!response.beginswith("250 ")) { close(sock); return false; } for(auto& contact : info.to) { send(sock, {"RCPT TO: <", contact.mail, ">\r\n"}); info.response.append(response = recv(sock)); if(!response.beginswith("250 ")) { close(sock); return false; } } for(auto& contact : info.cc) { send(sock, {"RCPT TO: <", contact.mail, ">\r\n"}); info.response.append(response = recv(sock)); if(!response.beginswith("250 ")) { close(sock); return false; } } for(auto& contact : info.bcc) { send(sock, {"RCPT TO: <", contact.mail, ">\r\n"}); info.response.append(response = recv(sock)); if(!response.beginswith("250 ")) { close(sock); return false; } } send(sock, {"DATA\r\n"}); info.response.append(response = recv(sock)); if(!response.beginswith("354 ")) { close(sock); return false; } send(sock, {info.message, "\r\n", ".\r\n"}); info.response.append(response = recv(sock)); if(!response.beginswith("250 ")) { close(sock); return false; } send(sock, {"QUIT\r\n"}); info.response.append(response = recv(sock)); //if(!response.beginswith("221 ")) { close(sock); return false; } close(sock); return true; } string SMTP::message() { return info.message; } string SMTP::response() { return info.response; } bool SMTP::send(int sock, const string& text) { const char* data = text.data(); unsigned size = text.size(); while(size) { int length = ::send(sock, (const char*)data, size, 0); if(length == -1) return false; data += length; size -= length; } return true; } string SMTP::recv(int sock) { vector<uint8_t> buffer; while(true) { char c; if(::recv(sock, &c, sizeof(char), 0) < 1) break; buffer.append(c); if(c == '\n') break; } buffer.append(0); return buffer; } string SMTP::boundary() { random_lfsr random; random.seed(time(0)); string boundary; for(unsigned n = 0; n < 16; n++) boundary.append(hex<2>(random())); return boundary; } string SMTP::filename(const string& filename) { string result; for(auto& n : filename) { if(n <= 32 || n >= 127) result.append("%", hex<2>(n)); else result.append(n); } return result; } string SMTP::contact(const Information::Contact& contact) { if(!contact.name) return contact.mail; return {"\"", contact.name, "\" <", contact.mail, ">"}; } string SMTP::contacts(const vector<Information::Contact>& contacts) { string result; for(auto& contact : contacts) { result.append(this->contact(contact), "; "); } result.rtrim<1>("; "); return result; } string SMTP::split(const string& text) { string result; unsigned offset = 0; while(offset < text.size()) { unsigned length = min(76, text.size() - offset); if(length < 76) { result.append(text.slice(offset)); } else { result.append(text.slice(offset, 76), "\r\n"); } offset += length; } return result; } #ifdef _WIN32 int SMTP::close(int sock) { return closesocket(sock); } SMTP::SMTP() { int sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP); if(sock == INVALID_SOCKET && WSAGetLastError() == WSANOTINITIALISED) { WSADATA wsaData; if(WSAStartup(MAKEWORD(2, 2), &wsaData) != 0) { WSACleanup(); return; } } else { close(sock); } } #endif } #endif
27.097179
150
0.649699
[ "vector" ]
ce1c7cf65ed86050628394b19b75b40f701a1803
13,944
cpp
C++
Development/External/wxWindows_2.4.0/src/common/dynlib.cpp
addstone/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
37
2020-05-22T18:18:47.000Z
2022-03-19T06:51:54.000Z
Development/External/wxWindows_2.4.0/src/common/dynlib.cpp
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
null
null
null
Development/External/wxWindows_2.4.0/src/common/dynlib.cpp
AdanosGotoman/unrealengine3
4579d360dfd52b12493292120b27bb430f978fc8
[ "FSFAP" ]
27
2020-05-17T01:03:30.000Z
2022-03-06T19:10:14.000Z
///////////////////////////////////////////////////////////////////////////// // Name: dynlib.cpp // Purpose: Dynamic library management // Author: Guilhem Lavaux // Modified by: // Created: 20/07/98 // RCS-ID: $Id: dynlib.cpp,v 1.67.2.2 2002/12/19 23:43:33 VS Exp $ // Copyright: (c) Guilhem Lavaux // Licence: wxWindows license ///////////////////////////////////////////////////////////////////////////// // ============================================================================ // declarations // ============================================================================ // ---------------------------------------------------------------------------- // headers // ---------------------------------------------------------------------------- #ifdef __GNUG__ # pragma implementation "dynlib.h" #endif #include "wx/wxprec.h" #ifdef __BORLANDC__ #pragma hdrstop #endif #if wxUSE_DYNLIB_CLASS && !wxUSE_DYNAMIC_LOADER #if defined(__WINDOWS__) #include "wx/msw/private.h" #endif #include "wx/dynlib.h" #include "wx/filefn.h" #include "wx/intl.h" #include "wx/log.h" #if defined(__WXMAC__) #include "wx/mac/private.h" #endif // ---------------------------------------------------------------------------- // conditional compilation // ---------------------------------------------------------------------------- #if defined(__WXPM__) || defined(__EMX__) # define INCL_DOS # include <os2.h> # define wxDllOpen(error, lib, handle) DosLoadModule(error, sizeof(error), lib, &handle) # define wxDllGetSymbol(handle, modaddr) DosQueryProcAddr(handle, 1L, NULL, (PFN*)modaddr) # define wxDllClose(handle) DosFreeModule(handle) #elif defined(HAVE_DLOPEN) // note about dlopen() flags: we use RTLD_NOW to have more Windows-like // behaviour (Win won't let you load a library with missing symbols) and // RTLD_GLOBAL because it is needed sometimes and probably doesn't hurt // otherwise. On True64-Unix RTLD_GLOBAL is not allowed and on VMS the // second argument on dlopen is ignored. #ifdef __VMS # define wxDllOpen(lib) dlopen(lib.fn_str(), 0 ) #elif defined( __osf__ ) # define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY ) #else # define wxDllOpen(lib) dlopen(lib.fn_str(), RTLD_LAZY | RTLD_GLOBAL) #endif #define wxDllGetSymbol(handle, name) dlsym(handle, name) # define wxDllClose dlclose #elif defined(HAVE_SHL_LOAD) # define wxDllOpen(lib) shl_load(lib.fn_str(), BIND_DEFERRED, 0) # define wxDllClose shl_unload static inline void *wxDllGetSymbol(shl_t handle, const wxString& name) { void *sym; if ( shl_findsym(&handle, name.mb_str(), TYPE_UNDEFINED, &sym) == 0 ) return sym; else return 0; } #elif defined(__DARWIN__) /* Porting notes: * The dlopen port is a port from dl_next.xs by Anno Siegel. * dl_next.xs is itself a port from dl_dlopen.xs by Paul Marquess. * The method used here is just to supply the sun style dlopen etc. * functions in terms of Darwin NS*. */ void *dlopen(const char *path, int mode /* mode is ignored */); void *dlsym(void *handle, const char *symbol); int dlclose(void *handle); const char *dlerror(void); # define wxDllOpen(lib) dlopen(lib.fn_str(), 0) # define wxDllGetSymbol(handle, name) dlsym(handle, name) # define wxDllClose dlclose #elif defined(__WINDOWS__) // using LoadLibraryEx under Win32 to avoid name clash with LoadLibrary # ifdef __WIN32__ #ifdef _UNICODE # define wxDllOpen(lib) ::LoadLibraryExW(lib, 0, 0) #else # define wxDllOpen(lib) ::LoadLibraryExA(lib, 0, 0) #endif # else // Win16 # define wxDllOpen(lib) ::LoadLibrary(lib) # endif // Win32/16 # define wxDllGetSymbol(handle, name) ::GetProcAddress(handle, name) # define wxDllClose ::FreeLibrary #elif defined(__WXMAC__) # define wxDllClose(handle) CloseConnection(&((CFragConnectionID)handle)) #else # error "Don't know how to load shared libraries on this platform." #endif // OS // --------------------------------------------------------------------------- // Global variables // --------------------------------------------------------------------------- wxLibraries wxTheLibraries; // ============================================================================ // implementation // ============================================================================ // construct the full name from the base shared object name: adds a .dll // suffix under Windows or .so under Unix static wxString ConstructLibraryName(const wxString& basename) { wxString fullname; fullname << basename << wxDllLoader::GetDllExt(); return fullname; } // --------------------------------------------------------------------------- // wxLibrary (one instance per dynamic library) // --------------------------------------------------------------------------- wxLibrary::wxLibrary(wxDllType handle) { typedef wxClassInfo *(*t_get_first)(void); t_get_first get_first; m_handle = handle; // Some system may use a local heap for library. get_first = (t_get_first)GetSymbol(_T("wxGetClassFirst")); // It is a wxWindows DLL. if (get_first) PrepareClasses(get_first()); } wxLibrary::~wxLibrary() { if ( m_handle ) { wxDllClose(m_handle); } } wxObject *wxLibrary::CreateObject(const wxString& name) { wxClassInfo *info = (wxClassInfo *)classTable.Get(name); if (!info) return NULL; return info->CreateObject(); } void wxLibrary::PrepareClasses(wxClassInfo *first) { // Index all class infos by their class name wxClassInfo *info = first; while (info) { if (info->m_className) classTable.Put(info->m_className, (wxObject *)info); info = info->m_next; } // Set base pointers for each wxClassInfo info = first; while (info) { if (info->GetBaseClassName1()) info->m_baseInfo1 = (wxClassInfo *)classTable.Get(info->GetBaseClassName1()); if (info->GetBaseClassName2()) info->m_baseInfo2 = (wxClassInfo *)classTable.Get(info->GetBaseClassName2()); info = info->m_next; } } void *wxLibrary::GetSymbol(const wxString& symbname) { return wxDllLoader::GetSymbol(m_handle, symbname); } // --------------------------------------------------------------------------- // wxDllLoader // --------------------------------------------------------------------------- #if defined(__WINDOWS__) || defined(__WXPM__) || defined(__EMX__) const wxString wxDllLoader::ms_dllext( _T(".dll") ); #elif defined(__UNIX__) #if defined(__HPUX__) const wxString wxDllLoader::ms_dllext( _T(".sl") ); #else const wxString wxDllLoader::ms_dllext( _T(".so") ); #endif #elif defined(__WXMAC__) const wxString wxDllLoader::ms_dllext( _T("") ); #endif /* static */ wxDllType wxDllLoader::GetProgramHandle() { #if defined( HAVE_DLOPEN ) && !defined(__EMX__) // optain handle for main program return dlopen(NULL, RTLD_NOW/*RTLD_LAZY*/); #elif defined (HAVE_SHL_LOAD) // shl_findsymbol with NULL handle looks up in main program return 0; #else wxFAIL_MSG( wxT("This method is not implemented under Windows or OS/2")); return 0; #endif } /* static */ wxDllType wxDllLoader::LoadLibrary(const wxString & libname, bool *success) { wxDllType handle; bool failed = FALSE; #if defined(__WXMAC__) && !defined(__UNIX__) FSSpec myFSSpec; Ptr myMainAddr; Str255 myErrName; wxMacFilename2FSSpec( libname , &myFSSpec ); if( GetDiskFragment( &myFSSpec, 0, kCFragGoesToEOF, "\p", kPrivateCFragCopy, &((CFragConnectionID)handle), &myMainAddr, myErrName ) != noErr ) { p2cstr( myErrName ); wxLogSysError( _("Failed to load shared library '%s' Error '%s'"), libname.c_str(), (char*)myErrName ); handle = 0; failed = TRUE; } #elif defined(__WXPM__) || defined(__EMX__) char zError[256] = ""; wxDllOpen(zError, libname, handle); #else handle = wxDllOpen(libname); #endif if ( !handle ) { wxString msg(_("Failed to load shared library '%s'")); #ifdef HAVE_DLERROR const wxChar *err = dlerror(); if( err ) { failed = TRUE; wxLogError( msg, err ); } #else failed = TRUE; wxLogSysError( msg, libname.c_str() ); #endif } if ( success ) *success = !failed; return handle; } /* static */ void wxDllLoader::UnloadLibrary(wxDllType handle) { wxDllClose(handle); } /* static */ void *wxDllLoader::GetSymbol(wxDllType dllHandle, const wxString &name, bool *success) { bool failed = FALSE; void *symbol = 0; #if defined(__WXMAC__) && !defined(__UNIX__) Ptr symAddress; CFragSymbolClass symClass; Str255 symName; #if TARGET_CARBON c2pstrcpy( (StringPtr) symName, name ); #else strcpy( (char *) symName, name ); c2pstr( (char *) symName ); #endif if( FindSymbol( ((CFragConnectionID)dllHandle), symName, &symAddress, &symClass ) == noErr ) symbol = (void *)symAddress; #elif defined(__WXPM__) || defined(__EMX__) wxDllGetSymbol(dllHandle, symbol); #else // Windows or Unix // mb_str() is necessary in Unicode build // // "void *" cast is needed by gcc 3.1 + w32api 1.4, don't ask me why symbol = (void *)wxDllGetSymbol(dllHandle, name.mb_str()); #endif // OS if ( !symbol ) { #ifdef HAVE_DLERROR const wxChar *err = dlerror(); if( err ) { wxLogError(wxT("%s"), err); } #else failed = TRUE; wxLogSysError(_("Couldn't find symbol '%s' in a dynamic library"), name.c_str()); #endif } if( success ) *success = !failed; return symbol; } // --------------------------------------------------------------------------- // wxLibraries (only one instance should normally exist) // --------------------------------------------------------------------------- wxLibraries::wxLibraries():m_loaded(wxKEY_STRING) { } wxLibraries::~wxLibraries() { wxNode *node = m_loaded.First(); while (node) { wxLibrary *lib = (wxLibrary *)node->Data(); delete lib; node = node->Next(); } } wxLibrary *wxLibraries::LoadLibrary(const wxString& name) { wxLibrary *lib; wxClassInfo *old_sm_first; wxNode *node = m_loaded.Find(name.GetData()); if (node != NULL) return ((wxLibrary *)node->Data()); // If DLL shares data, this is necessary. old_sm_first = wxClassInfo::sm_first; wxClassInfo::sm_first = NULL; wxString libname = ConstructLibraryName(name); bool success = FALSE; wxDllType handle = wxDllLoader::LoadLibrary(libname, &success); if(success) { lib = new wxLibrary(handle); wxClassInfo::sm_first = old_sm_first; m_loaded.Append(name.GetData(), lib); } else lib = NULL; return lib; } wxObject *wxLibraries::CreateObject(const wxString& path) { wxNode *node = m_loaded.First(); wxObject *obj; while (node) { obj = ((wxLibrary *)node->Data())->CreateObject(path); if (obj) return obj; node = node->Next(); } return NULL; } #endif // wxUSE_DYNLIB_CLASS && !wxUSE_DYNAMIC_LOADER #if defined(__DARWIN__) && (wxUSE_DYNLIB_CLASS || wxUSE_DYNAMIC_LOADER) // --------------------------------------------------------------------------- // For Darwin/Mac OS X // supply the sun style dlopen functions in terms of Darwin NS* // --------------------------------------------------------------------------- #include <stdio.h> #include <mach-o/dyld.h> static char dl_last_error[1024]; static void TranslateError(const char *path, int number) { unsigned int index; static char *OFIErrorStrings[] = { "%s(%d): Object Image Load Failure\n", "%s(%d): Object Image Load Success\n", "%s(%d): Not an recognisable object file\n", "%s(%d): No valid architecture\n", "%s(%d): Object image has an invalid format\n", "%s(%d): Invalid access (permissions?)\n", "%s(%d): Unknown error code from NSCreateObjectFileImageFromFile\n", }; #define NUM_OFI_ERRORS (sizeof(OFIErrorStrings) / sizeof(OFIErrorStrings[0])) index = number; if (index > NUM_OFI_ERRORS - 1) { index = NUM_OFI_ERRORS - 1; } sprintf(dl_last_error, OFIErrorStrings[index], path, number); } const char *dlerror() { return dl_last_error; } void *dlopen(const char *path, int WXUNUSED(mode) /* mode is ignored */) { int dyld_result; NSObjectFileImage ofile; NSModule handle = NULL; dyld_result = NSCreateObjectFileImageFromFile(path, &ofile); if (dyld_result != NSObjectFileImageSuccess) { TranslateError(path, dyld_result); } else { // NSLinkModule will cause the run to abort on any link error's // not very friendly but the error recovery functionality is limited. handle = NSLinkModule(ofile, path, NSLINKMODULE_OPTION_BINDNOW); } return handle; } int dlclose(void *handle) { NSUnLinkModule( handle, NSUNLINKMODULE_OPTION_NONE); return 0; } void *dlsym(void *WXUNUSED(handle), const char *symbol) { void *addr; if (NSIsSymbolNameDefined(symbol)) { addr = NSAddressOfSymbol(NSLookupAndBindSymbol(symbol)); } else { addr = NULL; } return addr; } #endif // defined(__DARWIN__) && (wxUSE_DYNLIB_CLASS || wxUSE_DYNAMIC_LOADER)
27.832335
96
0.56354
[ "object" ]
ce238b5b3e4342351610fe028d41f641be41019c
6,906
cpp
C++
src/general/particle.cpp
alexander-rass/HiPPSO
42334f18f8cee2dbada09a8c99c47cf1119107a5
[ "MIT" ]
4
2017-03-22T11:52:22.000Z
2021-01-16T04:07:45.000Z
src/general/particle.cpp
alexander-rass/HiPPSO
42334f18f8cee2dbada09a8c99c47cf1119107a5
[ "MIT" ]
5
2017-03-21T13:02:49.000Z
2018-12-11T15:44:01.000Z
src/general/particle.cpp
alexander-rass/HiPPSO
42334f18f8cee2dbada09a8c99c47cf1119107a5
[ "MIT" ]
2
2020-09-11T17:59:10.000Z
2020-09-11T18:54:03.000Z
/** * @file general/particle.cpp * @author Alexander Raß (alexander.rass@fau.de) * @date July, 2013 * @brief This file contains information about the particles of the swarm. * * @copyright * This project is released under the MIT License (MIT). * * @copyright * The MIT License (MIT) * * @copyright * Copyright (c) 2016 by Friedrich-Alexander-Universität Erlangen-Nürnberg and * Alexander Raß * * @copyright * 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: * * @copyright * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * @copyright * 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 "general/particle.h" #include "function/function.h" #include "general/check_condition.h" #include "general/configuration.h" #include "arbitrary_precision_calculation/operations.h" #include "neighborhood/neighborhood.h" #include "position_and_velocity_updater/position_and_velocity_updater.h" #include "statistics/statistics.h" namespace highprecisionpso { int Particle::active_particles_ = 0; Particle::Particle() { id = active_particles_++; local_attractor_position.clear(); local_attractor_value_cached_ = NULL; local_attractor_value_cached_precision_ = 1; } std::vector<mpf_t*> Particle::GetLocalAttractorPosition() { return arbitraryprecisioncalculation::vectoroperations::Clone(local_attractor_position); } mpf_t* Particle::GetLocalAttractorValue() { if(0 == local_attractor_position.size())return NULL; if(local_attractor_value_cached_ == NULL || mpf_get_default_prec() != local_attractor_value_cached_precision_){ if(local_attractor_value_cached_ == NULL)arbitraryprecisioncalculation::mpftoperations::ChangeNumberOfMpftValuesCached(1); arbitraryprecisioncalculation::mpftoperations::ReleaseValue(local_attractor_value_cached_); local_attractor_value_cached_precision_ = mpf_get_default_prec(); local_attractor_value_cached_ = configuration::g_function->Evaluate(local_attractor_position); } return arbitraryprecisioncalculation::mpftoperations::Clone(local_attractor_value_cached_); } std::vector<mpf_t*> Particle::GetPosition() { return arbitraryprecisioncalculation::vectoroperations::Clone(position); } std::vector<mpf_t*> Particle::GetVelocity() { return arbitraryprecisioncalculation::vectoroperations::Clone(velocity); } void Particle::SetLocalAttractorPosition(std::vector<mpf_t*> newLocalAttractorPosition) { configuration::g_statistics->local_attractor_update_counter[id]++; arbitraryprecisioncalculation::vectoroperations::ReleaseValues(local_attractor_position); local_attractor_position = arbitraryprecisioncalculation::vectoroperations::Clone(newLocalAttractorPosition); if(local_attractor_value_cached_ != NULL) { arbitraryprecisioncalculation::mpftoperations::ReleaseValue(local_attractor_value_cached_); arbitraryprecisioncalculation::mpftoperations::ChangeNumberOfMpftValuesCached(-1); } local_attractor_value_cached_ = NULL; } void Particle::SetPosition(std::vector<mpf_t*> newPosition) { arbitraryprecisioncalculation::vectoroperations::ReleaseValues(position); position = arbitraryprecisioncalculation::vectoroperations::Clone(newPosition); mpf_t* newVal = configuration::g_function->Evaluate(position); mpf_t* curLocalAttractorValue = GetLocalAttractorValue(); if (curLocalAttractorValue == NULL || (arbitraryprecisioncalculation::mpftoperations::Compare(newVal, curLocalAttractorValue) <= 0) ) { SetLocalAttractorPosition(position); UpdateGlobalAttractor(position, newVal); } arbitraryprecisioncalculation::mpftoperations::ReleaseValue(curLocalAttractorValue); arbitraryprecisioncalculation::mpftoperations::ReleaseValue(newVal); } void Particle::SetVelocity(std::vector<mpf_t*> newVelocity) { arbitraryprecisioncalculation::vectoroperations::ReleaseValues(velocity); velocity = arbitraryprecisioncalculation::vectoroperations::Clone(newVelocity); } void Particle::UpdateGlobalAttractor(std::vector<mpf_t*> goodPosition, mpf_t* goodValue) { configuration::g_neighborhood->UpdateAttractor(goodPosition, goodValue, this); } void Particle::UpdatePosition() { configuration::g_position_and_velocity_updater->Update(this); } void Particle::LoadData(std::ifstream* inputstream, ProgramVersion* version_of_stored_data){ AssertCondition( position.size() == 0, "Load of particle failed."); AssertCondition( velocity.size() == 0, "Load of particle failed."); AssertCondition( local_attractor_position.size() == 0, "Load of particle failed."); for (int d = 0; d < configuration::g_dimensions; d++) { position.push_back(arbitraryprecisioncalculation::mpftoperations::LoadMpft(inputstream)); } for (int d = 0; d < configuration::g_dimensions; d++) { velocity.push_back(arbitraryprecisioncalculation::mpftoperations::LoadMpft(inputstream)); } for (int d = 0; d < configuration::g_dimensions; d++) { local_attractor_position.push_back(arbitraryprecisioncalculation::mpftoperations::LoadMpft(inputstream)); } if((*version_of_stored_data)>=ProgramVersion("1.0.2")){ local_attractor_value_cached_ = arbitraryprecisioncalculation::mpftoperations::LoadMpft(inputstream); (*inputstream) >> local_attractor_value_cached_precision_; } } void Particle::StoreData(std::ofstream* outputstream){ for (int d = 0; d < configuration::g_dimensions; d++) { arbitraryprecisioncalculation::mpftoperations::StoreMpft(position[d], outputstream); } (*outputstream) << std::endl; for (int d = 0; d < configuration::g_dimensions; d++) { arbitraryprecisioncalculation::mpftoperations::StoreMpft(velocity[d], outputstream); } (*outputstream) << std::endl; for (int d = 0; d < configuration::g_dimensions; d++) { arbitraryprecisioncalculation::mpftoperations::StoreMpft(local_attractor_position[d], outputstream); } (*outputstream) << std::endl; arbitraryprecisioncalculation::mpftoperations::StoreMpft(local_attractor_value_cached_, outputstream); (*outputstream) << std::endl; (*outputstream) << local_attractor_value_cached_precision_; (*outputstream) << std::endl; } } // namespace highprecisionpso
43.1625
136
0.794671
[ "vector" ]
ce2b16f3e87a01c632c7373fd0ac35a583e0827c
1,366
cpp
C++
Competitive Programing Problem Solutions/Other/LU/f.cpp
BIJOY-SUST/ACM---ICPC
b382d80d327ddcab15ab15c0e763ccf8a22e0d43
[ "Apache-2.0" ]
1
2022-02-27T12:07:59.000Z
2022-02-27T12:07:59.000Z
Competitive Programing Problem Solutions/Other/LU/f.cpp
BIJOY-SUST/Competitive-Programming
b382d80d327ddcab15ab15c0e763ccf8a22e0d43
[ "Apache-2.0" ]
null
null
null
Competitive Programing Problem Solutions/Other/LU/f.cpp
BIJOY-SUST/Competitive-Programming
b382d80d327ddcab15ab15c0e763ccf8a22e0d43
[ "Apache-2.0" ]
null
null
null
#include<bits/stdc++.h> using namespace std; /*class data{ public: string name; int rrr; }; */bool compare(string a,string b){ return lexicographical_compare(a.begin(),a.end(),b.begin(),b.end()); } int main(){ int t; cin>>t; map<int,string>m; vector<string>se; for(int j=1;j<=t;j++){ int n,d=0,c=0; cin>>n; for(int i=1;i<=n;i++){ string s; int rat; cin>>s>>rat; m[rat]=s; if(rat>d){ d=rat; se.push_back(s); } else if(rat==d){ c++; se.push_back(s); } } string ss; if(c==0){ ss=m[d]; } else{ sort(se.begin(),se.end(),compare); ss=se[0]; } if(d>=1&&d<=1199){ cout<<"Case "<<j<<": "<<ss<<" is Newbie!.\n"; } else if(d>=1200&&d<=1399){ cout<<"Case "<<j<<": "<<ss<<" is Pupil!.\n"; } else if(d>=1400&&d<=1599){ cout<<"Case "<<j<<": "<<ss<<" is Specialist!.\n"; } else if(d>=1600&&d<=1899){ cout<<"Case "<<j<<": "<<ss<<" is Expert!.\n"; } se.clear(); m.clear(); } return 0; }
23.551724
77
0.360176
[ "vector" ]
ce2ff668e2f87302d1b7be9d3c2999a748022603
3,487
cc
C++
src/partition.cc
VoVAllen/dist_metis
27f56c051caf97fc6d7bdb5bea77dac5b8db28b2
[ "Apache-2.0" ]
1
2020-11-25T13:44:59.000Z
2020-11-25T13:44:59.000Z
src/partition.cc
VoVAllen/dist_metis
27f56c051caf97fc6d7bdb5bea77dac5b8db28b2
[ "Apache-2.0" ]
null
null
null
src/partition.cc
VoVAllen/dist_metis
27f56c051caf97fc6d7bdb5bea77dac5b8db28b2
[ "Apache-2.0" ]
null
null
null
#include <dmlc/io.h> #include <mpi.h> #include <parmetis.h> #include <partition.h> #include <iostream> #include <memory> #include <string> void MetisAssignment(int64_t num_partition, std::string input_filename, std::string output_filename, size_t mpi_com_handle) { auto fs = std::unique_ptr<dmlc::SeekStream>( dmlc::SeekStream::CreateForRead(input_filename.c_str())); static_assert(std::is_same<idx_t, int64_t>::value, "type must be `int64_t`"); static_assert(std::is_same<real_t, float>::value, "real_t must be `float`"); MPI_Comm *mpi_con = reinterpret_cast<MPI_Comm *>(mpi_com_handle); int mpi_size, rank; MPI_Comm_size(*mpi_con, &mpi_size); MPI_Comm_rank(*mpi_con, &rank); // mpi_size = 2; // rank = 1; uint64_t magicNum; size_t indptr_start_pos, indcies_start_pos, vwgt_start_pos; idx_t num_vertexs; fs->Read(&magicNum); fs->Read(&num_vertexs); fs->Read(&indptr_start_pos); fs->Read(&indcies_start_pos); fs->Read(&vwgt_start_pos); std::vector<idx_t> indptr, indices, vwgt_arr; std::vector<idx_t> part_arr; part_arr.resize(num_vertexs); std::vector<idx_t> vtxdist; vtxdist.push_back(0); size_t pos = num_vertexs / mpi_size; for (size_t i = 1; i < mpi_size + 1; i++) { if (pos > num_vertexs) { pos = num_vertexs; } vtxdist.push_back(pos); pos += num_vertexs / mpi_size; } size_t num_indptr = vtxdist[rank + 1] - vtxdist[rank]; indptr.resize(num_indptr + 1); fs->Seek(indptr_start_pos + sizeof(int64_t) + vtxdist[rank] * sizeof(int64_t)); fs->ReadArray(&indptr[0], num_indptr + 1); size_t num_indices = indptr[indptr.size() - 1] - indptr[0]; fs->Seek(indcies_start_pos + sizeof(int64_t) + indptr[0] * sizeof(int64_t)); indices.resize(num_indices); fs->ReadArray(&indices[0], num_indices); int64_t relabel_base = indptr[0]; for (size_t i = 0; i < indptr.size(); i++) { indptr[i] = indptr[i] - relabel_base; } idx_t nvtxs = num_vertexs; idx_t ncon = 1; // # balacing constraints. idx_t *xadj = &indptr[0]; idx_t *adjncy = &indices[0]; idx_t nparts = num_partition; idx_t objval = 0; idx_t *part = &part_arr[0]; int64_t vwgt_len = vwgt_arr.size(); idx_t *vwgt = NULL; idx_t wgtflag = 0; if (vwgt_len > 0) { ncon = vwgt_len / num_vertexs; vwgt = &vwgt_arr[0]; wgtflag = 2; } idx_t numflag = 0; idx_t options[3] = {0, 0, 0}; std::vector<real_t> tpwgts; tpwgts.resize(ncon * nparts); std::fill(tpwgts.begin(), tpwgts.end(), 1.0f / (nparts)); std::vector<real_t> ubvec; ubvec.resize(ncon); std::fill(ubvec.begin(), ubvec.end(), 1.05f); ParMETIS_V3_PartKway( &vtxdist[0], // vertex partition, xadj, // indptr adjncy, // indices vwgt, // the weights of the vertices nullptr, // edge weight &wgtflag, // flags of whether use weights of the edges &numflag, // count from zero &ncon, // The number of balancing constraints. &nparts, // Number of partitions &tpwgts[0], // the desired weight for each partition and constraint &ubvec[0], // the allowed load imbalanceg tolerance &options[0], // options &objval, // total edge cut part, // partition output mpi_con); auto out_fs = std::unique_ptr<dmlc::Stream>(dmlc::Stream::Create( (output_filename + std::to_string(rank)).c_str(), "w")); out_fs->Write(part_arr); }
33.854369
79
0.640379
[ "vector" ]
ce31cee7631a982bc2f702ac885afcd2bebfc35d
3,373
cpp
C++
src/lua-format.cpp
karanankit01/LuaFormatter
edb5f13b0b6491a4c8cc596d5348f53ba387690f
[ "Apache-2.0" ]
1
2021-02-04T04:46:59.000Z
2021-02-04T04:46:59.000Z
src/lua-format.cpp
karanankit01/LuaFormatter
edb5f13b0b6491a4c8cc596d5348f53ba387690f
[ "Apache-2.0" ]
null
null
null
src/lua-format.cpp
karanankit01/LuaFormatter
edb5f13b0b6491a4c8cc596d5348f53ba387690f
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include "FormatVisitor.h" #include "LuaLexer.h" using namespace std; using namespace antlr4; static string __format(ANTLRInputStream& input, const Config& config) { LuaLexer lexer(&input); CommonTokenStream tokenstream(&lexer); LuaParser parser(&tokenstream); LuaParser::ChunkContext* chunk = parser.chunk(); if (parser.getNumberOfSyntaxErrors() > 0) { throw invalid_argument("Input contains syntax errors"); } vector<antlr4::Token*> tokenVector; for (auto t : tokenstream.getTokens()) { tokenVector.emplace_back(t); } FormatVisitor visitor(tokenVector, config); return chunk->accept(&visitor).as<string>(); } static const string DISABLE_FORMAT_BEGIN = "-- LuaFormatter off"; static const string DISABLE_FORMAT_END = "-- LuaFormatter on"; // TODO: Collect it while walking AST seems better vector<pair<size_t, size_t>> findBlocksBetweenFormatSwitch(const string& str) { vector<pair<size_t, size_t>> blocks; size_t pos = string::npos; size_t findAt = 0; deque<size_t> startArr; while ((pos = str.find(DISABLE_FORMAT_BEGIN, findAt)) != string::npos) { startArr.push_back(pos); findAt = pos + DISABLE_FORMAT_BEGIN.size(); } pos = string::npos; findAt = 0; while ((pos = str.find(DISABLE_FORMAT_END, findAt)) != string::npos) { if (!startArr.empty()) { size_t start = startArr.front(); startArr.pop_front(); blocks.push_back({start, pos}); } findAt = pos + DISABLE_FORMAT_END.size(); } return blocks; } string resetContentInDisableFormatBlocks(const string& original, const string& formatted) { vector<pair<size_t, size_t>> originalBlocks = findBlocksBetweenFormatSwitch(original); vector<pair<size_t, size_t>> formattedBlocks = findBlocksBetweenFormatSwitch(formatted); if (originalBlocks.size() != formattedBlocks.size()) { cerr << "Unexpected! originalBlocks.size() = " << originalBlocks.size() << " , formattedBlocks.size() = " << formattedBlocks.size() << endl; } size_t sz = min(originalBlocks.size(), formattedBlocks.size()); if (sz == 0) { return formatted; } ostringstream os; os << formatted.substr(0, formattedBlocks[0].first); for (size_t i = 0; i < sz; i++) { size_t startAt = originalBlocks[i].first; size_t endAt = originalBlocks[i].second; size_t nextFormttedBlockStartAt = formattedBlocks[i].second; size_t nextFormttedBlockEndAt = formatted.size(); if (i != sz - 1) { nextFormttedBlockEndAt = formattedBlocks[i + 1].first; } os << original.substr(startAt, endAt - startAt); os << formatted.substr(nextFormttedBlockStartAt, nextFormttedBlockEndAt - nextFormttedBlockStartAt); } return os.str(); } string lua_format(istream& is, const Config& config) { std::ostringstream os; os << is.rdbuf(); string original = os.str(); ANTLRInputStream input(original); string formatted = __format(input, config); return resetContentInDisableFormatBlocks(original, formatted); } string lua_format(const string& str, const Config& config) { ANTLRInputStream input(str); string formatted = __format(input, config); return resetContentInDisableFormatBlocks(str, formatted); }
35.135417
108
0.671509
[ "vector" ]
ce31d349ebb64a389c76d0fa9e05fc2b06697e86
14,006
hpp
C++
src/Command.hpp
TheTasak/StringManipulator
6fe87e0026c2ba70b74becfecc6b3336757dbbb4
[ "MIT" ]
2
2018-09-17T19:50:59.000Z
2019-01-13T21:10:28.000Z
src/Command.hpp
TheTasak/StringManipulator
6fe87e0026c2ba70b74becfecc6b3336757dbbb4
[ "MIT" ]
8
2018-09-20T16:41:05.000Z
2019-08-20T14:57:45.000Z
src/Command.hpp
TheTasak/StringManipulator
6fe87e0026c2ba70b74becfecc6b3336757dbbb4
[ "MIT" ]
null
null
null
#pragma once #include "Utilities.hpp" #include "String.hpp" #include "File.hpp" namespace Command { std::string run(std::string); std::string checkFlag(std::string input) { std::size_t par = input.find(")"); if(par != std::string::npos) { std::string s = input.substr(par+1); std::string flag = s; std::string flagtab[] = {FLAG_FILEINOUT_APP, FLAG_FILEINOUT_ATE, FLAG_FILEINOUT_TRUNC, FLAG_FILEINOUT_DEFAULT, FLAG_FILEIN_DEFAULT, FLAG_FILEOUT_APP, FLAG_FILEOUT_ATE, FLAG_FILEOUT_DEFAULT, FLAG_FILEOUT_TRUNC}; std::size_t foundfirst = flag.find_first_of("?"); std::size_t foundlast = flag.find_last_of("?"); if(foundfirst != std::string::npos && foundlast != std::string::npos) flag.erase(foundfirst,foundlast); for(std::string s : flagtab) if(flag == s) return s; if(flag != "") return FLAG_WRONG; return FLAG_BLANK; } else return FLAG_BLANK; } std::string getFileName(std::string input) { std::size_t found = input.find("?"); if(found == std::string::npos) return ""; std::string s = input.substr(found+1); found = s.find("?"); if(found == std::string::npos) return ""; s.erase(found); return s; } std::string saveToFile(std::string s, std::string content = "") { if(checkFlag(s) == FLAG_FILEOUT_APP || checkFlag(s) == FLAG_FILEOUT_ATE || checkFlag(s) == FLAG_FILEOUT_TRUNC || checkFlag(s) == FLAG_FILEOUT_DEFAULT || checkFlag(s) == FLAG_FILEINOUT_APP || checkFlag(s) == FLAG_FILEINOUT_TRUNC || checkFlag(s) == FLAG_FILEINOUT_DEFAULT || checkFlag(s) == FLAG_FILEINOUT_ATE) { std::string filename = getFileName(s); if(!filename.empty()) File::setFileText(filename,String::lastResult, checkFlag(s)); } else if(content != "") { std::string text = ""; if(content == "!") text = File::setFileText(s,String::lastResult); else if(content == "$") text = File::setFileText(s,String::container); else text = File::setFileText(s,content); return text; } return ""; } void commandShow() { std::string file = File::getFileText(COMMAND_FILEPATH); Out::print(file); } template <typename T> void resultUpdate(std::string (*pointer)(T), std::string one) { if(one == LAST_RESULT && String::lastResult != "") String::lastResult = pointer(String::lastResult); else if(one == CONTAINER && String::container != "") String::lastResult = pointer(String::container); else String::lastResult = pointer(one); } template <typename T> void resultUpdate(std::string (*pointer)(T,T), std::string one, std::string two) { std::string o_1 = (one == LAST_RESULT && String::lastResult != "") ? String::lastResult : one; if(one == CONTAINER) o_1 = String::container; std::string o_2 = (two == LAST_RESULT && String::lastResult != "") ? String::lastResult : two; if(two == CONTAINER) o_2 = String::container; String::lastResult = pointer(o_1,o_2); } template <typename T> void resultUpdate(std::string (*pointer)(T,T,T), std::string one, std::string two,std::string three) { std::string o_1 = (one == LAST_RESULT && String::lastResult != "") ? String::lastResult : one; if(one == CONTAINER) o_1 = String::container; std::string o_2 = (two == LAST_RESULT && String::lastResult != "") ? String::lastResult : two; if(two == CONTAINER) o_2 = String::container; std::string o_3 = (three == LAST_RESULT && String::lastResult != "") ? String::lastResult : three; if(three == CONTAINER) o_3 = String::container; String::lastResult = pointer(o_1,o_2,o_3); } void command(std::string s,std::string type,int arguments = 1) { std::size_t beginstr = s.find_first_of("("); std::size_t endstr = s.find_last_of(")"); std::string first; if(arguments == 1) { if(beginstr != std::string::npos && endstr != std::string::npos) { first = s.substr(beginstr+1, endstr - beginstr - 1); std::string (*pointer)(std::string); if(type == UPPER) pointer = &String::to_upper; else if(type == LOWER) pointer = &String::to_lower; else if(type == IS_DIGIT) pointer = &String::is_digit; else if(type == IS_PRIME) pointer = &String::is_prime; else if(type == REVERSE) pointer = &String::reverse; else if(type == FILE_GET) pointer = &File::getFileText; else if(type == LEN) pointer = &String::length; else if(type == TO_OPPOSITE) pointer = &String::to_opposite; else if(type == FACTORIAL) pointer = &String::factorial; else if(type == PASSWORD_GEN) pointer = &String::passwordGen; else if(type == TEXT_GEN) pointer = &String::textGen; else if(type == SET_CONTAINER) pointer = &String::setContainer; else if(type == WORD_COUNT) pointer = &String::wordCount; else if(type == TO_ASCII) pointer = &String::to_ascii; else if(type == TO_TEXT) pointer = &String::to_text; else if(type == RUN) pointer = &Command::run; else if(type == REMOVE_NUM) pointer = &String::removenumbers; else if(type == REMOVE_TEXT) pointer = &String::removetext; else pointer = nullptr; if(checkFlag(s) == FLAG_FILEIN_DEFAULT || checkFlag(s) == FLAG_FILEINOUT_APP || checkFlag(s) == FLAG_FILEINOUT_ATE || checkFlag(s) == FLAG_FILEINOUT_DEFAULT || checkFlag(s) == FLAG_FILEINOUT_TRUNC) first = File::getFileText(first); resultUpdate(pointer,first); saveToFile(s); Out::print(String::lastResult); } else Out::print(ERROR_NOTSPECIFIED); } else if(arguments == 2) { std::size_t comma = s.find(","); if(comma != std::string::npos && beginstr != std::string::npos && endstr != std::string::npos) { first = s.substr(beginstr+1, comma - beginstr - 1); std::string second = s.substr(comma+1, endstr - comma - 1); std::string (*pointer)(std::string,std::string); if(type == MULTIPLY_CHAR) pointer = &String::multiply; else if(type == REMOVE) pointer = &String::remove; else if(type == LIST_PRIME) pointer = &String::listPrime; else if(type == FILE_SAVE) pointer = &Command::saveToFile; else if(type == COUNT) pointer = &String::count; else if(type == ROOT) pointer = &String::root; else if(type == RANDOM) pointer = &String::random; else if(type == SPLIT) pointer = &String::split; else if(type == ROTATE) pointer = &String::rotate; else if(type == REMOVE_NTH) pointer = &String::removenth; else pointer = nullptr; if(checkFlag(s) == FLAG_FILEIN_DEFAULT || checkFlag(s) == FLAG_FILEINOUT_APP || checkFlag(s) == FLAG_FILEINOUT_ATE || checkFlag(s) == FLAG_FILEINOUT_DEFAULT || checkFlag(s) == FLAG_FILEINOUT_TRUNC) first = File::getFileText(first); resultUpdate(pointer,first,second); saveToFile(s); Out::print(String::lastResult); } else Out::print(ERROR_NOTSPECIFIED); } else if(arguments == 3) { std::size_t comma = s.find(","); if(comma != std::string::npos) { std::size_t comma_sec = s.find(",", comma+1); std::string second,third; std::string (*pointer)(std::string,std::string,std::string); if(comma_sec != std::string::npos && beginstr != std::string::npos && endstr != std::string::npos) { first = s.substr(beginstr+1, comma - beginstr - 1); second = s.substr(comma+1, comma_sec - comma - 1); third = s.substr(comma_sec+1, endstr - comma_sec - 1); if(type == REPLACE) pointer = &String::replace; else if(type == RANGE) pointer = &String::range; else if(type == ADD_CHAR) pointer = &String::addChar; else if(type == REMOVE_RANGE) pointer = &String::removerange; else if(type == TO_BASE) pointer = &String::toBase; else pointer = nullptr; if(checkFlag(s) == FLAG_FILEIN_DEFAULT || checkFlag(s) == FLAG_FILEINOUT_APP || checkFlag(s) == FLAG_FILEINOUT_ATE || checkFlag(s) == FLAG_FILEINOUT_DEFAULT || checkFlag(s) == FLAG_FILEINOUT_TRUNC) first = File::getFileText(first); resultUpdate(pointer,first,second,third); saveToFile(s); Out::print(String::lastResult); } else Out::print(ERROR_NOTSPECIFIED); } else Out::print(ERROR_NOTSPECIFIED); } else Out::print(ERROR_NOTSPECIFIED); } void checkCommand(std::string s) { using namespace Command; std::size_t bracket = s.find("("); std::string str = (bracket != std::string::npos) ? s.substr(0,bracket) : s; if(str == FILE_GET) command(s,FILE_GET); else if(str == ADD_CHAR) command(s,ADD_CHAR,3); else if(str == FILE_SAVE) command(s,FILE_SAVE,2); else if(str == MULTIPLY_CHAR) command(s,MULTIPLY_CHAR,2); else if(str == REVERSE) command(s,REVERSE); else if(str == REMOVE) command(s,REMOVE,2); else if(str == REPLACE) command(s,REPLACE,3); else if(str == UPPER) command(s,UPPER); else if(str == LOWER) command(s,LOWER); else if(str == IS_DIGIT) command(s,IS_DIGIT); else if(str == IS_PRIME) command(s,IS_PRIME); else if(str == LIST_PRIME) command(s,LIST_PRIME,2); else if(str == LEN) command(s,LEN); else if(str == RANGE) command(s,RANGE,3); else if(str == COUNT) command(s,COUNT,2); else if(str == ROOT) command(s,ROOT,2); else if(str == RANDOM) command(s,RANDOM,2); else if(str == TO_OPPOSITE) command(s,TO_OPPOSITE); else if(str == FACTORIAL) command(s,FACTORIAL); else if(str == PASSWORD_GEN) command(s,PASSWORD_GEN); else if(str == TEXT_GEN) command(s,TEXT_GEN); else if(str == TO_BASE) command(s,TO_BASE,3); else if(str == RUN) command(s,RUN); else if(str == HELP) commandShow(); else if(str == CLEAR_ACC) String::accumulator = 0; else if(str == SHOW_LAST) Out::print(String::lastResult); else if(str == SHOW_ACC) Out::print(String::accumulator); else if(str == CLEAR_LAST) String::lastResult = ""; else if(str == SET_CONTAINER) command(s,SET_CONTAINER); else if(str == WORD_COUNT) command(s,WORD_COUNT); else if(str == SPLIT) command(s,SPLIT,2); else if(str == ROTATE) command(s,ROTATE,2); else if(str == TO_ASCII) command(s,TO_ASCII); else if(str == TO_TEXT) command(s,TO_TEXT); else if(str == REMOVE_TEXT) command(s,REMOVE_TEXT); else if(str == REMOVE_NUM) command(s,REMOVE_NUM); else if(str == REMOVE_RANGE) command(s,REMOVE_RANGE,3); else if(str == REMOVE_NTH) command(s,REMOVE_NTH,2); else if(str == CLEAR_CONTAINER) String::container = ""; else if(str == SHOW_CONTAINER) Out::print(String::container); //else if(str == LIST_DIR) Out::print(String::ls()); else Out::print(ERROR_COMMAND_NOT_DEFINED); } std::string run(const std::string s) { std::vector<std::string> vec; int previous = 0; std::string result = ""; for(unsigned int i = 0; i < s.size(); i++) { if(s[i] == ';') { std::string push = s.substr(previous,i-previous); if(push[0] == '\n' || push[0] == ' ') push.erase(0,1); vec.push_back(push); previous = i+1; } } for(unsigned int i = 0; i < vec.size(); i++) { Out::print(vec.at(i)+ ": "); checkCommand(vec.at(i)); Out::print("",true); } return result; } }
49.316901
137
0.505426
[ "vector" ]
ce372ef1b84ccdd78c8aca068e6095acdfd08707
697
hpp
C++
VideoCaptureInfoGetter/source/DeviceEnumerator.hpp
mntone/VideoCaptureInfoGetter
2c60dd8ba08df4fbfaaa89e9591466ba8cdae6de
[ "MIT" ]
1
2016-06-04T20:17:08.000Z
2016-06-04T20:17:08.000Z
VideoCaptureInfoGetter/source/DeviceEnumerator.hpp
mntone/VideoCaptureInfoGetter
2c60dd8ba08df4fbfaaa89e9591466ba8cdae6de
[ "MIT" ]
null
null
null
VideoCaptureInfoGetter/source/DeviceEnumerator.hpp
mntone/VideoCaptureInfoGetter
2c60dd8ba08df4fbfaaa89e9591466ba8cdae6de
[ "MIT" ]
null
null
null
#pragma once namespace Mntone { namespace DirectShowSupport { class DeviceEnumerator final { public: DeviceEnumerator(); ::std::vector<::std::wstring> GetDeviceNamesFromCategory(CLSID const& category); ::std::vector<::std::wstring> GetVideoInputDeviceNames(); ::std::vector<::std::wstring> GetAudioInputDeviceNames(); HRESULT TryGetDeviceMoniker(CLSID const& category, ::std::wstring deviceName, IMoniker** moniker) noexcept; HRESULT TryGetVideoInputDeviceMoniker(::std::wstring deviceName, IMoniker** moniker) noexcept; HRESULT TryGetAudioInputDeviceMoniker(::std::wstring deviceName, IMoniker** moniker) noexcept; private: ::Microsoft::WRL::ComPtr<ICreateDevEnum> dev_enum_; }; } }
29.041667
108
0.776184
[ "vector" ]
ce38ebd37db72a312aa551b95f319ef983c10ab8
3,988
hh
C++
src/utils/dataseg_helper.hh
robertu94/cuSZ
fb94ca71172ff6cd19a95f1ea057614d8768b1d2
[ "BSD-3-Clause" ]
null
null
null
src/utils/dataseg_helper.hh
robertu94/cuSZ
fb94ca71172ff6cd19a95f1ea057614d8768b1d2
[ "BSD-3-Clause" ]
null
null
null
src/utils/dataseg_helper.hh
robertu94/cuSZ
fb94ca71172ff6cd19a95f1ea057614d8768b1d2
[ "BSD-3-Clause" ]
null
null
null
/** * @file dataseg_helper.hh * @author Jiannan Tian * @brief * @version 0.3 * @date 2021-10-05 * * (C) 2021 by Washington State University, Argonne National Laboratory * */ #ifndef CUSZ_UTILS_DATASEG_HELPER_HH #define CUSZ_UTILS_DATASEG_HELPER_HH // #include "../common/definition.hh" #include "../header.hh" #include "cuda_mem.cuh" #include <unordered_map> #include <vector> class DataSeg { public: std::unordered_map<cusz::SEG, int> name2order = { {cusz::SEG::HEADER, 0}, {cusz::SEG::BOOK, 1}, {cusz::SEG::QUANT, 2}, {cusz::SEG::REVBOOK, 3}, {cusz::SEG::SPFMT, 4}, {cusz::SEG::HUFF_META, 5}, {cusz::SEG::HUFF_DATA, 6}, // {cusz::SEG::ANCHOR, 7}}; std::unordered_map<int, cusz::SEG> order2name = { {0, cusz::SEG::HEADER}, {1, cusz::SEG::BOOK}, {2, cusz::SEG::QUANT}, {3, cusz::SEG::REVBOOK}, {4, cusz::SEG::SPFMT}, {5, cusz::SEG::HUFF_META}, {6, cusz::SEG::HUFF_DATA}, // {7, cusz::SEG::ANCHOR}}; std::unordered_map<cusz::SEG, uint32_t> nbyte = { {cusz::SEG::HEADER, sizeof(cuszHEADER)}, {cusz::SEG::BOOK, 0U}, {cusz::SEG::QUANT, 0U}, {cusz::SEG::REVBOOK, 0U}, {cusz::SEG::ANCHOR, 0U}, {cusz::SEG::SPFMT, 0U}, {cusz::SEG::HUFF_META, 0U}, {cusz::SEG::HUFF_DATA, 0U}}; std::unordered_map<cusz::SEG, std::string> name2str{ {cusz::SEG::HEADER, "HEADER"}, {cusz::SEG::BOOK, "BOOK"}, {cusz::SEG::QUANT, "QUANT"}, {cusz::SEG::REVBOOK, "REVBOOK"}, {cusz::SEG::ANCHOR, "ANCHOR"}, {cusz::SEG::SPFMT, "SPFMT"}, {cusz::SEG::HUFF_META, "HUFF_META"}, {cusz::SEG::HUFF_DATA, "HUFF_DATA"}}; std::vector<uint32_t> offset; uint32_t get_offset(cusz::SEG name) { return offset.at(name2order.at(name)); } std::string get_namestr(cusz::SEG name) { return name2str.at(name); } }; struct DatasegHelper { using BYTE = uint8_t; static void header_nbyte_from_dataseg(cuszHEADER* header, DataSeg& dataseg) { header->nbyte.book = dataseg.nbyte.at(cusz::SEG::BOOK); header->nbyte.revbook = dataseg.nbyte.at(cusz::SEG::REVBOOK); header->nbyte.spfmt = dataseg.nbyte.at(cusz::SEG::SPFMT); header->nbyte.huff_meta = dataseg.nbyte.at(cusz::SEG::HUFF_META); header->nbyte.huff_data = dataseg.nbyte.at(cusz::SEG::HUFF_DATA); header->nbyte.anchor = dataseg.nbyte.at(cusz::SEG::ANCHOR); } static void dataseg_nbyte_from_header(cuszHEADER* header, DataSeg& dataseg) { dataseg.nbyte.at(cusz::SEG::BOOK) = header->nbyte.book; dataseg.nbyte.at(cusz::SEG::REVBOOK) = header->nbyte.revbook; dataseg.nbyte.at(cusz::SEG::SPFMT) = header->nbyte.spfmt; dataseg.nbyte.at(cusz::SEG::HUFF_META) = header->nbyte.huff_meta; dataseg.nbyte.at(cusz::SEG::HUFF_DATA) = header->nbyte.huff_data; dataseg.nbyte.at(cusz::SEG::ANCHOR) = header->nbyte.anchor; } static void compress_time_conslidate_report(DataSeg& dataseg, std::vector<uint32_t>& offsets) { ReportHelper::print_datasegment_tablehead(); // print long numbers with thousand separator // https://stackoverflow.com/a/7455282 // https://stackoverflow.com/a/11695246 setlocale(LC_ALL, ""); for (auto i = 0; i < 8; i++) { const auto& name = dataseg.order2name.at(i); auto this_nbyte = dataseg.nbyte.at(name); auto o = offsets.back() + __cusz_get_alignable_len<BYTE, 128>(this_nbyte); offsets.push_back(o); if (this_nbyte != 0) printf( " %-18s\t%'12lu\t%'15lu\t%'15lu\n", // dataseg.get_namestr(name).c_str(), // (size_t)this_nbyte, // (size_t)offsets.at(i), // (size_t)offsets.back()); } } }; #endif
37.622642
110
0.579488
[ "vector" ]
ce3c463101e96754a45040c1867ad5cde141928b
8,923
cpp
C++
external/juce/JUCE/modules/juce_graphics/geometry/juce_PathIterator.cpp
ngwese/soundplane
92ed75035694db1a8886e4791aab0a23efff4cc3
[ "MIT" ]
20
2015-01-26T05:34:53.000Z
2022-01-31T07:09:35.000Z
external/juce/JUCE/modules/juce_graphics/geometry/juce_PathIterator.cpp
ngwese/soundplane
92ed75035694db1a8886e4791aab0a23efff4cc3
[ "MIT" ]
35
2015-03-07T18:26:09.000Z
2021-07-16T17:07:32.000Z
external/juce/JUCE/modules/juce_graphics/geometry/juce_PathIterator.cpp
ngwese/soundplane
92ed75035694db1a8886e4791aab0a23efff4cc3
[ "MIT" ]
8
2015-03-10T08:44:04.000Z
2021-01-04T00:31:12.000Z
/* ============================================================================== This file is part of the JUCE library. Copyright (c) 2015 - ROLI Ltd. Permission is granted to use this software under the terms of either: a) the GPL v2 (or any later version) b) the Affero GPL v3 Details of these licenses can be found at: www.gnu.org/licenses JUCE 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. ------------------------------------------------------------------------------ To release a closed-source product which uses JUCE, commercial licenses are available: visit www.juce.com for more information. ============================================================================== */ #if JUCE_MSVC && JUCE_DEBUG #pragma optimize ("t", on) #endif const float PathFlatteningIterator::defaultTolerance = 0.6f; //============================================================================== PathFlatteningIterator::PathFlatteningIterator (const Path& path_, const AffineTransform& transform_, const float tolerance) : x2 (0), y2 (0), closesSubPath (false), subPathIndex (-1), path (path_), transform (transform_), points (path_.data.elements), toleranceSquared (tolerance * tolerance), subPathCloseX (0), subPathCloseY (0), isIdentityTransform (transform_.isIdentity()), stackBase (32), index (0), stackSize (32) { stackPos = stackBase; } PathFlatteningIterator::~PathFlatteningIterator() { } bool PathFlatteningIterator::isLastInSubpath() const noexcept { return stackPos == stackBase.getData() && (index >= path.numElements || points [index] == Path::moveMarker); } bool PathFlatteningIterator::next() { x1 = x2; y1 = y2; float x3 = 0; float y3 = 0; float x4 = 0; float y4 = 0; for (;;) { float type; if (stackPos == stackBase) { if (index >= path.numElements) return false; type = points [index++]; if (type != Path::closeSubPathMarker) { x2 = points [index++]; y2 = points [index++]; if (type == Path::quadMarker) { x3 = points [index++]; y3 = points [index++]; if (! isIdentityTransform) transform.transformPoints (x2, y2, x3, y3); } else if (type == Path::cubicMarker) { x3 = points [index++]; y3 = points [index++]; x4 = points [index++]; y4 = points [index++]; if (! isIdentityTransform) transform.transformPoints (x2, y2, x3, y3, x4, y4); } else { if (! isIdentityTransform) transform.transformPoint (x2, y2); } } } else { type = *--stackPos; if (type != Path::closeSubPathMarker) { x2 = *--stackPos; y2 = *--stackPos; if (type == Path::quadMarker) { x3 = *--stackPos; y3 = *--stackPos; } else if (type == Path::cubicMarker) { x3 = *--stackPos; y3 = *--stackPos; x4 = *--stackPos; y4 = *--stackPos; } } } if (type == Path::lineMarker) { ++subPathIndex; closesSubPath = (stackPos == stackBase) && (index < path.numElements) && (points [index] == Path::closeSubPathMarker) && x2 == subPathCloseX && y2 == subPathCloseY; return true; } if (type == Path::quadMarker) { const size_t offset = (size_t) (stackPos - stackBase); if (offset >= stackSize - 10) { stackSize <<= 1; stackBase.realloc (stackSize); stackPos = stackBase + offset; } const float m1x = (x1 + x2) * 0.5f; const float m1y = (y1 + y2) * 0.5f; const float m2x = (x2 + x3) * 0.5f; const float m2y = (y2 + y3) * 0.5f; const float m3x = (m1x + m2x) * 0.5f; const float m3y = (m1y + m2y) * 0.5f; const float errorX = m3x - x2; const float errorY = m3y - y2; if (errorX * errorX + errorY * errorY > toleranceSquared) { *stackPos++ = y3; *stackPos++ = x3; *stackPos++ = m2y; *stackPos++ = m2x; *stackPos++ = Path::quadMarker; *stackPos++ = m3y; *stackPos++ = m3x; *stackPos++ = m1y; *stackPos++ = m1x; *stackPos++ = Path::quadMarker; } else { *stackPos++ = y3; *stackPos++ = x3; *stackPos++ = Path::lineMarker; *stackPos++ = m3y; *stackPos++ = m3x; *stackPos++ = Path::lineMarker; } jassert (stackPos < stackBase + stackSize); } else if (type == Path::cubicMarker) { const size_t offset = (size_t) (stackPos - stackBase); if (offset >= stackSize - 16) { stackSize <<= 1; stackBase.realloc (stackSize); stackPos = stackBase + offset; } const float m1x = (x1 + x2) * 0.5f; const float m1y = (y1 + y2) * 0.5f; const float m2x = (x3 + x2) * 0.5f; const float m2y = (y3 + y2) * 0.5f; const float m3x = (x3 + x4) * 0.5f; const float m3y = (y3 + y4) * 0.5f; const float m4x = (m1x + m2x) * 0.5f; const float m4y = (m1y + m2y) * 0.5f; const float m5x = (m3x + m2x) * 0.5f; const float m5y = (m3y + m2y) * 0.5f; const float error1X = m4x - x2; const float error1Y = m4y - y2; const float error2X = m5x - x3; const float error2Y = m5y - y3; if (error1X * error1X + error1Y * error1Y > toleranceSquared || error2X * error2X + error2Y * error2Y > toleranceSquared) { *stackPos++ = y4; *stackPos++ = x4; *stackPos++ = m3y; *stackPos++ = m3x; *stackPos++ = m5y; *stackPos++ = m5x; *stackPos++ = Path::cubicMarker; *stackPos++ = (m4y + m5y) * 0.5f; *stackPos++ = (m4x + m5x) * 0.5f; *stackPos++ = m4y; *stackPos++ = m4x; *stackPos++ = m1y; *stackPos++ = m1x; *stackPos++ = Path::cubicMarker; } else { *stackPos++ = y4; *stackPos++ = x4; *stackPos++ = Path::lineMarker; *stackPos++ = m5y; *stackPos++ = m5x; *stackPos++ = Path::lineMarker; *stackPos++ = m4y; *stackPos++ = m4x; *stackPos++ = Path::lineMarker; } } else if (type == Path::closeSubPathMarker) { if (x2 != subPathCloseX || y2 != subPathCloseY) { x1 = x2; y1 = y2; x2 = subPathCloseX; y2 = subPathCloseY; closesSubPath = true; return true; } } else { jassert (type == Path::moveMarker); subPathIndex = -1; subPathCloseX = x1 = x2; subPathCloseY = y1 = y2; } } } #if JUCE_MSVC && JUCE_DEBUG #pragma optimize ("", on) // resets optimisations to the project defaults #endif
31.090592
83
0.408271
[ "transform" ]
ce41d713c7d1981135be83f06ff2b099f1225fd8
19,526
cpp
C++
3rdparty/eigen-eigen-c58038c56923/test/sparse_basic.cpp
kassemitani/openbr
7b453f7abc6f997839a858f4b7686bc5e21ef7b2
[ "Apache-2.0" ]
156
2018-10-09T09:01:42.000Z
2019-12-25T09:07:47.000Z
3rdparty/eigen-eigen-c58038c56923/test/sparse_basic.cpp
kassemitani/openbr
7b453f7abc6f997839a858f4b7686bc5e21ef7b2
[ "Apache-2.0" ]
10
2018-10-12T11:54:58.000Z
2019-10-11T03:29:20.000Z
3rdparty/eigen-eigen-c58038c56923/test/sparse_basic.cpp
kassemitani/openbr
7b453f7abc6f997839a858f4b7686bc5e21ef7b2
[ "Apache-2.0" ]
64
2016-11-04T16:03:03.000Z
2018-07-20T18:03:00.000Z
// This file is part of Eigen, a lightweight C++ template library // for linear algebra. // // Copyright (C) 2008-2011 Gael Guennebaud <gael.guennebaud@inria.fr> // Copyright (C) 2008 Daniel Gomez Ferro <dgomezferro@gmail.com> // Copyright (C) 2013 Désiré Nuentsa-Wakam <desire.nuentsa_wakam@inria.fr> // // This Source Code Form is subject to the terms of the Mozilla // Public License v. 2.0. If a copy of the MPL was not distributed // with this file, You can obtain one at http://mozilla.org/MPL/2.0/. #include "sparse.h" template<typename SparseMatrixType> void sparse_basic(const SparseMatrixType& ref) { typedef typename SparseMatrixType::Index Index; typedef Matrix<Index,2,1> Vector2; const Index rows = ref.rows(); const Index cols = ref.cols(); typedef typename SparseMatrixType::Scalar Scalar; enum { Flags = SparseMatrixType::Flags }; double density = (std::max)(8./(rows*cols), 0.01); typedef Matrix<Scalar,Dynamic,Dynamic> DenseMatrix; typedef Matrix<Scalar,Dynamic,1> DenseVector; typedef Matrix<Scalar,1,Dynamic> RowDenseVector; Scalar eps = 1e-6; Scalar s1 = internal::random<Scalar>(); { SparseMatrixType m(rows, cols); DenseMatrix refMat = DenseMatrix::Zero(rows, cols); DenseVector vec1 = DenseVector::Random(rows); std::vector<Vector2> zeroCoords; std::vector<Vector2> nonzeroCoords; initSparse<Scalar>(density, refMat, m, 0, &zeroCoords, &nonzeroCoords); if (zeroCoords.size()==0 || nonzeroCoords.size()==0) return; // test coeff and coeffRef for (int i=0; i<(int)zeroCoords.size(); ++i) { VERIFY_IS_MUCH_SMALLER_THAN( m.coeff(zeroCoords[i].x(),zeroCoords[i].y()), eps ); if(internal::is_same<SparseMatrixType,SparseMatrix<Scalar,Flags> >::value) VERIFY_RAISES_ASSERT( m.coeffRef(zeroCoords[0].x(),zeroCoords[0].y()) = 5 ); } VERIFY_IS_APPROX(m, refMat); m.coeffRef(nonzeroCoords[0].x(), nonzeroCoords[0].y()) = Scalar(5); refMat.coeffRef(nonzeroCoords[0].x(), nonzeroCoords[0].y()) = Scalar(5); VERIFY_IS_APPROX(m, refMat); // test InnerIterators and Block expressions for (int t=0; t<10; ++t) { int j = internal::random<int>(0,cols-1); int i = internal::random<int>(0,rows-1); int w = internal::random<int>(1,cols-j-1); int h = internal::random<int>(1,rows-i-1); VERIFY_IS_APPROX(m.block(i,j,h,w), refMat.block(i,j,h,w)); for(int c=0; c<w; c++) { VERIFY_IS_APPROX(m.block(i,j,h,w).col(c), refMat.block(i,j,h,w).col(c)); for(int r=0; r<h; r++) { VERIFY_IS_APPROX(m.block(i,j,h,w).col(c).coeff(r), refMat.block(i,j,h,w).col(c).coeff(r)); VERIFY_IS_APPROX(m.block(i,j,h,w).coeff(r,c), refMat.block(i,j,h,w).coeff(r,c)); } } for(int r=0; r<h; r++) { VERIFY_IS_APPROX(m.block(i,j,h,w).row(r), refMat.block(i,j,h,w).row(r)); for(int c=0; c<w; c++) { VERIFY_IS_APPROX(m.block(i,j,h,w).row(r).coeff(c), refMat.block(i,j,h,w).row(r).coeff(c)); VERIFY_IS_APPROX(m.block(i,j,h,w).coeff(r,c), refMat.block(i,j,h,w).coeff(r,c)); } } VERIFY_IS_APPROX(m.middleCols(j,w), refMat.middleCols(j,w)); VERIFY_IS_APPROX(m.middleRows(i,h), refMat.middleRows(i,h)); for(int r=0; r<h; r++) { VERIFY_IS_APPROX(m.middleCols(j,w).row(r), refMat.middleCols(j,w).row(r)); VERIFY_IS_APPROX(m.middleRows(i,h).row(r), refMat.middleRows(i,h).row(r)); for(int c=0; c<w; c++) { VERIFY_IS_APPROX(m.col(c).coeff(r), refMat.col(c).coeff(r)); VERIFY_IS_APPROX(m.row(r).coeff(c), refMat.row(r).coeff(c)); VERIFY_IS_APPROX(m.middleCols(j,w).coeff(r,c), refMat.middleCols(j,w).coeff(r,c)); VERIFY_IS_APPROX(m.middleRows(i,h).coeff(r,c), refMat.middleRows(i,h).coeff(r,c)); if(m.middleCols(j,w).coeff(r,c) != Scalar(0)) { VERIFY_IS_APPROX(m.middleCols(j,w).coeffRef(r,c), refMat.middleCols(j,w).coeff(r,c)); } if(m.middleRows(i,h).coeff(r,c) != Scalar(0)) { VERIFY_IS_APPROX(m.middleRows(i,h).coeff(r,c), refMat.middleRows(i,h).coeff(r,c)); } } } for(int c=0; c<w; c++) { VERIFY_IS_APPROX(m.middleCols(j,w).col(c), refMat.middleCols(j,w).col(c)); VERIFY_IS_APPROX(m.middleRows(i,h).col(c), refMat.middleRows(i,h).col(c)); } } for(int c=0; c<cols; c++) { VERIFY_IS_APPROX(m.col(c) + m.col(c), (m + m).col(c)); VERIFY_IS_APPROX(m.col(c) + m.col(c), refMat.col(c) + refMat.col(c)); } for(int r=0; r<rows; r++) { VERIFY_IS_APPROX(m.row(r) + m.row(r), (m + m).row(r)); VERIFY_IS_APPROX(m.row(r) + m.row(r), refMat.row(r) + refMat.row(r)); } // test assertion VERIFY_RAISES_ASSERT( m.coeffRef(-1,1) = 0 ); VERIFY_RAISES_ASSERT( m.coeffRef(0,m.cols()) = 0 ); } // test insert (inner random) { DenseMatrix m1(rows,cols); m1.setZero(); SparseMatrixType m2(rows,cols); if(internal::random<int>()%2) m2.reserve(VectorXi::Constant(m2.outerSize(), 2)); for (Index j=0; j<cols; ++j) { for (Index k=0; k<rows/2; ++k) { Index i = internal::random<Index>(0,rows-1); if (m1.coeff(i,j)==Scalar(0)) m2.insert(i,j) = m1(i,j) = internal::random<Scalar>(); } } m2.finalize(); VERIFY_IS_APPROX(m2,m1); } // test insert (fully random) { DenseMatrix m1(rows,cols); m1.setZero(); SparseMatrixType m2(rows,cols); if(internal::random<int>()%2) m2.reserve(VectorXi::Constant(m2.outerSize(), 2)); for (int k=0; k<rows*cols; ++k) { Index i = internal::random<Index>(0,rows-1); Index j = internal::random<Index>(0,cols-1); if ((m1.coeff(i,j)==Scalar(0)) && (internal::random<int>()%2)) m2.insert(i,j) = m1(i,j) = internal::random<Scalar>(); else { Scalar v = internal::random<Scalar>(); m2.coeffRef(i,j) += v; m1(i,j) += v; } } VERIFY_IS_APPROX(m2,m1); } // test insert (un-compressed) for(int mode=0;mode<4;++mode) { DenseMatrix m1(rows,cols); m1.setZero(); SparseMatrixType m2(rows,cols); VectorXi r(VectorXi::Constant(m2.outerSize(), ((mode%2)==0) ? m2.innerSize() : std::max<int>(1,m2.innerSize()/8))); m2.reserve(r); for (int k=0; k<rows*cols; ++k) { Index i = internal::random<Index>(0,rows-1); Index j = internal::random<Index>(0,cols-1); if (m1.coeff(i,j)==Scalar(0)) m2.insert(i,j) = m1(i,j) = internal::random<Scalar>(); if(mode==3) m2.reserve(r); } if(internal::random<int>()%2) m2.makeCompressed(); VERIFY_IS_APPROX(m2,m1); } // test innerVector() { DenseMatrix refMat2 = DenseMatrix::Zero(rows, rows); SparseMatrixType m2(rows, rows); initSparse<Scalar>(density, refMat2, m2); Index j0 = internal::random<Index>(0,rows-1); Index j1 = internal::random<Index>(0,rows-1); if(SparseMatrixType::IsRowMajor) VERIFY_IS_APPROX(m2.innerVector(j0), refMat2.row(j0)); else VERIFY_IS_APPROX(m2.innerVector(j0), refMat2.col(j0)); if(SparseMatrixType::IsRowMajor) VERIFY_IS_APPROX(m2.innerVector(j0)+m2.innerVector(j1), refMat2.row(j0)+refMat2.row(j1)); else VERIFY_IS_APPROX(m2.innerVector(j0)+m2.innerVector(j1), refMat2.col(j0)+refMat2.col(j1)); SparseMatrixType m3(rows,rows); m3.reserve(VectorXi::Constant(rows,rows/2)); for(Index j=0; j<rows; ++j) for(Index k=0; k<j; ++k) m3.insertByOuterInner(j,k) = k+1; for(Index j=0; j<rows; ++j) { VERIFY(j==numext::real(m3.innerVector(j).nonZeros())); if(j>0) VERIFY(j==numext::real(m3.innerVector(j).lastCoeff())); } m3.makeCompressed(); for(Index j=0; j<rows; ++j) { VERIFY(j==numext::real(m3.innerVector(j).nonZeros())); if(j>0) VERIFY(j==numext::real(m3.innerVector(j).lastCoeff())); } //m2.innerVector(j0) = 2*m2.innerVector(j1); //refMat2.col(j0) = 2*refMat2.col(j1); //VERIFY_IS_APPROX(m2, refMat2); } // test innerVectors() { DenseMatrix refMat2 = DenseMatrix::Zero(rows, rows); SparseMatrixType m2(rows, rows); initSparse<Scalar>(density, refMat2, m2); if(internal::random<float>(0,1)>0.5) m2.makeCompressed(); Index j0 = internal::random<Index>(0,rows-2); Index j1 = internal::random<Index>(0,rows-2); Index n0 = internal::random<Index>(1,rows-(std::max)(j0,j1)); if(SparseMatrixType::IsRowMajor) VERIFY_IS_APPROX(m2.innerVectors(j0,n0), refMat2.block(j0,0,n0,cols)); else VERIFY_IS_APPROX(m2.innerVectors(j0,n0), refMat2.block(0,j0,rows,n0)); if(SparseMatrixType::IsRowMajor) VERIFY_IS_APPROX(m2.innerVectors(j0,n0)+m2.innerVectors(j1,n0), refMat2.middleRows(j0,n0)+refMat2.middleRows(j1,n0)); else VERIFY_IS_APPROX(m2.innerVectors(j0,n0)+m2.innerVectors(j1,n0), refMat2.block(0,j0,rows,n0)+refMat2.block(0,j1,rows,n0)); VERIFY_IS_APPROX(m2, refMat2); m2.innerVectors(j0,n0) = m2.innerVectors(j0,n0) + m2.innerVectors(j1,n0); if(SparseMatrixType::IsRowMajor) refMat2.middleRows(j0,n0) = (refMat2.middleRows(j0,n0) + refMat2.middleRows(j1,n0)).eval(); else refMat2.middleCols(j0,n0) = (refMat2.middleCols(j0,n0) + refMat2.middleCols(j1,n0)).eval(); VERIFY_IS_APPROX(m2, refMat2); } // test basic computations { DenseMatrix refM1 = DenseMatrix::Zero(rows, rows); DenseMatrix refM2 = DenseMatrix::Zero(rows, rows); DenseMatrix refM3 = DenseMatrix::Zero(rows, rows); DenseMatrix refM4 = DenseMatrix::Zero(rows, rows); SparseMatrixType m1(rows, rows); SparseMatrixType m2(rows, rows); SparseMatrixType m3(rows, rows); SparseMatrixType m4(rows, rows); initSparse<Scalar>(density, refM1, m1); initSparse<Scalar>(density, refM2, m2); initSparse<Scalar>(density, refM3, m3); initSparse<Scalar>(density, refM4, m4); VERIFY_IS_APPROX(m1+m2, refM1+refM2); VERIFY_IS_APPROX(m1+m2+m3, refM1+refM2+refM3); VERIFY_IS_APPROX(m3.cwiseProduct(m1+m2), refM3.cwiseProduct(refM1+refM2)); VERIFY_IS_APPROX(m1*s1-m2, refM1*s1-refM2); VERIFY_IS_APPROX(m1*=s1, refM1*=s1); VERIFY_IS_APPROX(m1/=s1, refM1/=s1); VERIFY_IS_APPROX(m1+=m2, refM1+=refM2); VERIFY_IS_APPROX(m1-=m2, refM1-=refM2); if(SparseMatrixType::IsRowMajor) VERIFY_IS_APPROX(m1.innerVector(0).dot(refM2.row(0)), refM1.row(0).dot(refM2.row(0))); else VERIFY_IS_APPROX(m1.innerVector(0).dot(refM2.row(0)), refM1.col(0).dot(refM2.row(0))); VERIFY_IS_APPROX(m1.conjugate(), refM1.conjugate()); VERIFY_IS_APPROX(m1.real(), refM1.real()); refM4.setRandom(); // sparse cwise* dense VERIFY_IS_APPROX(m3.cwiseProduct(refM4), refM3.cwiseProduct(refM4)); // VERIFY_IS_APPROX(m3.cwise()/refM4, refM3.cwise()/refM4); // test aliasing VERIFY_IS_APPROX((m1 = -m1), (refM1 = -refM1)); VERIFY_IS_APPROX((m1 = m1.transpose()), (refM1 = refM1.transpose().eval())); VERIFY_IS_APPROX((m1 = -m1.transpose()), (refM1 = -refM1.transpose().eval())); VERIFY_IS_APPROX((m1 += -m1), (refM1 += -refM1)); } // test transpose { DenseMatrix refMat2 = DenseMatrix::Zero(rows, rows); SparseMatrixType m2(rows, rows); initSparse<Scalar>(density, refMat2, m2); VERIFY_IS_APPROX(m2.transpose().eval(), refMat2.transpose().eval()); VERIFY_IS_APPROX(m2.transpose(), refMat2.transpose()); VERIFY_IS_APPROX(SparseMatrixType(m2.adjoint()), refMat2.adjoint()); } // test generic blocks { DenseMatrix refMat2 = DenseMatrix::Zero(rows, rows); SparseMatrixType m2(rows, rows); initSparse<Scalar>(density, refMat2, m2); Index j0 = internal::random<Index>(0,rows-2); Index j1 = internal::random<Index>(0,rows-2); Index n0 = internal::random<Index>(1,rows-(std::max)(j0,j1)); if(SparseMatrixType::IsRowMajor) VERIFY_IS_APPROX(m2.block(j0,0,n0,cols), refMat2.block(j0,0,n0,cols)); else VERIFY_IS_APPROX(m2.block(0,j0,rows,n0), refMat2.block(0,j0,rows,n0)); if(SparseMatrixType::IsRowMajor) VERIFY_IS_APPROX(m2.block(j0,0,n0,cols)+m2.block(j1,0,n0,cols), refMat2.block(j0,0,n0,cols)+refMat2.block(j1,0,n0,cols)); else VERIFY_IS_APPROX(m2.block(0,j0,rows,n0)+m2.block(0,j1,rows,n0), refMat2.block(0,j0,rows,n0)+refMat2.block(0,j1,rows,n0)); Index i = internal::random<Index>(0,m2.outerSize()-1); if(SparseMatrixType::IsRowMajor) { m2.innerVector(i) = m2.innerVector(i) * s1; refMat2.row(i) = refMat2.row(i) * s1; VERIFY_IS_APPROX(m2,refMat2); } else { m2.innerVector(i) = m2.innerVector(i) * s1; refMat2.col(i) = refMat2.col(i) * s1; VERIFY_IS_APPROX(m2,refMat2); } VERIFY_IS_APPROX(DenseVector(m2.col(j0)), refMat2.col(j0)); VERIFY_IS_APPROX(m2.col(j0), refMat2.col(j0)); VERIFY_IS_APPROX(RowDenseVector(m2.row(j0)), refMat2.row(j0)); VERIFY_IS_APPROX(m2.row(j0), refMat2.row(j0)); VERIFY_IS_APPROX(m2.block(j0,j1,n0,n0), refMat2.block(j0,j1,n0,n0)); VERIFY_IS_APPROX((2*m2).block(j0,j1,n0,n0), (2*refMat2).block(j0,j1,n0,n0)); } // test prune { SparseMatrixType m2(rows, rows); DenseMatrix refM2(rows, rows); refM2.setZero(); int countFalseNonZero = 0; int countTrueNonZero = 0; for (Index j=0; j<m2.outerSize(); ++j) { m2.startVec(j); for (Index i=0; i<m2.innerSize(); ++i) { float x = internal::random<float>(0,1); if (x<0.1) { // do nothing } else if (x<0.5) { countFalseNonZero++; m2.insertBackByOuterInner(j,i) = Scalar(0); } else { countTrueNonZero++; m2.insertBackByOuterInner(j,i) = Scalar(1); if(SparseMatrixType::IsRowMajor) refM2(j,i) = Scalar(1); else refM2(i,j) = Scalar(1); } } } m2.finalize(); VERIFY(countFalseNonZero+countTrueNonZero == m2.nonZeros()); VERIFY_IS_APPROX(m2, refM2); m2.prune(Scalar(1)); VERIFY(countTrueNonZero==m2.nonZeros()); VERIFY_IS_APPROX(m2, refM2); } // test setFromTriplets { typedef Triplet<Scalar,Index> TripletType; std::vector<TripletType> triplets; int ntriplets = rows*cols; triplets.reserve(ntriplets); DenseMatrix refMat(rows,cols); refMat.setZero(); for(int i=0;i<ntriplets;++i) { Index r = internal::random<Index>(0,rows-1); Index c = internal::random<Index>(0,cols-1); Scalar v = internal::random<Scalar>(); triplets.push_back(TripletType(r,c,v)); refMat(r,c) += v; } SparseMatrixType m(rows,cols); m.setFromTriplets(triplets.begin(), triplets.end()); VERIFY_IS_APPROX(m, refMat); } // test triangularView { DenseMatrix refMat2(rows, rows), refMat3(rows, rows); SparseMatrixType m2(rows, rows), m3(rows, rows); initSparse<Scalar>(density, refMat2, m2); refMat3 = refMat2.template triangularView<Lower>(); m3 = m2.template triangularView<Lower>(); VERIFY_IS_APPROX(m3, refMat3); refMat3 = refMat2.template triangularView<Upper>(); m3 = m2.template triangularView<Upper>(); VERIFY_IS_APPROX(m3, refMat3); refMat3 = refMat2.template triangularView<UnitUpper>(); m3 = m2.template triangularView<UnitUpper>(); VERIFY_IS_APPROX(m3, refMat3); refMat3 = refMat2.template triangularView<UnitLower>(); m3 = m2.template triangularView<UnitLower>(); VERIFY_IS_APPROX(m3, refMat3); refMat3 = refMat2.template triangularView<StrictlyUpper>(); m3 = m2.template triangularView<StrictlyUpper>(); VERIFY_IS_APPROX(m3, refMat3); refMat3 = refMat2.template triangularView<StrictlyLower>(); m3 = m2.template triangularView<StrictlyLower>(); VERIFY_IS_APPROX(m3, refMat3); } // test selfadjointView if(!SparseMatrixType::IsRowMajor) { DenseMatrix refMat2(rows, rows), refMat3(rows, rows); SparseMatrixType m2(rows, rows), m3(rows, rows); initSparse<Scalar>(density, refMat2, m2); refMat3 = refMat2.template selfadjointView<Lower>(); m3 = m2.template selfadjointView<Lower>(); VERIFY_IS_APPROX(m3, refMat3); } // test sparseView { DenseMatrix refMat2 = DenseMatrix::Zero(rows, rows); SparseMatrixType m2(rows, rows); initSparse<Scalar>(density, refMat2, m2); VERIFY_IS_APPROX(m2.eval(), refMat2.sparseView().eval()); } // test diagonal { DenseMatrix refMat2 = DenseMatrix::Zero(rows, rows); SparseMatrixType m2(rows, rows); initSparse<Scalar>(density, refMat2, m2); VERIFY_IS_APPROX(m2.diagonal(), refMat2.diagonal().eval()); } // test conservative resize { std::vector< std::pair<Index,Index> > inc; inc.push_back(std::pair<Index,Index>(-3,-2)); inc.push_back(std::pair<Index,Index>(0,0)); inc.push_back(std::pair<Index,Index>(3,2)); inc.push_back(std::pair<Index,Index>(3,0)); inc.push_back(std::pair<Index,Index>(0,3)); for(size_t i = 0; i< inc.size(); i++) { Index incRows = inc[i].first; Index incCols = inc[i].second; SparseMatrixType m1(rows, cols); DenseMatrix refMat1 = DenseMatrix::Zero(rows, cols); initSparse<Scalar>(density, refMat1, m1); m1.conservativeResize(rows+incRows, cols+incCols); refMat1.conservativeResize(rows+incRows, cols+incCols); if (incRows > 0) refMat1.bottomRows(incRows).setZero(); if (incCols > 0) refMat1.rightCols(incCols).setZero(); VERIFY_IS_APPROX(m1, refMat1); // Insert new values if (incRows > 0) m1.insert(m1.rows()-1, 0) = refMat1(refMat1.rows()-1, 0) = 1; if (incCols > 0) m1.insert(0, m1.cols()-1) = refMat1(0, refMat1.cols()-1) = 1; VERIFY_IS_APPROX(m1, refMat1); } } // test Identity matrix { DenseMatrix refMat1 = DenseMatrix::Identity(rows, rows); SparseMatrixType m1(rows, rows); m1.setIdentity(); VERIFY_IS_APPROX(m1, refMat1); } } void test_sparse_basic() { for(int i = 0; i < g_repeat; i++) { int s = Eigen::internal::random<int>(1,50); EIGEN_UNUSED_VARIABLE(s); CALL_SUBTEST_1(( sparse_basic(SparseMatrix<double>(8, 8)) )); CALL_SUBTEST_2(( sparse_basic(SparseMatrix<std::complex<double>, ColMajor>(s, s)) )); CALL_SUBTEST_2(( sparse_basic(SparseMatrix<std::complex<double>, RowMajor>(s, s)) )); CALL_SUBTEST_1(( sparse_basic(SparseMatrix<double>(s, s)) )); CALL_SUBTEST_1(( sparse_basic(SparseMatrix<double,ColMajor,long int>(s, s)) )); CALL_SUBTEST_1(( sparse_basic(SparseMatrix<double,RowMajor,long int>(s, s)) )); CALL_SUBTEST_1(( sparse_basic(SparseMatrix<double,ColMajor,short int>(short(s), short(s))) )); CALL_SUBTEST_1(( sparse_basic(SparseMatrix<double,RowMajor,short int>(short(s), short(s))) )); } }
35.437387
121
0.615385
[ "vector" ]
ce42d60c550ce994ed2b518d013ad4cd9205ffe8
127,489
cpp
C++
CWE-119/source_files/CVE-2013-5596/Firefox_22.0_CVE_2013_5596_image_src_RasterImage.cpp
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
185
2017-12-14T08:18:15.000Z
2022-03-30T02:58:36.000Z
CWE-119/source_files/CVE-2013-5596/Firefox_22.0_CVE_2013_5596_image_src_RasterImage.cpp
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
11
2018-01-30T23:31:20.000Z
2022-01-17T05:03:56.000Z
CWE-119/source_files/CVE-2013-5596/Firefox_22.0_CVE_2013_5596_image_src_RasterImage.cpp
CGCL-codes/VulDeePecker
98610f3e116df97a1e819ffc81fbc7f6f138a8f2
[ "Apache-2.0" ]
87
2018-01-10T08:12:32.000Z
2022-02-19T10:29:31.000Z
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "base/histogram.h" #include "ImageLogging.h" #include "nsComponentManagerUtils.h" #include "imgDecoderObserver.h" #include "nsError.h" #include "Decoder.h" #include "RasterImage.h" #include "nsIInterfaceRequestor.h" #include "nsIInterfaceRequestorUtils.h" #include "nsIMultiPartChannel.h" #include "nsAutoPtr.h" #include "nsStringStream.h" #include "prenv.h" #include "prsystem.h" #include "ImageContainer.h" #include "Layers.h" #include "nsPresContext.h" #include "nsThread.h" #include "nsIThreadPool.h" #include "nsXPCOMCIDInternal.h" #include "nsIObserverService.h" #include "nsPNGDecoder.h" #include "nsGIFDecoder2.h" #include "nsJPEGDecoder.h" #include "nsBMPDecoder.h" #include "nsICODecoder.h" #include "nsIconDecoder.h" #ifdef MOZ_WBMP #include "nsWBMPDecoder.h" #endif #include "gfxContext.h" #include "mozilla/Services.h" #include "mozilla/Preferences.h" #include "mozilla/StandardInteger.h" #include "mozilla/Telemetry.h" #include "mozilla/TimeStamp.h" #include "mozilla/ClearOnShutdown.h" #include "mozilla/gfx/Scale.h" #include "GeckoProfiler.h" #include <algorithm> using namespace mozilla; using namespace mozilla::image; using namespace mozilla::layers; // a mask for flags that will affect the decoding #define DECODE_FLAGS_MASK (imgIContainer::FLAG_DECODE_NO_PREMULTIPLY_ALPHA | imgIContainer::FLAG_DECODE_NO_COLORSPACE_CONVERSION) #define DECODE_FLAGS_DEFAULT 0 /* Accounting for compressed data */ #if defined(PR_LOGGING) static PRLogModuleInfo * GetCompressedImageAccountingLog() { static PRLogModuleInfo *sLog; if (!sLog) sLog = PR_NewLogModule("CompressedImageAccounting"); return sLog; } #else #define GetCompressedImageAccountingLog() #endif // Tweakable progressive decoding parameters. These are initialized to 0 here // because otherwise, we have to initialize them in a static initializer, which // makes us slower to start up. static uint32_t gDecodeBytesAtATime = 0; static uint32_t gMaxMSBeforeYield = 0; static bool gHQDownscaling = false; // This is interpreted as a floating-point value / 1000 static uint32_t gHQDownscalingMinFactor = 1000; static bool gMultithreadedDecoding = true; static int32_t gDecodingThreadLimit = -1; // The number of pixels in a 5 megapixel decoded image. // Equivalent to an example 3125x1600 resolution. static uint32_t gHQUpscalingMaxSize = 20971520; // The maximum number of times any one RasterImage was decoded. This is only // used for statistics. static int32_t sMaxDecodeCount = 0; static void InitPrefCaches() { Preferences::AddUintVarCache(&gDecodeBytesAtATime, "image.mem.decode_bytes_at_a_time", 200000); Preferences::AddUintVarCache(&gMaxMSBeforeYield, "image.mem.max_ms_before_yield", 400); Preferences::AddBoolVarCache(&gHQDownscaling, "image.high_quality_downscaling.enabled", false); Preferences::AddUintVarCache(&gHQDownscalingMinFactor, "image.high_quality_downscaling.min_factor", 1000); Preferences::AddBoolVarCache(&gMultithreadedDecoding, "image.multithreaded_decoding.enabled", true); Preferences::AddIntVarCache(&gDecodingThreadLimit, "image.multithreaded_decoding.limit", -1); Preferences::AddUintVarCache(&gHQUpscalingMaxSize, "image.high_quality_upscaling.max_size", 20971520); } /* We define our own error checking macros here for 2 reasons: * * 1) Most of the failures we encounter here will (hopefully) be * the result of decoding failures (ie, bad data) and not code * failures. As such, we don't want to clutter up debug consoles * with spurious messages about NS_ENSURE_SUCCESS failures. * * 2) We want to set the internal error flag, shutdown properly, * and end up in an error state. * * So this macro should be called when the desired failure behavior * is to put the container into an error state and return failure. * It goes without saying that macro won't compile outside of a * non-static RasterImage method. */ #define LOG_CONTAINER_ERROR \ PR_BEGIN_MACRO \ PR_LOG (GetImgLog(), PR_LOG_ERROR, \ ("RasterImage: [this=%p] Error " \ "detected at line %u for image of " \ "type %s\n", this, __LINE__, \ mSourceDataMimeType.get())); \ PR_END_MACRO #define CONTAINER_ENSURE_SUCCESS(status) \ PR_BEGIN_MACRO \ nsresult _status = status; /* eval once */ \ if (NS_FAILED(_status)) { \ LOG_CONTAINER_ERROR; \ DoError(); \ return _status; \ } \ PR_END_MACRO #define CONTAINER_ENSURE_TRUE(arg, rv) \ PR_BEGIN_MACRO \ if (!(arg)) { \ LOG_CONTAINER_ERROR; \ DoError(); \ return rv; \ } \ PR_END_MACRO static int num_containers; static int num_discardable_containers; static int64_t total_source_bytes; static int64_t discardable_source_bytes; /* Are we globally disabling image discarding? */ static bool DiscardingEnabled() { static bool inited; static bool enabled; if (!inited) { inited = true; enabled = (PR_GetEnv("MOZ_DISABLE_IMAGE_DISCARD") == nullptr); } return enabled; } class ScaleRequest { public: ScaleRequest(RasterImage* aImage, const gfxSize& aScale, imgFrame* aSrcFrame) : scale(aScale) , dstLocked(false) , done(false) , stopped(false) { MOZ_ASSERT(!aSrcFrame->GetIsPaletted()); MOZ_ASSERT(aScale.width > 0 && aScale.height > 0); weakImage = aImage->asWeakPtr(); srcRect = aSrcFrame->GetRect(); nsIntRect dstRect = srcRect; dstRect.ScaleRoundOut(scale.width, scale.height); dstSize = dstRect.Size(); } // This can only be called on the main thread. bool GetSurfaces(imgFrame* srcFrame) { MOZ_ASSERT(NS_IsMainThread()); nsRefPtr<RasterImage> image = weakImage.get(); if (!image) { return false; } bool success = false; if (!dstLocked) { bool srcLocked = NS_SUCCEEDED(srcFrame->LockImageData()); dstLocked = NS_SUCCEEDED(dstFrame->LockImageData()); nsRefPtr<gfxASurface> dstASurf; nsRefPtr<gfxASurface> srcASurf; success = srcLocked && NS_SUCCEEDED(srcFrame->GetSurface(getter_AddRefs(srcASurf))); success = success && dstLocked && NS_SUCCEEDED(dstFrame->GetSurface(getter_AddRefs(dstASurf))); success = success && srcLocked && dstLocked && srcASurf && dstASurf; if (success) { srcSurface = srcASurf->GetAsImageSurface(); dstSurface = dstASurf->GetAsImageSurface(); srcData = srcSurface->Data(); dstData = dstSurface->Data(); srcStride = srcSurface->Stride(); dstStride = dstSurface->Stride(); srcFormat = mozilla::gfx::ImageFormatToSurfaceFormat(srcFrame->GetFormat()); } // We have references to the Thebes surfaces, so we don't need to leave // the source frame (that we don't own) locked. We'll unlock the // destination frame in ReleaseSurfaces(), below. if (srcLocked) { success = NS_SUCCEEDED(srcFrame->UnlockImageData()) && success; } success = success && srcSurface && dstSurface; } return success; } // This can only be called on the main thread. bool ReleaseSurfaces() { MOZ_ASSERT(NS_IsMainThread()); nsRefPtr<RasterImage> image = weakImage.get(); if (!image) { return false; } bool success = false; if (dstLocked) { success = NS_SUCCEEDED(dstFrame->UnlockImageData()); dstLocked = false; srcData = nullptr; dstData = nullptr; srcSurface = nullptr; dstSurface = nullptr; } return success; } // These values may only be touched on the main thread. WeakPtr<RasterImage> weakImage; nsAutoPtr<imgFrame> dstFrame; nsRefPtr<gfxImageSurface> srcSurface; nsRefPtr<gfxImageSurface> dstSurface; // Below are the values that may be touched on the scaling thread. gfxSize scale; uint8_t* srcData; uint8_t* dstData; nsIntRect srcRect; gfxIntSize dstSize; uint32_t srcStride; uint32_t dstStride; mozilla::gfx::SurfaceFormat srcFormat; bool dstLocked; bool done; // This boolean is accessed from both threads simultaneously without locking. // That's safe because stopping a ScaleRequest is strictly an optimization; // if we're not cache-coherent, at worst we'll do extra work. bool stopped; }; class DrawRunner : public nsRunnable { public: DrawRunner(ScaleRequest* request) : mScaleRequest(request) {} NS_IMETHOD Run() { // ScaleWorker is finished with this request, so we can unlock the data now. mScaleRequest->ReleaseSurfaces(); nsRefPtr<RasterImage> image = mScaleRequest->weakImage.get(); if (image) { RasterImage::ScaleStatus status; if (mScaleRequest->done) { status = RasterImage::SCALE_DONE; } else { status = RasterImage::SCALE_INVALID; } image->ScalingDone(mScaleRequest, status); } return NS_OK; } private: /* members */ nsAutoPtr<ScaleRequest> mScaleRequest; }; class ScaleRunner : public nsRunnable { public: ScaleRunner(RasterImage* aImage, const gfxSize& aScale, imgFrame* aSrcFrame) { nsAutoPtr<ScaleRequest> request(new ScaleRequest(aImage, aScale, aSrcFrame)); // Destination is unconditionally ARGB32 because that's what the scaler // outputs. request->dstFrame = new imgFrame(); nsresult rv = request->dstFrame->Init(0, 0, request->dstSize.width, request->dstSize.height, gfxASurface::ImageFormatARGB32); if (NS_FAILED(rv) || !request->GetSurfaces(aSrcFrame)) { return; } aImage->ScalingStart(request); mScaleRequest = request; } NS_IMETHOD Run() { // An alias just for ease of typing ScaleRequest* request = mScaleRequest; if (!request->stopped) { request->done = mozilla::gfx::Scale(request->srcData, request->srcRect.width, request->srcRect.height, request->srcStride, request->dstData, request->dstSize.width, request->dstSize.height, request->dstStride, request->srcFormat); } else { request->done = false; } // OK, we've got a new scaled image. Let's get the main thread to unlock and // redraw it. nsRefPtr<DrawRunner> runner = new DrawRunner(mScaleRequest.forget()); NS_DispatchToMainThread(runner, NS_DISPATCH_NORMAL); return NS_OK; } bool IsOK() const { return !!mScaleRequest; } private: nsAutoPtr<ScaleRequest> mScaleRequest; }; namespace mozilla { namespace image { /* static */ StaticRefPtr<RasterImage::DecodePool> RasterImage::DecodePool::sSingleton; static nsCOMPtr<nsIThread> sScaleWorkerThread = nullptr; #ifndef DEBUG NS_IMPL_THREADSAFE_ISUPPORTS2(RasterImage, imgIContainer, nsIProperties) #else NS_IMPL_THREADSAFE_ISUPPORTS3(RasterImage, imgIContainer, nsIProperties, imgIContainerDebug) #endif //****************************************************************************** RasterImage::RasterImage(imgStatusTracker* aStatusTracker, nsIURI* aURI /* = nullptr */) : ImageResource(aStatusTracker, aURI), // invoke superclass's constructor mSize(0,0), mFrameDecodeFlags(DECODE_FLAGS_DEFAULT), mMultipartDecodedFrame(nullptr), mAnim(nullptr), mLoopCount(-1), mLockCount(0), mDecodeCount(0), #ifdef DEBUG mFramesNotified(0), #endif mDecodingMutex("RasterImage"), mDecoder(nullptr), mBytesDecoded(0), mInDecoder(false), mHasSize(false), mDecodeOnDraw(false), mMultipart(false), mDiscardable(false), mHasSourceData(false), mDecoded(false), mHasBeenDecoded(false), mAnimationFinished(false), mFinishing(false), mInUpdateImageContainer(false), mWantFullDecode(false), mScaleRequest(nullptr) { // Set up the discard tracker node. mDiscardTrackerNode.img = this; Telemetry::GetHistogramById(Telemetry::IMAGE_DECODE_COUNT)->Add(0); // Statistics num_containers++; } //****************************************************************************** RasterImage::~RasterImage() { // Discardable statistics if (mDiscardable) { num_discardable_containers--; discardable_source_bytes -= mSourceData.Length(); PR_LOG (GetCompressedImageAccountingLog(), PR_LOG_DEBUG, ("CompressedImageAccounting: destroying RasterImage %p. " "Total Containers: %d, Discardable containers: %d, " "Total source bytes: %lld, Source bytes for discardable containers %lld", this, num_containers, num_discardable_containers, total_source_bytes, discardable_source_bytes)); } if (mDecoder) { // Kill off our decode request, if it's pending. (If not, this call is // harmless.) MutexAutoLock lock(mDecodingMutex); DecodePool::StopDecoding(this); mDecoder = nullptr; // Unlock the last frame (if we have any). Our invariant is that, while we // have a decoder open, the last frame is always locked. // This would be done in ShutdownDecoder, but since mDecoder is non-null, // we didn't call ShutdownDecoder and we need to do it manually. if (mFrames.Length() > 0) { imgFrame *curframe = mFrames.ElementAt(mFrames.Length() - 1); curframe->UnlockImageData(); } } delete mAnim; for (unsigned int i = 0; i < mFrames.Length(); ++i) delete mFrames[i]; delete mMultipartDecodedFrame; // Total statistics num_containers--; total_source_bytes -= mSourceData.Length(); if (NS_IsMainThread()) { DiscardTracker::Remove(&mDiscardTrackerNode); } } /* static */ void RasterImage::Initialize() { InitPrefCaches(); // Create our singletons now, so we don't have to worry about what thread // they're created on. DecodePool::Singleton(); } nsresult RasterImage::Init(const char* aMimeType, uint32_t aFlags) { // We don't support re-initialization if (mInitialized) return NS_ERROR_ILLEGAL_VALUE; // Not sure an error can happen before init, but be safe if (mError) return NS_ERROR_FAILURE; NS_ENSURE_ARG_POINTER(aMimeType); // We must be non-discardable and non-decode-on-draw for // multipart channels NS_ABORT_IF_FALSE(!(aFlags & INIT_FLAG_MULTIPART) || (!(aFlags & INIT_FLAG_DISCARDABLE) && !(aFlags & INIT_FLAG_DECODE_ON_DRAW)), "Can't be discardable or decode-on-draw for multipart"); // Store initialization data mSourceDataMimeType.Assign(aMimeType); mDiscardable = !!(aFlags & INIT_FLAG_DISCARDABLE); mDecodeOnDraw = !!(aFlags & INIT_FLAG_DECODE_ON_DRAW); mMultipart = !!(aFlags & INIT_FLAG_MULTIPART); // Statistics if (mDiscardable) { num_discardable_containers++; discardable_source_bytes += mSourceData.Length(); } // If we're being called from ExtractFrame (used by borderimage), // we don't actually do any decoding. Bail early. // XXX - This should be removed when we fix borderimage if (mSourceDataMimeType.Length() == 0) { mInitialized = true; return NS_OK; } // Instantiate the decoder nsresult rv = InitDecoder(/* aDoSizeDecode = */ true); CONTAINER_ENSURE_SUCCESS(rv); // If we aren't storing source data, we want to switch from a size decode to // a full decode as soon as possible. if (!StoringSourceData()) { mWantFullDecode = true; } // Mark us as initialized mInitialized = true; return NS_OK; } bool RasterImage::AdvanceFrame(TimeStamp aTime, nsIntRect* aDirtyRect) { NS_ASSERTION(aTime <= TimeStamp::Now(), "Given time appears to be in the future"); imgFrame* nextFrame = nullptr; uint32_t currentFrameIndex = mAnim->currentAnimationFrameIndex; uint32_t nextFrameIndex = mAnim->currentAnimationFrameIndex + 1; uint32_t timeout = 0; // Figure out if we have the next full frame. This is more complicated than // just checking for mFrames.Length() because decoders append their frames // before they're filled in. NS_ABORT_IF_FALSE(mDecoder || nextFrameIndex <= mFrames.Length(), "How did we get 2 indices too far by incrementing?"); // If we don't have a decoder, we know we've got everything we're going to // get. If we do, we only display fully-downloaded frames; everything else // gets delayed. bool haveFullNextFrame = (mMultipart && mBytesDecoded == 0) || !mDecoder || nextFrameIndex < mDecoder->GetCompleteFrameCount(); // If we're done decoding the next frame, go ahead and display it now and // reinit with the next frame's delay time. if (haveFullNextFrame) { if (mFrames.Length() == nextFrameIndex) { // End of Animation, unless we are looping forever // If animation mode is "loop once", it's time to stop animating if (mAnimationMode == kLoopOnceAnimMode || mLoopCount == 0) { mAnimationFinished = true; EvaluateAnimation(); } // We may have used compositingFrame to build a frame, and then copied // it back into mFrames[..]. If so, delete composite to save memory if (mAnim->compositingFrame && mAnim->lastCompositedFrameIndex == -1) { mAnim->compositingFrame = nullptr; } nextFrameIndex = 0; if (mLoopCount > 0) { mLoopCount--; } if (!mAnimating) { // break out early if we are actually done animating return false; } } if (!(nextFrame = mFrames[nextFrameIndex])) { // something wrong with the next frame, skip it mAnim->currentAnimationFrameIndex = nextFrameIndex; return false; } timeout = nextFrame->GetTimeout(); } else { // Uh oh, the frame we want to show is currently being decoded (partial) // Wait until the next refresh driver tick and try again return false; } if (!(timeout > 0)) { mAnimationFinished = true; EvaluateAnimation(); } if (nextFrameIndex == 0) { *aDirtyRect = mAnim->firstFrameRefreshArea; } else { imgFrame *curFrame = mFrames[currentFrameIndex]; if (!curFrame) { return false; } // Change frame if (NS_FAILED(DoComposite(aDirtyRect, curFrame, nextFrame, nextFrameIndex))) { // something went wrong, move on to next NS_WARNING("RasterImage::AdvanceFrame(): Compositing of frame failed"); nextFrame->SetCompositingFailed(true); mAnim->currentAnimationFrameIndex = nextFrameIndex; mAnim->currentAnimationFrameTime = aTime; return false; } nextFrame->SetCompositingFailed(false); } // Set currentAnimationFrameIndex at the last possible moment mAnim->currentAnimationFrameIndex = nextFrameIndex; mAnim->currentAnimationFrameTime = aTime; return true; } //****************************************************************************** // [notxpcom] void requestRefresh ([const] in TimeStamp aTime); NS_IMETHODIMP_(void) RasterImage::RequestRefresh(const mozilla::TimeStamp& aTime) { if (!mAnimating || !ShouldAnimate()) { return; } EnsureAnimExists(); // only advance the frame if the current time is greater than or // equal to the current frame's end time. TimeStamp currentFrameEndTime = GetCurrentImgFrameEndTime(); bool frameAdvanced = false; // The dirtyRect variable will contain an accumulation of the sub-rectangles // that are dirty for each frame we advance in AdvanceFrame(). nsIntRect dirtyRect; while (currentFrameEndTime <= aTime) { TimeStamp oldFrameEndTime = currentFrameEndTime; nsIntRect frameDirtyRect; bool didAdvance = AdvanceFrame(aTime, &frameDirtyRect); frameAdvanced = frameAdvanced || didAdvance; currentFrameEndTime = GetCurrentImgFrameEndTime(); // Accumulate the dirty area. dirtyRect = dirtyRect.Union(frameDirtyRect); // if we didn't advance a frame, and our frame end time didn't change, // then we need to break out of this loop & wait for the frame(s) // to finish downloading if (!frameAdvanced && (currentFrameEndTime == oldFrameEndTime)) { break; } } if (frameAdvanced) { // Notify listeners that our frame has actually changed, but do this only // once for all frames that we've now passed (if AdvanceFrame() was called // more than once). #ifdef DEBUG mFramesNotified++; #endif UpdateImageContainer(); // Explicitly call this on mStatusTracker so we're sure to not interfere // with the decoding process if (mStatusTracker) mStatusTracker->FrameChanged(&dirtyRect); } } //****************************************************************************** /* [noscript] imgIContainer extractFrame(uint32_t aWhichFrame, * [const] in nsIntRect aRegion, * in uint32_t aFlags); */ NS_IMETHODIMP RasterImage::ExtractFrame(uint32_t aWhichFrame, const nsIntRect &aRegion, uint32_t aFlags, imgIContainer **_retval) { NS_ENSURE_ARG_POINTER(_retval); nsresult rv; if (aWhichFrame > FRAME_MAX_VALUE) return NS_ERROR_INVALID_ARG; if (mError) return NS_ERROR_FAILURE; // Disallowed in the API if (mInDecoder && (aFlags & imgIContainer::FLAG_SYNC_DECODE)) return NS_ERROR_FAILURE; // Make a new container. This should switch to another class with bug 505959. nsRefPtr<RasterImage> img(new RasterImage()); // We don't actually have a mimetype in this case. The empty string tells the // init routine not to try to instantiate a decoder. This should be fixed in // bug 505959. img->Init("", INIT_FLAG_NONE); img->SetSize(aRegion.width, aRegion.height); img->mDecoded = true; // Also, we need to mark the image as decoded img->mHasBeenDecoded = true; img->mFrameDecodeFlags = aFlags & DECODE_FLAGS_MASK; if (!ApplyDecodeFlags(aFlags)) return NS_ERROR_NOT_AVAILABLE; // If a synchronous decode was requested, do it if (aFlags & FLAG_SYNC_DECODE) { rv = SyncDecode(); CONTAINER_ENSURE_SUCCESS(rv); } // Get the frame. If it's not there, it's probably the caller's fault for // not waiting for the data to be loaded from the network or not passing // FLAG_SYNC_DECODE uint32_t frameIndex = (aWhichFrame == FRAME_FIRST) ? 0 : GetCurrentImgFrameIndex(); imgFrame *frame = GetDrawableImgFrame(frameIndex); if (!frame) { *_retval = nullptr; return NS_ERROR_FAILURE; } // The frame can be smaller than the image. We want to extract only the part // of the frame that actually exists. nsIntRect framerect = frame->GetRect(); framerect.IntersectRect(framerect, aRegion); if (framerect.IsEmpty()) return NS_ERROR_NOT_AVAILABLE; nsAutoPtr<imgFrame> subframe; rv = frame->Extract(framerect, getter_Transfers(subframe)); if (NS_FAILED(rv)) return rv; img->mFrames.AppendElement(subframe.forget()); img->mStatusTracker->RecordLoaded(); img->mStatusTracker->RecordDecoded(); *_retval = img.forget().get(); return NS_OK; } //****************************************************************************** /* readonly attribute int32_t width; */ NS_IMETHODIMP RasterImage::GetWidth(int32_t *aWidth) { NS_ENSURE_ARG_POINTER(aWidth); if (mError) { *aWidth = 0; return NS_ERROR_FAILURE; } *aWidth = mSize.width; return NS_OK; } //****************************************************************************** /* readonly attribute int32_t height; */ NS_IMETHODIMP RasterImage::GetHeight(int32_t *aHeight) { NS_ENSURE_ARG_POINTER(aHeight); if (mError) { *aHeight = 0; return NS_ERROR_FAILURE; } *aHeight = mSize.height; return NS_OK; } //****************************************************************************** /* [noscript] readonly attribute nsSize intrinsicSize; */ NS_IMETHODIMP RasterImage::GetIntrinsicSize(nsSize* aSize) { if (mError) return NS_ERROR_FAILURE; *aSize = nsSize(nsPresContext::CSSPixelsToAppUnits(mSize.width), nsPresContext::CSSPixelsToAppUnits(mSize.height)); return NS_OK; } //****************************************************************************** /* [noscript] readonly attribute nsSize intrinsicRatio; */ NS_IMETHODIMP RasterImage::GetIntrinsicRatio(nsSize* aRatio) { if (mError) return NS_ERROR_FAILURE; *aRatio = nsSize(mSize.width, mSize.height); return NS_OK; } //****************************************************************************** /* unsigned short GetType(); */ NS_IMETHODIMP RasterImage::GetType(uint16_t *aType) { NS_ENSURE_ARG_POINTER(aType); *aType = GetType(); return NS_OK; } //****************************************************************************** /* [noscript, notxpcom] uint16_t GetType(); */ NS_IMETHODIMP_(uint16_t) RasterImage::GetType() { return imgIContainer::TYPE_RASTER; } imgFrame* RasterImage::GetImgFrameNoDecode(uint32_t framenum) { if (!mAnim) { NS_ASSERTION(framenum == 0, "Don't ask for a frame > 0 if we're not animated!"); return mFrames.SafeElementAt(0, nullptr); } if (mAnim->lastCompositedFrameIndex == int32_t(framenum)) return mAnim->compositingFrame; return mFrames.SafeElementAt(framenum, nullptr); } imgFrame* RasterImage::GetImgFrame(uint32_t framenum) { nsresult rv = WantDecodedFrames(); CONTAINER_ENSURE_TRUE(NS_SUCCEEDED(rv), nullptr); return GetImgFrameNoDecode(framenum); } imgFrame* RasterImage::GetDrawableImgFrame(uint32_t framenum) { imgFrame* frame = nullptr; if (mMultipart && framenum == GetCurrentImgFrameIndex()) { // In the multipart case we prefer to use mMultipartDecodedFrame, which is // the most recent one we completely decoded, rather than display the real // current frame and risk severe tearing. frame = mMultipartDecodedFrame; } if (!frame) { frame = GetImgFrame(framenum); } // We will return a paletted frame if it's not marked as compositing failed // so we can catch crashes for reasons we haven't investigated. if (frame && frame->GetCompositingFailed()) return nullptr; return frame; } uint32_t RasterImage::GetCurrentImgFrameIndex() const { if (mAnim) return mAnim->currentAnimationFrameIndex; return 0; } TimeStamp RasterImage::GetCurrentImgFrameEndTime() const { imgFrame* currentFrame = mFrames[mAnim->currentAnimationFrameIndex]; TimeStamp currentFrameTime = mAnim->currentAnimationFrameTime; int64_t timeout = currentFrame->GetTimeout(); if (timeout < 0) { // We need to return a sentinel value in this case, because our logic // doesn't work correctly if we have a negative timeout value. The reason // this positive infinity was chosen was because it works with the loop in // RequestRefresh() above. return TimeStamp() + TimeDuration::FromMilliseconds(static_cast<double>(UINT64_MAX)); } TimeDuration durationOfTimeout = TimeDuration::FromMilliseconds(static_cast<double>(timeout)); TimeStamp currentFrameEndTime = currentFrameTime + durationOfTimeout; return currentFrameEndTime; } imgFrame* RasterImage::GetCurrentImgFrame() { return GetImgFrame(GetCurrentImgFrameIndex()); } imgFrame* RasterImage::GetCurrentDrawableImgFrame() { return GetDrawableImgFrame(GetCurrentImgFrameIndex()); } //****************************************************************************** /* [notxpcom] boolean frameIsOpaque(in uint32_t aWhichFrame); */ NS_IMETHODIMP_(bool) RasterImage::FrameIsOpaque(uint32_t aWhichFrame) { if (aWhichFrame > FRAME_MAX_VALUE) { NS_WARNING("aWhichFrame outside valid range!"); return false; } if (mError) return false; // See if we can get an image frame. imgFrame* frame = aWhichFrame == FRAME_FIRST ? GetImgFrameNoDecode(0) : GetImgFrameNoDecode(GetCurrentImgFrameIndex()); // If we don't get a frame, the safe answer is "not opaque". if (!frame) return false; // Other, the frame is transparent if either: // 1. It needs a background. // 2. Its size doesn't cover our entire area. nsIntRect framerect = frame->GetRect(); return !frame->GetNeedsBackground() && framerect.IsEqualInterior(nsIntRect(0, 0, mSize.width, mSize.height)); } nsIntRect RasterImage::FrameRect(uint32_t aWhichFrame) { if (aWhichFrame > FRAME_MAX_VALUE) { NS_WARNING("aWhichFrame outside valid range!"); return nsIntRect(); } // Get the requested frame. imgFrame* frame = aWhichFrame == FRAME_FIRST ? GetImgFrameNoDecode(0) : GetImgFrameNoDecode(GetCurrentImgFrameIndex()); // If we have the frame, use that rectangle. if (frame) { return frame->GetRect(); } // If the frame doesn't exist, we return the empty rectangle. It's not clear // whether this is appropriate in general, but at the moment the only // consumer of this method is imgStatusTracker (when it wants to figure out // dirty rectangles to send out batched observer updates). This should // probably be revisited when we fix bug 503973. return nsIntRect(); } uint32_t RasterImage::GetCurrentFrameIndex() { return GetCurrentImgFrameIndex(); } uint32_t RasterImage::GetNumFrames() { return mFrames.Length(); } //****************************************************************************** /* readonly attribute boolean animated; */ NS_IMETHODIMP RasterImage::GetAnimated(bool *aAnimated) { if (mError) return NS_ERROR_FAILURE; NS_ENSURE_ARG_POINTER(aAnimated); // If we have mAnim, we can know for sure if (mAnim) { *aAnimated = true; return NS_OK; } // Otherwise, we need to have been decoded to know for sure, since if we were // decoded at least once mAnim would have been created for animated images if (!mHasBeenDecoded) return NS_ERROR_NOT_AVAILABLE; // We know for sure *aAnimated = false; return NS_OK; } nsresult RasterImage::CopyFrame(uint32_t aWhichFrame, uint32_t aFlags, gfxImageSurface **_retval) { if (aWhichFrame > FRAME_MAX_VALUE) return NS_ERROR_INVALID_ARG; if (mError) return NS_ERROR_FAILURE; // Disallowed in the API if (mInDecoder && (aFlags & imgIContainer::FLAG_SYNC_DECODE)) return NS_ERROR_FAILURE; nsresult rv; if (!ApplyDecodeFlags(aFlags)) return NS_ERROR_NOT_AVAILABLE; // If requested, synchronously flush any data we have lying around to the decoder if (aFlags & FLAG_SYNC_DECODE) { rv = SyncDecode(); CONTAINER_ENSURE_SUCCESS(rv); } NS_ENSURE_ARG_POINTER(_retval); // Get the frame. If it's not there, it's probably the caller's fault for // not waiting for the data to be loaded from the network or not passing // FLAG_SYNC_DECODE uint32_t frameIndex = (aWhichFrame == FRAME_FIRST) ? 0 : GetCurrentImgFrameIndex(); imgFrame *frame = GetDrawableImgFrame(frameIndex); if (!frame) { *_retval = nullptr; return NS_ERROR_FAILURE; } nsRefPtr<gfxPattern> pattern; frame->GetPattern(getter_AddRefs(pattern)); nsIntRect intframerect = frame->GetRect(); gfxRect framerect(intframerect.x, intframerect.y, intframerect.width, intframerect.height); // Create a 32-bit image surface of our size, but draw using the frame's // rect, implicitly padding the frame out to the image's size. nsRefPtr<gfxImageSurface> imgsurface = new gfxImageSurface(gfxIntSize(mSize.width, mSize.height), gfxASurface::ImageFormatARGB32); gfxContext ctx(imgsurface); ctx.SetOperator(gfxContext::OPERATOR_SOURCE); ctx.Rectangle(framerect); ctx.Translate(framerect.TopLeft()); ctx.SetPattern(pattern); ctx.Fill(); *_retval = imgsurface.forget().get(); return NS_OK; } //****************************************************************************** /* [noscript] gfxASurface getFrame(in uint32_t aWhichFrame, * in uint32_t aFlags); */ NS_IMETHODIMP RasterImage::GetFrame(uint32_t aWhichFrame, uint32_t aFlags, gfxASurface **_retval) { if (aWhichFrame > FRAME_MAX_VALUE) return NS_ERROR_INVALID_ARG; if (mError) return NS_ERROR_FAILURE; // Disallowed in the API if (mInDecoder && (aFlags & imgIContainer::FLAG_SYNC_DECODE)) return NS_ERROR_FAILURE; nsresult rv = NS_OK; if (!ApplyDecodeFlags(aFlags)) return NS_ERROR_NOT_AVAILABLE; // If the caller requested a synchronous decode, do it if (aFlags & FLAG_SYNC_DECODE) { rv = SyncDecode(); CONTAINER_ENSURE_SUCCESS(rv); } // Get the frame. If it's not there, it's probably the caller's fault for // not waiting for the data to be loaded from the network or not passing // FLAG_SYNC_DECODE uint32_t frameIndex = (aWhichFrame == FRAME_FIRST) ? 0 : GetCurrentImgFrameIndex(); imgFrame *frame = GetDrawableImgFrame(frameIndex); if (!frame) { *_retval = nullptr; return NS_ERROR_FAILURE; } nsRefPtr<gfxASurface> framesurf; // If this frame covers the entire image, we can just reuse its existing // surface. nsIntRect framerect = frame->GetRect(); if (framerect.x == 0 && framerect.y == 0 && framerect.width == mSize.width && framerect.height == mSize.height) rv = frame->GetSurface(getter_AddRefs(framesurf)); // The image doesn't have a surface because it's been optimized away. Create // one. if (!framesurf) { nsRefPtr<gfxImageSurface> imgsurf; rv = CopyFrame(aWhichFrame, aFlags, getter_AddRefs(imgsurf)); framesurf = imgsurf; } *_retval = framesurf.forget().get(); return rv; } already_AddRefed<layers::Image> RasterImage::GetCurrentImage() { if (!mDecoded) { // We can't call StartDecoding because that can synchronously notify // which can cause DOM modification RequestDecode(); return nullptr; } nsRefPtr<gfxASurface> imageSurface; nsresult rv = GetFrame(FRAME_CURRENT, FLAG_NONE, getter_AddRefs(imageSurface)); NS_ENSURE_SUCCESS(rv, nullptr); if (!imageSurface) { return nullptr; } if (!mImageContainer) { mImageContainer = LayerManager::CreateImageContainer(); } CairoImage::Data cairoData; cairoData.mSurface = imageSurface; GetWidth(&cairoData.mSize.width); GetHeight(&cairoData.mSize.height); ImageFormat cairoFormat = CAIRO_SURFACE; nsRefPtr<layers::Image> image = mImageContainer->CreateImage(&cairoFormat, 1); NS_ASSERTION(image, "Failed to create Image"); NS_ASSERTION(image->GetFormat() == cairoFormat, "Wrong format"); static_cast<CairoImage*>(image.get())->SetData(cairoData); return image.forget(); } NS_IMETHODIMP RasterImage::GetImageContainer(LayerManager* aManager, ImageContainer **_retval) { int32_t maxTextureSize = aManager->GetMaxTextureSize(); if (mSize.width > maxTextureSize || mSize.height > maxTextureSize) { *_retval = nullptr; return NS_OK; } if (IsUnlocked() && mStatusTracker) { mStatusTracker->OnUnlockedDraw(); } if (mImageContainer) { *_retval = mImageContainer; NS_ADDREF(*_retval); return NS_OK; } nsRefPtr<layers::Image> image = GetCurrentImage(); if (!image) { return NS_ERROR_NOT_AVAILABLE; } mImageContainer->SetCurrentImageInTransaction(image); *_retval = mImageContainer; NS_ADDREF(*_retval); return NS_OK; } void RasterImage::UpdateImageContainer() { if (!mImageContainer || IsInUpdateImageContainer()) { return; } SetInUpdateImageContainer(true); nsRefPtr<layers::Image> image = GetCurrentImage(); if (!image) { return; } mImageContainer->SetCurrentImage(image); SetInUpdateImageContainer(false); } size_t RasterImage::HeapSizeOfSourceWithComputedFallback(nsMallocSizeOfFun aMallocSizeOf) const { // n == 0 is possible for two reasons. // - This is a zero-length image. // - We're on a platform where moz_malloc_size_of always returns 0. // In either case the fallback works appropriately. size_t n = mSourceData.SizeOfExcludingThis(aMallocSizeOf); if (n == 0) { n = mSourceData.Length(); } return n; } size_t RasterImage::SizeOfDecodedWithComputedFallbackIfHeap(gfxASurface::MemoryLocation aLocation, nsMallocSizeOfFun aMallocSizeOf) const { size_t n = 0; for (uint32_t i = 0; i < mFrames.Length(); ++i) { imgFrame* frame = mFrames.SafeElementAt(i, nullptr); NS_ABORT_IF_FALSE(frame, "Null frame in frame array!"); n += frame->SizeOfExcludingThisWithComputedFallbackIfHeap(aLocation, aMallocSizeOf); } if (mScaleResult.status == SCALE_DONE) { n += mScaleResult.frame->SizeOfExcludingThisWithComputedFallbackIfHeap(aLocation, aMallocSizeOf); } return n; } size_t RasterImage::HeapSizeOfDecodedWithComputedFallback(nsMallocSizeOfFun aMallocSizeOf) const { return SizeOfDecodedWithComputedFallbackIfHeap(gfxASurface::MEMORY_IN_PROCESS_HEAP, aMallocSizeOf); } size_t RasterImage::NonHeapSizeOfDecoded() const { return SizeOfDecodedWithComputedFallbackIfHeap(gfxASurface::MEMORY_IN_PROCESS_NONHEAP, NULL); } size_t RasterImage::OutOfProcessSizeOfDecoded() const { return SizeOfDecodedWithComputedFallbackIfHeap(gfxASurface::MEMORY_OUT_OF_PROCESS, NULL); } void RasterImage::DeleteImgFrame(uint32_t framenum) { NS_ABORT_IF_FALSE(framenum < mFrames.Length(), "Deleting invalid frame!"); delete mFrames[framenum]; mFrames[framenum] = nullptr; } nsresult RasterImage::InternalAddFrameHelper(uint32_t framenum, imgFrame *aFrame, uint8_t **imageData, uint32_t *imageLength, uint32_t **paletteData, uint32_t *paletteLength, imgFrame** aRetFrame) { NS_ABORT_IF_FALSE(framenum <= mFrames.Length(), "Invalid frame index!"); if (framenum > mFrames.Length()) return NS_ERROR_INVALID_ARG; nsAutoPtr<imgFrame> frame(aFrame); // We are in the middle of decoding. This will be unlocked when we finish // decoding or switch to another frame. frame->LockImageData(); if (paletteData && paletteLength) frame->GetPaletteData(paletteData, paletteLength); frame->GetImageData(imageData, imageLength); *aRetFrame = frame; mFrames.InsertElementAt(framenum, frame.forget()); return NS_OK; } nsresult RasterImage::InternalAddFrame(uint32_t framenum, int32_t aX, int32_t aY, int32_t aWidth, int32_t aHeight, gfxASurface::gfxImageFormat aFormat, uint8_t aPaletteDepth, uint8_t **imageData, uint32_t *imageLength, uint32_t **paletteData, uint32_t *paletteLength, imgFrame** aRetFrame) { // We assume that we're in the middle of decoding because we unlock the // previous frame when we create a new frame, and only when decoding do we // lock frames. NS_ABORT_IF_FALSE(mDecoder, "Only decoders may add frames!"); NS_ABORT_IF_FALSE(framenum <= mFrames.Length(), "Invalid frame index!"); if (framenum > mFrames.Length()) return NS_ERROR_INVALID_ARG; nsAutoPtr<imgFrame> frame(new imgFrame()); nsresult rv = frame->Init(aX, aY, aWidth, aHeight, aFormat, aPaletteDepth); NS_ENSURE_SUCCESS(rv, rv); // We know we are in a decoder. Therefore, we must unlock the previous frame // when we move on to decoding into the next frame. if (mFrames.Length() > 0) { imgFrame *prevframe = mFrames.ElementAt(mFrames.Length() - 1); prevframe->UnlockImageData(); } if (mFrames.Length() == 0) { return InternalAddFrameHelper(framenum, frame.forget(), imageData, imageLength, paletteData, paletteLength, aRetFrame); } if (mFrames.Length() == 1) { // Since we're about to add our second frame, initialize animation stuff EnsureAnimExists(); // If we dispose of the first frame by clearing it, then the // First Frame's refresh area is all of itself. // RESTORE_PREVIOUS is invalid (assumed to be DISPOSE_CLEAR) int32_t frameDisposalMethod = mFrames[0]->GetFrameDisposalMethod(); if (frameDisposalMethod == kDisposeClear || frameDisposalMethod == kDisposeRestorePrevious) mAnim->firstFrameRefreshArea = mFrames[0]->GetRect(); } // Calculate firstFrameRefreshArea // Some gifs are huge but only have a small area that they animate // We only need to refresh that small area when Frame 0 comes around again nsIntRect frameRect = frame->GetRect(); mAnim->firstFrameRefreshArea.UnionRect(mAnim->firstFrameRefreshArea, frameRect); rv = InternalAddFrameHelper(framenum, frame.forget(), imageData, imageLength, paletteData, paletteLength, aRetFrame); // We may be able to start animating, if we now have enough frames EvaluateAnimation(); return rv; } bool RasterImage::ApplyDecodeFlags(uint32_t aNewFlags) { if (mFrameDecodeFlags == (aNewFlags & DECODE_FLAGS_MASK)) return true; // Not asking very much of us here. if (mDecoded) { // if we can't discard, then we're screwed; we have no way // to re-decode. Similarly if we aren't allowed to do a sync // decode. if (!(aNewFlags & FLAG_SYNC_DECODE)) return false; if (!CanForciblyDiscard() || mDecoder || mAnim) return false; ForceDiscard(); } mFrameDecodeFlags = aNewFlags & DECODE_FLAGS_MASK; return true; } nsresult RasterImage::SetSize(int32_t aWidth, int32_t aHeight) { MOZ_ASSERT(NS_IsMainThread()); if (mError) return NS_ERROR_FAILURE; // Ensure that we have positive values // XXX - Why isn't the size unsigned? Should this be changed? if ((aWidth < 0) || (aHeight < 0)) return NS_ERROR_INVALID_ARG; // if we already have a size, check the new size against the old one if (!mMultipart && mHasSize && ((aWidth != mSize.width) || (aHeight != mSize.height))) { NS_WARNING("Image changed size on redecode! This should not happen!"); // Make the decoder aware of the error so that it doesn't try to call // FinishInternal during ShutdownDecoder. if (mDecoder) mDecoder->PostResizeError(); DoError(); return NS_ERROR_UNEXPECTED; } // Set the size and flag that we have it mSize.SizeTo(aWidth, aHeight); mHasSize = true; return NS_OK; } nsresult RasterImage::EnsureFrame(uint32_t aFrameNum, int32_t aX, int32_t aY, int32_t aWidth, int32_t aHeight, gfxASurface::gfxImageFormat aFormat, uint8_t aPaletteDepth, uint8_t **imageData, uint32_t *imageLength, uint32_t **paletteData, uint32_t *paletteLength, imgFrame** aRetFrame) { if (mError) return NS_ERROR_FAILURE; NS_ENSURE_ARG_POINTER(imageData); NS_ENSURE_ARG_POINTER(imageLength); NS_ENSURE_ARG_POINTER(aRetFrame); NS_ABORT_IF_FALSE(aFrameNum <= mFrames.Length(), "Invalid frame index!"); if (aPaletteDepth > 0) { NS_ENSURE_ARG_POINTER(paletteData); NS_ENSURE_ARG_POINTER(paletteLength); } if (aFrameNum > mFrames.Length()) return NS_ERROR_INVALID_ARG; // Adding a frame that doesn't already exist. if (aFrameNum == mFrames.Length()) return InternalAddFrame(aFrameNum, aX, aY, aWidth, aHeight, aFormat, aPaletteDepth, imageData, imageLength, paletteData, paletteLength, aRetFrame); imgFrame *frame = GetImgFrameNoDecode(aFrameNum); if (!frame) return InternalAddFrame(aFrameNum, aX, aY, aWidth, aHeight, aFormat, aPaletteDepth, imageData, imageLength, paletteData, paletteLength, aRetFrame); // See if we can re-use the frame that already exists. nsIntRect rect = frame->GetRect(); if (rect.x == aX && rect.y == aY && rect.width == aWidth && rect.height == aHeight && frame->GetFormat() == aFormat && frame->GetPaletteDepth() == aPaletteDepth) { frame->GetImageData(imageData, imageLength); if (paletteData) { frame->GetPaletteData(paletteData, paletteLength); } *aRetFrame = frame; // We can re-use the frame if it has image data. if (*imageData && paletteData && *paletteData) { return NS_OK; } if (*imageData && !paletteData) { return NS_OK; } } // Not reusable, so replace the frame directly. // We know this frame is already locked, because it's the one we're currently // writing to. frame->UnlockImageData(); DeleteImgFrame(aFrameNum); mFrames.RemoveElementAt(aFrameNum); nsAutoPtr<imgFrame> newFrame(new imgFrame()); nsresult rv = newFrame->Init(aX, aY, aWidth, aHeight, aFormat, aPaletteDepth); NS_ENSURE_SUCCESS(rv, rv); return InternalAddFrameHelper(aFrameNum, newFrame.forget(), imageData, imageLength, paletteData, paletteLength, aRetFrame); } nsresult RasterImage::EnsureFrame(uint32_t aFramenum, int32_t aX, int32_t aY, int32_t aWidth, int32_t aHeight, gfxASurface::gfxImageFormat aFormat, uint8_t** imageData, uint32_t* imageLength, imgFrame** aFrame) { return EnsureFrame(aFramenum, aX, aY, aWidth, aHeight, aFormat, /* aPaletteDepth = */ 0, imageData, imageLength, /* aPaletteData = */ nullptr, /* aPaletteLength = */ nullptr, aFrame); } void RasterImage::FrameUpdated(uint32_t aFrameNum, nsIntRect &aUpdatedRect) { NS_ABORT_IF_FALSE(aFrameNum < mFrames.Length(), "Invalid frame index!"); imgFrame *frame = GetImgFrameNoDecode(aFrameNum); NS_ABORT_IF_FALSE(frame, "Calling FrameUpdated on frame that doesn't exist!"); frame->ImageUpdated(aUpdatedRect); if (aFrameNum == GetCurrentImgFrameIndex() && !IsInUpdateImageContainer()) { mImageContainer = nullptr; } } nsresult RasterImage::SetFrameAsNonPremult(uint32_t aFrameNum, bool aIsNonPremult) { if (mError) return NS_ERROR_FAILURE; NS_ABORT_IF_FALSE(aFrameNum < mFrames.Length(), "Invalid frame index!"); if (aFrameNum >= mFrames.Length()) return NS_ERROR_INVALID_ARG; imgFrame* frame = GetImgFrameNoDecode(aFrameNum); NS_ABORT_IF_FALSE(frame, "Calling SetFrameAsNonPremult on frame that doesn't exist!"); NS_ENSURE_TRUE(frame, NS_ERROR_FAILURE); frame->SetAsNonPremult(aIsNonPremult); return NS_OK; } nsresult RasterImage::DecodingComplete() { MOZ_ASSERT(NS_IsMainThread()); if (mError) return NS_ERROR_FAILURE; // Flag that we're done decoding. // XXX - these should probably be combined when we fix animated image // discarding with bug 500402. mDecoded = true; mHasBeenDecoded = true; nsresult rv; // We now have one of the qualifications for discarding. Re-evaluate. if (CanDiscard()) { NS_ABORT_IF_FALSE(!DiscardingActive(), "We shouldn't have been discardable before this"); rv = DiscardTracker::Reset(&mDiscardTrackerNode); CONTAINER_ENSURE_SUCCESS(rv); } // If there's only 1 frame, optimize it. Optimizing animated images // is not supported. // // We don't optimize the frame for multipart images because we reuse // the frame. if ((mFrames.Length() == 1) && !mMultipart) { rv = mFrames[0]->Optimize(); NS_ENSURE_SUCCESS(rv, rv); } // Double-buffer our frame in the multipart case, since we'll start decoding // into mFrames again immediately and this produces severe tearing. if (mMultipart) { if (mFrames.Length() == 1) { imgFrame* swapFrame = mMultipartDecodedFrame; mMultipartDecodedFrame = GetImgFrameNoDecode(GetCurrentFrameIndex()); mFrames.Clear(); if (swapFrame) { mFrames.AppendElement(swapFrame); } } else { // Don't double buffer for animated multipart images. It entails more // complexity and it's not really needed since we already are smart about // not displaying the still-decoding frame of an animated image. We may // have already stored an extra frame, though, so we'll release it here. delete mMultipartDecodedFrame; } } return NS_OK; } //****************************************************************************** /* void StartAnimation () */ nsresult RasterImage::StartAnimation() { if (mError) return NS_ERROR_FAILURE; NS_ABORT_IF_FALSE(ShouldAnimate(), "Should not animate!"); EnsureAnimExists(); imgFrame* currentFrame = GetCurrentImgFrame(); if (currentFrame) { if (currentFrame->GetTimeout() < 0) { // -1 means display this frame forever mAnimationFinished = true; return NS_ERROR_ABORT; } // We need to set the time that this initial frame was first displayed, as // this is used in AdvanceFrame(). mAnim->currentAnimationFrameTime = TimeStamp::Now(); } return NS_OK; } //****************************************************************************** /* void stopAnimation (); */ nsresult RasterImage::StopAnimation() { NS_ABORT_IF_FALSE(mAnimating, "Should be animating!"); if (mError) return NS_ERROR_FAILURE; return NS_OK; } //****************************************************************************** /* void resetAnimation (); */ NS_IMETHODIMP RasterImage::ResetAnimation() { if (mError) return NS_ERROR_FAILURE; if (mAnimationMode == kDontAnimMode || !mAnim || mAnim->currentAnimationFrameIndex == 0) return NS_OK; mAnimationFinished = false; if (mAnimating) StopAnimation(); mAnim->lastCompositedFrameIndex = -1; mAnim->currentAnimationFrameIndex = 0; UpdateImageContainer(); // Note - We probably want to kick off a redecode somewhere around here when // we fix bug 500402. // Update display if we were animating before if (mAnimating && mStatusTracker) { mStatusTracker->FrameChanged(&(mAnim->firstFrameRefreshArea)); } if (ShouldAnimate()) { StartAnimation(); // The animation may not have been running before, if mAnimationFinished // was false (before we changed it to true in this function). So, mark the // animation as running. mAnimating = true; } return NS_OK; } void RasterImage::SetLoopCount(int32_t aLoopCount) { if (mError) return; // -1 infinite // 0 no looping, one iteration // 1 one loop, two iterations // ... mLoopCount = aLoopCount; } nsresult RasterImage::AddSourceData(const char *aBuffer, uint32_t aCount) { MutexAutoLock lock(mDecodingMutex); if (mError) return NS_ERROR_FAILURE; NS_ENSURE_ARG_POINTER(aBuffer); nsresult rv = NS_OK; // We should not call this if we're not initialized NS_ABORT_IF_FALSE(mInitialized, "Calling AddSourceData() on uninitialized " "RasterImage!"); // We should not call this if we're already finished adding source data NS_ABORT_IF_FALSE(!mHasSourceData, "Calling AddSourceData() after calling " "sourceDataComplete()!"); // This call should come straight from necko - no reentrancy allowed NS_ABORT_IF_FALSE(!mInDecoder, "Re-entrant call to AddSourceData!"); // Image is already decoded, we shouldn't be getting data, but it could // be extra garbage data at the end of a file. if (mDecoded) { return NS_OK; } // Starting a new part's frames, let's clean up before we add any // This needs to happen just before we start getting EnsureFrame() call(s), // so that there's no gap for anything to miss us. if (mMultipart && mBytesDecoded == 0) { // Our previous state may have been animated, so let's clean up if (mAnimating) { StopAnimation(); mAnimating = false; } mAnimationFinished = false; if (mAnim) { delete mAnim; mAnim = nullptr; } // If there's only one frame, this could cause flickering int old_frame_count = mFrames.Length(); if (old_frame_count > 1) { for (int i = 0; i < old_frame_count; ++i) { DeleteImgFrame(i); } mFrames.Clear(); } } // If we're not storing source data and we've previously gotten the size, // write the data directly to the decoder. (If we haven't gotten the size, // we'll queue up the data and write it out when we do.) if (!StoringSourceData() && mHasSize) { rv = WriteToDecoder(aBuffer, aCount); CONTAINER_ENSURE_SUCCESS(rv); // We're not storing source data, so this data is probably coming straight // from the network. In this case, we want to display data as soon as we // get it, so we want to flush invalidations after every write. nsRefPtr<Decoder> kungFuDeathGrip = mDecoder; mInDecoder = true; mDecoder->FlushInvalidations(); mInDecoder = false; rv = FinishedSomeDecoding(); CONTAINER_ENSURE_SUCCESS(rv); } // Otherwise, we're storing data in the source buffer else { // Store the data char *newElem = mSourceData.AppendElements(aBuffer, aCount); if (!newElem) return NS_ERROR_OUT_OF_MEMORY; if (mDecoder) { DecodePool::Singleton()->RequestDecode(this); } } // Statistics total_source_bytes += aCount; if (mDiscardable) discardable_source_bytes += aCount; PR_LOG (GetCompressedImageAccountingLog(), PR_LOG_DEBUG, ("CompressedImageAccounting: Added compressed data to RasterImage %p (%s). " "Total Containers: %d, Discardable containers: %d, " "Total source bytes: %lld, Source bytes for discardable containers %lld", this, mSourceDataMimeType.get(), num_containers, num_discardable_containers, total_source_bytes, discardable_source_bytes)); return NS_OK; } /* Note! buf must be declared as char buf[9]; */ // just used for logging and hashing the header static void get_header_str (char *buf, char *data, size_t data_len) { int i; int n; static char hex[] = "0123456789abcdef"; n = data_len < 4 ? data_len : 4; for (i = 0; i < n; i++) { buf[i * 2] = hex[(data[i] >> 4) & 0x0f]; buf[i * 2 + 1] = hex[data[i] & 0x0f]; } buf[i * 2] = 0; } nsresult RasterImage::DoImageDataComplete() { MOZ_ASSERT(NS_IsMainThread()); if (mError) return NS_ERROR_FAILURE; // If we've been called before, ignore. Otherwise, flag that we have everything if (mHasSourceData) return NS_OK; mHasSourceData = true; // If there's a decoder open, synchronously decode the beginning of the image // to check for errors and get the image's size. (If we already have the // image's size, this does nothing.) Then kick off an async decode of the // rest of the image. if (mDecoder) { nsresult rv = DecodePool::Singleton()->DecodeUntilSizeAvailable(this); CONTAINER_ENSURE_SUCCESS(rv); } { MutexAutoLock lock(mDecodingMutex); // If we're not storing any source data, then there's nothing more we can do // once we've tried decoding for size. if (!StoringSourceData() && mDecoder) { nsresult rv = ShutdownDecoder(eShutdownIntent_Done); CONTAINER_ENSURE_SUCCESS(rv); } // If DecodeUntilSizeAvailable didn't finish the decode, let the decode worker // finish decoding this image. if (mDecoder) { DecodePool::Singleton()->RequestDecode(this); } // Free up any extra space in the backing buffer mSourceData.Compact(); } // Log header information if (PR_LOG_TEST(GetCompressedImageAccountingLog(), PR_LOG_DEBUG)) { char buf[9]; get_header_str(buf, mSourceData.Elements(), mSourceData.Length()); PR_LOG (GetCompressedImageAccountingLog(), PR_LOG_DEBUG, ("CompressedImageAccounting: RasterImage::SourceDataComplete() - data " "is done for container %p (%s) - header %p is 0x%s (length %d)", this, mSourceDataMimeType.get(), mSourceData.Elements(), buf, mSourceData.Length())); } // We now have one of the qualifications for discarding. Re-evaluate. if (CanDiscard()) { nsresult rv = DiscardTracker::Reset(&mDiscardTrackerNode); CONTAINER_ENSURE_SUCCESS(rv); } return NS_OK; } nsresult RasterImage::OnImageDataComplete(nsIRequest*, nsISupports*, nsresult aStatus, bool aLastPart) { nsresult finalStatus = DoImageDataComplete(); // Give precedence to Necko failure codes. if (NS_FAILED(aStatus)) finalStatus = aStatus; if (mDecodeRequest) { mDecodeRequest->mStatusTracker->GetDecoderObserver()->OnStopRequest(aLastPart, finalStatus); } else { mStatusTracker->GetDecoderObserver()->OnStopRequest(aLastPart, finalStatus); } // We just recorded OnStopRequest; we need to inform our listeners. { MutexAutoLock lock(mDecodingMutex); FinishedSomeDecoding(); } return finalStatus; } nsresult RasterImage::OnImageDataAvailable(nsIRequest*, nsISupports*, nsIInputStream* aInStr, uint64_t, uint32_t aCount) { nsresult rv; // WriteToRasterImage always consumes everything it gets // if it doesn't run out of memory uint32_t bytesRead; rv = aInStr->ReadSegments(WriteToRasterImage, this, aCount, &bytesRead); NS_ABORT_IF_FALSE(bytesRead == aCount || HasError(), "WriteToRasterImage should consume everything or the image must be in error!"); return rv; } nsresult RasterImage::OnNewSourceData() { MOZ_ASSERT(NS_IsMainThread()); nsresult rv; if (mError) return NS_ERROR_FAILURE; // The source data should be complete before calling this NS_ABORT_IF_FALSE(mHasSourceData, "Calling NewSourceData before SourceDataComplete!"); if (!mHasSourceData) return NS_ERROR_ILLEGAL_VALUE; // Only supported for multipart channels. It wouldn't be too hard to change this, // but it would involve making sure that things worked for decode-on-draw and // discarding. Presently there's no need for this, so we don't. NS_ABORT_IF_FALSE(mMultipart, "NewSourceData only supported for multipart"); if (!mMultipart) return NS_ERROR_ILLEGAL_VALUE; // We're multipart, so we shouldn't be storing source data NS_ABORT_IF_FALSE(!StoringSourceData(), "Shouldn't be storing source data for multipart"); // We're not storing the source data and we got SourceDataComplete. We should // have shut down the previous decoder NS_ABORT_IF_FALSE(!mDecoder, "Shouldn't have a decoder in NewSourceData"); // The decoder was shut down and we didn't flag an error, so we should be decoded NS_ABORT_IF_FALSE(mDecoded, "Should be decoded in NewSourceData"); // Reset some flags mDecoded = false; mHasSourceData = false; mHasSize = false; mWantFullDecode = true; mDecodeRequest = nullptr; // We always need the size first. rv = InitDecoder(/* aDoSizeDecode = */ true); CONTAINER_ENSURE_SUCCESS(rv); return NS_OK; } nsresult RasterImage::SetSourceSizeHint(uint32_t sizeHint) { if (sizeHint && StoringSourceData()) return mSourceData.SetCapacity(sizeHint) ? NS_OK : NS_ERROR_OUT_OF_MEMORY; return NS_OK; } //****************************************************************************** // DoComposite gets called when the timer for animation get fired and we have to // update the composited frame of the animation. nsresult RasterImage::DoComposite(nsIntRect* aDirtyRect, imgFrame* aPrevFrame, imgFrame* aNextFrame, int32_t aNextFrameIndex) { NS_ENSURE_ARG_POINTER(aDirtyRect); NS_ENSURE_ARG_POINTER(aPrevFrame); NS_ENSURE_ARG_POINTER(aNextFrame); int32_t prevFrameDisposalMethod = aPrevFrame->GetFrameDisposalMethod(); if (prevFrameDisposalMethod == kDisposeRestorePrevious && !mAnim->compositingPrevFrame) prevFrameDisposalMethod = kDisposeClear; nsIntRect prevFrameRect = aPrevFrame->GetRect(); bool isFullPrevFrame = (prevFrameRect.x == 0 && prevFrameRect.y == 0 && prevFrameRect.width == mSize.width && prevFrameRect.height == mSize.height); // Optimization: DisposeClearAll if the previous frame is the same size as // container and it's clearing itself if (isFullPrevFrame && (prevFrameDisposalMethod == kDisposeClear)) prevFrameDisposalMethod = kDisposeClearAll; int32_t nextFrameDisposalMethod = aNextFrame->GetFrameDisposalMethod(); nsIntRect nextFrameRect = aNextFrame->GetRect(); bool isFullNextFrame = (nextFrameRect.x == 0 && nextFrameRect.y == 0 && nextFrameRect.width == mSize.width && nextFrameRect.height == mSize.height); if (!aNextFrame->GetIsPaletted()) { // Optimization: Skip compositing if the previous frame wants to clear the // whole image if (prevFrameDisposalMethod == kDisposeClearAll) { aDirtyRect->SetRect(0, 0, mSize.width, mSize.height); return NS_OK; } // Optimization: Skip compositing if this frame is the same size as the // container and it's fully drawing over prev frame (no alpha) if (isFullNextFrame && (nextFrameDisposalMethod != kDisposeRestorePrevious) && !aNextFrame->GetHasAlpha()) { aDirtyRect->SetRect(0, 0, mSize.width, mSize.height); return NS_OK; } } // Calculate area that needs updating switch (prevFrameDisposalMethod) { default: case kDisposeNotSpecified: case kDisposeKeep: *aDirtyRect = nextFrameRect; break; case kDisposeClearAll: // Whole image container is cleared aDirtyRect->SetRect(0, 0, mSize.width, mSize.height); break; case kDisposeClear: // Calc area that needs to be redrawn (the combination of previous and // this frame) // XXX - This could be done with multiple framechanged calls // Having prevFrame way at the top of the image, and nextFrame // way at the bottom, and both frames being small, we'd be // telling framechanged to refresh the whole image when only two // small areas are needed. aDirtyRect->UnionRect(nextFrameRect, prevFrameRect); break; case kDisposeRestorePrevious: aDirtyRect->SetRect(0, 0, mSize.width, mSize.height); break; } // Optimization: // Skip compositing if the last composited frame is this frame // (Only one composited frame was made for this animation. Example: // Only Frame 3 of a 10 frame image required us to build a composite frame // On the second loop, we do not need to rebuild the frame // since it's still sitting in compositingFrame) if (mAnim->lastCompositedFrameIndex == aNextFrameIndex) { return NS_OK; } bool needToBlankComposite = false; // Create the Compositing Frame if (!mAnim->compositingFrame) { mAnim->compositingFrame = new imgFrame(); nsresult rv = mAnim->compositingFrame->Init(0, 0, mSize.width, mSize.height, gfxASurface::ImageFormatARGB32); if (NS_FAILED(rv)) { mAnim->compositingFrame = nullptr; return rv; } needToBlankComposite = true; } else if (aNextFrameIndex != mAnim->lastCompositedFrameIndex+1) { // If we are not drawing on top of last composited frame, // then we are building a new composite frame, so let's clear it first. needToBlankComposite = true; } // More optimizations possible when next frame is not transparent // But if the next frame has kDisposeRestorePrevious, // this "no disposal" optimization is not possible, // because the frame in "after disposal operation" state // needs to be stored in compositingFrame, so it can be // copied into compositingPrevFrame later. bool doDisposal = true; if (!aNextFrame->GetHasAlpha() && nextFrameDisposalMethod != kDisposeRestorePrevious) { if (isFullNextFrame) { // Optimization: No need to dispose prev.frame when // next frame is full frame and not transparent. doDisposal = false; // No need to blank the composite frame needToBlankComposite = false; } else { if ((prevFrameRect.x >= nextFrameRect.x) && (prevFrameRect.y >= nextFrameRect.y) && (prevFrameRect.x + prevFrameRect.width <= nextFrameRect.x + nextFrameRect.width) && (prevFrameRect.y + prevFrameRect.height <= nextFrameRect.y + nextFrameRect.height)) { // Optimization: No need to dispose prev.frame when // next frame fully overlaps previous frame. doDisposal = false; } } } if (doDisposal) { // Dispose of previous: clear, restore, or keep (copy) switch (prevFrameDisposalMethod) { case kDisposeClear: if (needToBlankComposite) { // If we just created the composite, it could have anything in it's // buffer. Clear whole frame ClearFrame(mAnim->compositingFrame); } else { // Only blank out previous frame area (both color & Mask/Alpha) ClearFrame(mAnim->compositingFrame, prevFrameRect); } break; case kDisposeClearAll: ClearFrame(mAnim->compositingFrame); break; case kDisposeRestorePrevious: // It would be better to copy only the area changed back to // compositingFrame. if (mAnim->compositingPrevFrame) { CopyFrameImage(mAnim->compositingPrevFrame, mAnim->compositingFrame); // destroy only if we don't need it for this frame's disposal if (nextFrameDisposalMethod != kDisposeRestorePrevious) mAnim->compositingPrevFrame = nullptr; } else { ClearFrame(mAnim->compositingFrame); } break; default: // Copy previous frame into compositingFrame before we put the new frame on top // Assumes that the previous frame represents a full frame (it could be // smaller in size than the container, as long as the frame before it erased // itself) // Note: Frame 1 never gets into DoComposite(), so (aNextFrameIndex - 1) will // always be a valid frame number. if (mAnim->lastCompositedFrameIndex != aNextFrameIndex - 1) { if (isFullPrevFrame && !aPrevFrame->GetIsPaletted()) { // Just copy the bits CopyFrameImage(aPrevFrame, mAnim->compositingFrame); } else { if (needToBlankComposite) { // Only blank composite when prev is transparent or not full. if (aPrevFrame->GetHasAlpha() || !isFullPrevFrame) { ClearFrame(mAnim->compositingFrame); } } DrawFrameTo(aPrevFrame, mAnim->compositingFrame, prevFrameRect); } } } } else if (needToBlankComposite) { // If we just created the composite, it could have anything in it's // buffers. Clear them ClearFrame(mAnim->compositingFrame); } // Check if the frame we are composing wants the previous image restored afer // it is done. Don't store it (again) if last frame wanted its image restored // too if ((nextFrameDisposalMethod == kDisposeRestorePrevious) && (prevFrameDisposalMethod != kDisposeRestorePrevious)) { // We are storing the whole image. // It would be better if we just stored the area that nextFrame is going to // overwrite. if (!mAnim->compositingPrevFrame) { mAnim->compositingPrevFrame = new imgFrame(); nsresult rv = mAnim->compositingPrevFrame->Init(0, 0, mSize.width, mSize.height, gfxASurface::ImageFormatARGB32); if (NS_FAILED(rv)) { mAnim->compositingPrevFrame = nullptr; return rv; } } CopyFrameImage(mAnim->compositingFrame, mAnim->compositingPrevFrame); } // blit next frame into it's correct spot DrawFrameTo(aNextFrame, mAnim->compositingFrame, nextFrameRect); // Set timeout of CompositeFrame to timeout of frame we just composed // Bug 177948 int32_t timeout = aNextFrame->GetTimeout(); mAnim->compositingFrame->SetTimeout(timeout); // Tell the image that it is fully 'downloaded'. nsresult rv = mAnim->compositingFrame->ImageUpdated(mAnim->compositingFrame->GetRect()); if (NS_FAILED(rv)) { return rv; } // We don't want to keep composite images for 8bit frames. // Also this optimization won't work if the next frame has // kDisposeRestorePrevious, because it would need to be restored // into "after prev disposal but before next blend" state, // not into empty frame. if (isFullNextFrame && mAnimationMode == kNormalAnimMode && mLoopCount != 0 && nextFrameDisposalMethod != kDisposeRestorePrevious && !aNextFrame->GetIsPaletted()) { // We have a composited full frame // Store the composited frame into the mFrames[..] so we don't have to // continuously re-build it // Then set the previous frame's disposal to CLEAR_ALL so we just draw the // frame next time around if (CopyFrameImage(mAnim->compositingFrame, aNextFrame)) { aPrevFrame->SetFrameDisposalMethod(kDisposeClearAll); mAnim->lastCompositedFrameIndex = -1; return NS_OK; } } mAnim->lastCompositedFrameIndex = aNextFrameIndex; return NS_OK; } //****************************************************************************** // Fill aFrame with black. Does also clears the mask. void RasterImage::ClearFrame(imgFrame *aFrame) { if (!aFrame) return; nsresult rv = aFrame->LockImageData(); if (NS_FAILED(rv)) return; nsRefPtr<gfxASurface> surf; aFrame->GetSurface(getter_AddRefs(surf)); // Erase the surface to transparent gfxContext ctx(surf); ctx.SetOperator(gfxContext::OPERATOR_CLEAR); ctx.Paint(); aFrame->UnlockImageData(); } //****************************************************************************** void RasterImage::ClearFrame(imgFrame *aFrame, nsIntRect &aRect) { if (!aFrame || aRect.width <= 0 || aRect.height <= 0) return; nsresult rv = aFrame->LockImageData(); if (NS_FAILED(rv)) return; nsRefPtr<gfxASurface> surf; aFrame->GetSurface(getter_AddRefs(surf)); // Erase the destination rectangle to transparent gfxContext ctx(surf); ctx.SetOperator(gfxContext::OPERATOR_CLEAR); ctx.Rectangle(gfxRect(aRect.x, aRect.y, aRect.width, aRect.height)); ctx.Fill(); aFrame->UnlockImageData(); } //****************************************************************************** // Whether we succeed or fail will not cause a crash, and there's not much // we can do about a failure, so there we don't return a nsresult bool RasterImage::CopyFrameImage(imgFrame *aSrcFrame, imgFrame *aDstFrame) { uint8_t* aDataSrc; uint8_t* aDataDest; uint32_t aDataLengthSrc; uint32_t aDataLengthDest; if (!aSrcFrame || !aDstFrame) return false; AutoFrameLocker dstLock(aDstFrame); AutoFrameLocker srcLock(aSrcFrame); if (!srcLock.Succeeded() || !dstLock.Succeeded()) { return false; } // Copy Image Over aSrcFrame->GetImageData(&aDataSrc, &aDataLengthSrc); aDstFrame->GetImageData(&aDataDest, &aDataLengthDest); if (!aDataDest || !aDataSrc || aDataLengthDest != aDataLengthSrc) { return false; } memcpy(aDataDest, aDataSrc, aDataLengthSrc); return true; } //****************************************************************************** /* * aSrc is the current frame being drawn, * aDst is the composition frame where the current frame is drawn into. * aSrcRect is the size of the current frame, and the position of that frame * in the composition frame. */ nsresult RasterImage::DrawFrameTo(imgFrame *aSrc, imgFrame *aDst, nsIntRect& aSrcRect) { NS_ENSURE_ARG_POINTER(aSrc); NS_ENSURE_ARG_POINTER(aDst); AutoFrameLocker srcLock(aSrc); AutoFrameLocker dstLock(aDst); nsIntRect dstRect = aDst->GetRect(); // According to both AGIF and APNG specs, offsets are unsigned if (aSrcRect.x < 0 || aSrcRect.y < 0) { NS_WARNING("RasterImage::DrawFrameTo: negative offsets not allowed"); return NS_ERROR_FAILURE; } // Outside the destination frame, skip it if ((aSrcRect.x > dstRect.width) || (aSrcRect.y > dstRect.height)) { return NS_OK; } if (aSrc->GetIsPaletted()) { // Larger than the destination frame, clip it int32_t width = std::min(aSrcRect.width, dstRect.width - aSrcRect.x); int32_t height = std::min(aSrcRect.height, dstRect.height - aSrcRect.y); // The clipped image must now fully fit within destination image frame NS_ASSERTION((aSrcRect.x >= 0) && (aSrcRect.y >= 0) && (aSrcRect.x + width <= dstRect.width) && (aSrcRect.y + height <= dstRect.height), "RasterImage::DrawFrameTo: Invalid aSrcRect"); // clipped image size may be smaller than source, but not larger NS_ASSERTION((width <= aSrcRect.width) && (height <= aSrcRect.height), "RasterImage::DrawFrameTo: source must be smaller than dest"); if (!srcLock.Succeeded() || !dstLock.Succeeded()) return NS_ERROR_FAILURE; // Get pointers to image data uint32_t size; uint8_t *srcPixels; uint32_t *colormap; uint32_t *dstPixels; aSrc->GetImageData(&srcPixels, &size); aSrc->GetPaletteData(&colormap, &size); aDst->GetImageData((uint8_t **)&dstPixels, &size); if (!srcPixels || !dstPixels || !colormap) { return NS_ERROR_FAILURE; } // Skip to the right offset dstPixels += aSrcRect.x + (aSrcRect.y * dstRect.width); if (!aSrc->GetHasAlpha()) { for (int32_t r = height; r > 0; --r) { for (int32_t c = 0; c < width; c++) { dstPixels[c] = colormap[srcPixels[c]]; } // Go to the next row in the source resp. destination image srcPixels += aSrcRect.width; dstPixels += dstRect.width; } } else { for (int32_t r = height; r > 0; --r) { for (int32_t c = 0; c < width; c++) { const uint32_t color = colormap[srcPixels[c]]; if (color) dstPixels[c] = color; } // Go to the next row in the source resp. destination image srcPixels += aSrcRect.width; dstPixels += dstRect.width; } } return NS_OK; } nsRefPtr<gfxPattern> srcPatt; aSrc->GetPattern(getter_AddRefs(srcPatt)); nsRefPtr<gfxASurface> dstSurf; aDst->GetSurface(getter_AddRefs(dstSurf)); gfxContext dst(dstSurf); dst.Translate(gfxPoint(aSrcRect.x, aSrcRect.y)); dst.Rectangle(gfxRect(0, 0, aSrcRect.width, aSrcRect.height), true); // first clear the surface if the blend flag says so int32_t blendMethod = aSrc->GetBlendMethod(); if (blendMethod == kBlendSource) { gfxContext::GraphicsOperator defaultOperator = dst.CurrentOperator(); dst.SetOperator(gfxContext::OPERATOR_CLEAR); dst.Fill(); dst.SetOperator(defaultOperator); } dst.SetPattern(srcPatt); dst.Paint(); return NS_OK; } /********* Methods to implement lazy allocation of nsIProperties object *************/ NS_IMETHODIMP RasterImage::Get(const char *prop, const nsIID & iid, void * *result) { if (!mProperties) return NS_ERROR_FAILURE; return mProperties->Get(prop, iid, result); } NS_IMETHODIMP RasterImage::Set(const char *prop, nsISupports *value) { if (!mProperties) mProperties = do_CreateInstance("@mozilla.org/properties;1"); if (!mProperties) return NS_ERROR_OUT_OF_MEMORY; return mProperties->Set(prop, value); } NS_IMETHODIMP RasterImage::Has(const char *prop, bool *_retval) { NS_ENSURE_ARG_POINTER(_retval); if (!mProperties) { *_retval = false; return NS_OK; } return mProperties->Has(prop, _retval); } NS_IMETHODIMP RasterImage::Undefine(const char *prop) { if (!mProperties) return NS_ERROR_FAILURE; return mProperties->Undefine(prop); } NS_IMETHODIMP RasterImage::GetKeys(uint32_t *count, char ***keys) { if (!mProperties) { *count = 0; *keys = nullptr; return NS_OK; } return mProperties->GetKeys(count, keys); } void RasterImage::Discard(bool force) { MOZ_ASSERT(NS_IsMainThread()); // We should be ok for discard NS_ABORT_IF_FALSE(force ? CanForciblyDiscard() : CanDiscard(), "Asked to discard but can't!"); // We should never discard when we have an active decoder NS_ABORT_IF_FALSE(!mDecoder, "Asked to discard with open decoder!"); // As soon as an image becomes animated, it becomes non-discardable and any // timers are cancelled. NS_ABORT_IF_FALSE(!mAnim, "Asked to discard for animated image!"); // For post-operation logging int old_frame_count = mFrames.Length(); // Delete all the decoded frames, then clear the array. for (int i = 0; i < old_frame_count; ++i) delete mFrames[i]; mFrames.Clear(); // Clear our downscaled frame. mScaleResult.status = SCALE_INVALID; mScaleResult.frame = nullptr; // Clear the last decoded multipart frame. delete mMultipartDecodedFrame; mMultipartDecodedFrame = nullptr; // Flag that we no longer have decoded frames for this image mDecoded = false; // Notify that we discarded if (mStatusTracker) mStatusTracker->OnDiscard(); mDecodeRequest = nullptr; if (force) DiscardTracker::Remove(&mDiscardTrackerNode); // Log PR_LOG(GetCompressedImageAccountingLog(), PR_LOG_DEBUG, ("CompressedImageAccounting: discarded uncompressed image " "data from RasterImage %p (%s) - %d frames (cached count: %d); " "Total Containers: %d, Discardable containers: %d, " "Total source bytes: %lld, Source bytes for discardable containers %lld", this, mSourceDataMimeType.get(), old_frame_count, mFrames.Length(), num_containers, num_discardable_containers, total_source_bytes, discardable_source_bytes)); } // Helper method to determine if we can discard an image bool RasterImage::CanDiscard() { return (DiscardingEnabled() && // Globally enabled... mDiscardable && // ...Enabled at creation time... (mLockCount == 0) && // ...not temporarily disabled... mHasSourceData && // ...have the source data... mDecoded); // ...and have something to discard. } bool RasterImage::CanForciblyDiscard() { return mDiscardable && // ...Enabled at creation time... mHasSourceData; // ...have the source data... } // Helper method to tell us whether the clock is currently running for // discarding this image. Mainly for assertions. bool RasterImage::DiscardingActive() { return mDiscardTrackerNode.isInList(); } // Helper method to determine if we're storing the source data in a buffer // or just writing it directly to the decoder bool RasterImage::StoringSourceData() const { return (mDecodeOnDraw || mDiscardable); } // Sets up a decoder for this image. It is an error to call this function // when decoding is already in process (ie - when mDecoder is non-null). nsresult RasterImage::InitDecoder(bool aDoSizeDecode, bool aIsSynchronous /* = false */) { // Ensure that the decoder is not already initialized NS_ABORT_IF_FALSE(!mDecoder, "Calling InitDecoder() while already decoding!"); // We shouldn't be firing up a decoder if we already have the frames decoded NS_ABORT_IF_FALSE(!mDecoded, "Calling InitDecoder() but already decoded!"); // Since we're not decoded, we should not have a discard timer active NS_ABORT_IF_FALSE(!DiscardingActive(), "Discard Timer active in InitDecoder()!"); // Make sure we actually get size before doing a full decode. if (!aDoSizeDecode) { NS_ABORT_IF_FALSE(mHasSize, "Must do a size decode before a full decode!"); } // Figure out which decoder we want eDecoderType type = GetDecoderType(mSourceDataMimeType.get()); CONTAINER_ENSURE_TRUE(type != eDecoderType_unknown, NS_IMAGELIB_ERROR_NO_DECODER); // Instantiate the appropriate decoder switch (type) { case eDecoderType_png: mDecoder = new nsPNGDecoder(*this); break; case eDecoderType_gif: mDecoder = new nsGIFDecoder2(*this); break; case eDecoderType_jpeg: // If we have all the data we don't want to waste cpu time doing // a progressive decode mDecoder = new nsJPEGDecoder(*this, mHasBeenDecoded ? Decoder::SEQUENTIAL : Decoder::PROGRESSIVE); break; case eDecoderType_bmp: mDecoder = new nsBMPDecoder(*this); break; case eDecoderType_ico: mDecoder = new nsICODecoder(*this); break; case eDecoderType_icon: mDecoder = new nsIconDecoder(*this); break; #ifdef MOZ_WBMP case eDecoderType_wbmp: mDecoder = new nsWBMPDecoder(*this); break; #endif default: NS_ABORT_IF_FALSE(0, "Shouldn't get here!"); } // If we already have frames, we're probably in the multipart/x-mixed-replace // case. Regardless, we need to lock the last frame. Our invariant is that, // while we have a decoder open, the last frame is always locked. if (mFrames.Length() > 0) { imgFrame *curframe = mFrames.ElementAt(mFrames.Length() - 1); curframe->LockImageData(); } // Initialize the decoder if (!mDecodeRequest) { mDecodeRequest = new DecodeRequest(this); } mDecoder->SetObserver(mDecodeRequest->mStatusTracker->GetDecoderObserver()); mDecoder->SetSizeDecode(aDoSizeDecode); mDecoder->SetDecodeFlags(mFrameDecodeFlags); mDecoder->SetSynchronous(aIsSynchronous); if (!aDoSizeDecode) { // We already have the size; tell the decoder so it can preallocate a // frame. By default, we create an ARGB frame with no offset. If decoders // need a different type, they need to ask for it themselves. mDecoder->NeedNewFrame(0, 0, 0, mSize.width, mSize.height, gfxASurface::ImageFormatARGB32); mDecoder->AllocateFrame(); } mDecoder->Init(); CONTAINER_ENSURE_SUCCESS(mDecoder->GetDecoderError()); if (!aDoSizeDecode) { Telemetry::GetHistogramById(Telemetry::IMAGE_DECODE_COUNT)->Subtract(mDecodeCount); mDecodeCount++; Telemetry::GetHistogramById(Telemetry::IMAGE_DECODE_COUNT)->Add(mDecodeCount); if (mDecodeCount > sMaxDecodeCount) { // Don't subtract out 0 from the histogram, because that causes its count // to go negative, which is not kosher. if (sMaxDecodeCount > 0) { Telemetry::GetHistogramById(Telemetry::IMAGE_MAX_DECODE_COUNT)->Subtract(sMaxDecodeCount); } sMaxDecodeCount = mDecodeCount; Telemetry::GetHistogramById(Telemetry::IMAGE_MAX_DECODE_COUNT)->Add(sMaxDecodeCount); } } return NS_OK; } // Flushes, closes, and nulls-out a decoder. Cleans up any related decoding // state. It is an error to call this function when there is no initialized // decoder. // // aIntent specifies the intent of the shutdown. If aIntent is // eShutdownIntent_Done, an error is flagged if we didn't get what we should // have out of the decode. If aIntent is eShutdownIntent_NotNeeded, we don't // check this. If aIntent is eShutdownIntent_Error, we shut down in error mode. nsresult RasterImage::ShutdownDecoder(eShutdownIntent aIntent) { MOZ_ASSERT(NS_IsMainThread()); mDecodingMutex.AssertCurrentThreadOwns(); // Ensure that our intent is valid NS_ABORT_IF_FALSE((aIntent >= 0) && (aIntent < eShutdownIntent_AllCount), "Invalid shutdown intent"); // Ensure that the decoder is initialized NS_ABORT_IF_FALSE(mDecoder, "Calling ShutdownDecoder() with no active decoder!"); // Figure out what kind of decode we were doing before we get rid of our decoder bool wasSizeDecode = mDecoder->IsSizeDecode(); // Unlock the last frame (if we have any). Our invariant is that, while we // have a decoder open, the last frame is always locked. if (mFrames.Length() > 0) { imgFrame *curframe = mFrames.ElementAt(mFrames.Length() - 1); curframe->UnlockImageData(); } // Finalize the decoder // null out mDecoder, _then_ check for errors on the close (otherwise the // error routine might re-invoke ShutdownDecoder) nsRefPtr<Decoder> decoder = mDecoder; mDecoder = nullptr; mFinishing = true; mInDecoder = true; decoder->Finish(aIntent); mInDecoder = false; mFinishing = false; // Kill off our decode request, if it's pending. (If not, this call is // harmless.) DecodePool::StopDecoding(this); nsresult decoderStatus = decoder->GetDecoderError(); if (NS_FAILED(decoderStatus)) { DoError(); return decoderStatus; } // We just shut down the decoder. If we didn't get what we want, but expected // to, flag an error bool failed = false; if (wasSizeDecode && !mHasSize) failed = true; if (!wasSizeDecode && !mDecoded) failed = true; if ((aIntent == eShutdownIntent_Done) && failed) { DoError(); return NS_ERROR_FAILURE; } // If we finished a full decode, and we're not meant to be storing source // data, stop storing it. if (!wasSizeDecode && !StoringSourceData()) { mSourceData.Clear(); } mBytesDecoded = 0; return NS_OK; } // Writes the data to the decoder, updating the total number of bytes written. nsresult RasterImage::WriteToDecoder(const char *aBuffer, uint32_t aCount) { mDecodingMutex.AssertCurrentThreadOwns(); // We should have a decoder NS_ABORT_IF_FALSE(mDecoder, "Trying to write to null decoder!"); // Write nsRefPtr<Decoder> kungFuDeathGrip = mDecoder; mInDecoder = true; mDecoder->Write(aBuffer, aCount); mInDecoder = false; if (!mDecoder) return NS_ERROR_FAILURE; CONTAINER_ENSURE_SUCCESS(mDecoder->GetDecoderError()); // Keep track of the total number of bytes written over the lifetime of the // decoder mBytesDecoded += aCount; return NS_OK; } // This function is called in situations where it's clear that we want the // frames in decoded form (Draw, GetFrame, CopyFrame, ExtractFrame, etc). // If we're completely decoded, this method resets the discard timer (if // we're discardable), since wanting the frames now is a good indicator of // wanting them again soon. If we're not decoded, this method kicks off // asynchronous decoding to generate the frames. nsresult RasterImage::WantDecodedFrames() { nsresult rv; // If we can discard, the clock should be running. Reset it. if (CanDiscard()) { NS_ABORT_IF_FALSE(DiscardingActive(), "Decoded and discardable but discarding not activated!"); rv = DiscardTracker::Reset(&mDiscardTrackerNode); CONTAINER_ENSURE_SUCCESS(rv); } // Request a decode (no-op if we're decoded) return StartDecoding(); } //****************************************************************************** /* void requestDecode() */ NS_IMETHODIMP RasterImage::RequestDecode() { return RequestDecodeCore(ASYNCHRONOUS); } /* void startDecode() */ NS_IMETHODIMP RasterImage::StartDecoding() { return RequestDecodeCore(SOMEWHAT_SYNCHRONOUS); } NS_IMETHODIMP RasterImage::RequestDecodeCore(RequestDecodeType aDecodeType) { MOZ_ASSERT(NS_IsMainThread()); nsresult rv; if (mError) return NS_ERROR_FAILURE; // If we've already got a full decoder running, and have already // decoded some bytes, we have nothing to do if (mDecoder && !mDecoder->IsSizeDecode() && mBytesDecoded) { return NS_OK; } // If we don't have any bytes to flush to the decoder, we can't do anything. // mBytesDecoded can be bigger than mSourceData.Length() if we're not storing // the source data. if (mBytesDecoded > mSourceData.Length()) return NS_OK; // mFinishing protects against the case when we enter RequestDecode from // ShutdownDecoder -- in that case, we're done with the decode, we're just // not quite ready to admit it. See bug 744309. if (mFinishing) return NS_OK; // If our callstack goes through a size decoder, we have a problem. // We need to shutdown the size decode and replace it with a full // decoder, but can't do that from within the decoder itself. Thus, we post // an asynchronous event to the event loop to do it later. Since // RequestDecode() is an asynchronous function this works fine (though it's // a little slower). if (mInDecoder) { nsRefPtr<imgDecodeRequestor> requestor = new imgDecodeRequestor(*this); return NS_DispatchToCurrentThread(requestor); } // If we have a size decoder open, make sure we get the size if (mDecoder && mDecoder->IsSizeDecode()) { nsresult rv = DecodePool::Singleton()->DecodeUntilSizeAvailable(this); CONTAINER_ENSURE_SUCCESS(rv); // If we didn't get the size out of the image, we won't until we get more // data, so signal that we want a full decode and give up for now. if (!mHasSize) { mWantFullDecode = true; return NS_OK; } } // If we're fully decoded, we have nothing to do. This has to be after // DecodeUntilSizeAvailable because it can result in a synchronous decode if // we're already waiting on a full decode. if (mDecoded) return NS_OK; MutexAutoLock lock(mDecodingMutex); // If we have a size decode open, interrupt it and shut it down; or if // the decoder has different flags than what we need if (mDecoder && mDecoder->GetDecodeFlags() != mFrameDecodeFlags) { nsresult rv = FinishedSomeDecoding(eShutdownIntent_NotNeeded); CONTAINER_ENSURE_SUCCESS(rv); } // If we don't have a decoder, create one if (!mDecoder) { rv = InitDecoder(/* aDoSizeDecode = */ false); CONTAINER_ENSURE_SUCCESS(rv); rv = FinishedSomeDecoding(); CONTAINER_ENSURE_SUCCESS(rv); MOZ_ASSERT(mDecoder); } // If we're waiting for decode work to be notified, go ahead and do that. if (mDecodeRequest && mDecodeRequest->mRequestStatus == DecodeRequest::REQUEST_WORK_DONE) { nsresult rv = FinishedSomeDecoding(); CONTAINER_ENSURE_SUCCESS(rv); } // If we've read all the data we have, we're done if (mHasSourceData && mBytesDecoded == mSourceData.Length()) return NS_OK; // If we can do decoding now, do so. Small images will decode completely, // large images will decode a bit and post themselves to the event loop // to finish decoding. if (!mDecoded && !mInDecoder && mHasSourceData && aDecodeType == SOMEWHAT_SYNCHRONOUS) { PROFILER_LABEL_PRINTF("RasterImage", "DecodeABitOf", "%s", GetURIString().get()); mDecoder->SetSynchronous(true); DecodePool::Singleton()->DecodeABitOf(this); // DecodeABitOf can destroy mDecoder. if (mDecoder) { mDecoder->SetSynchronous(false); } return NS_OK; } if (!mDecoded) { // If we get this far, dispatch the worker. We do this instead of starting // any immediate decoding to guarantee that all our decode notifications are // dispatched asynchronously, and to ensure we stay responsive. DecodePool::Singleton()->RequestDecode(this); } return NS_OK; } // Synchronously decodes as much data as possible nsresult RasterImage::SyncDecode() { MutexAutoLock imgLock(mDecodingMutex); if (mDecodeRequest) { // If the image is waiting for decode work to be notified, go ahead and do that. if (mDecodeRequest->mRequestStatus == DecodeRequest::REQUEST_WORK_DONE) { nsresult rv = FinishedSomeDecoding(); CONTAINER_ENSURE_SUCCESS(rv); } } nsresult rv; PROFILER_LABEL_PRINTF("RasterImage", "SyncDecode", "%s", GetURIString().get());; // We really have no good way of forcing a synchronous decode if we're being // called in a re-entrant manner (ie, from an event listener fired by a // decoder), because the decoding machinery is already tied up. We thus explicitly // disallow this type of call in the API, and check for it in API methods. NS_ABORT_IF_FALSE(!mInDecoder, "Yikes, forcing sync in reentrant call!"); // If we have a size decoder open, make sure we get the size if (mDecoder && mDecoder->IsSizeDecode()) { nsresult rv = DecodePool::Singleton()->DecodeUntilSizeAvailable(this); CONTAINER_ENSURE_SUCCESS(rv); // If we didn't get the size out of the image, we won't until we get more // data, so signal that we want a full decode and give up for now. if (!mHasSize) { mWantFullDecode = true; return NS_ERROR_NOT_AVAILABLE; } } // If we're decoded already, or decoding until the size was available // finished us as a side-effect, no worries if (mDecoded) return NS_OK; // If we don't have any bytes to flush to the decoder, we can't do anything. // mBytesDecoded can be bigger than mSourceData.Length() if we're not storing // the source data. if (mBytesDecoded > mSourceData.Length()) return NS_OK; // If we have a decoder open with different flags than what we need, shut it // down if (mDecoder && mDecoder->GetDecodeFlags() != mFrameDecodeFlags) { nsresult rv = FinishedSomeDecoding(eShutdownIntent_NotNeeded); CONTAINER_ENSURE_SUCCESS(rv); } // If we're currently waiting on a new frame for this image, we have to create // it now. if (mDecoder && mDecoder->NeedsNewFrame()) { mDecoder->AllocateFrame(); mDecodeRequest->mAllocatedNewFrame = true; } // If we don't have a decoder, create one if (!mDecoder) { rv = InitDecoder(/* aDoSizeDecode = */ false, /* aIsSynchronous = */ true); CONTAINER_ENSURE_SUCCESS(rv); } else { mDecoder->SetSynchronous(true); } // Write everything we have rv = DecodeSomeData(mSourceData.Length() - mBytesDecoded); CONTAINER_ENSURE_SUCCESS(rv); // When we're doing a sync decode, we want to get as much information from the // image as possible. We've send the decoder all of our data, so now's a good // time to flush any invalidations (in case we don't have all the data and what // we got left us mid-frame). nsRefPtr<Decoder> kungFuDeathGrip = mDecoder; mInDecoder = true; mDecoder->FlushInvalidations(); mInDecoder = false; rv = FinishedSomeDecoding(); CONTAINER_ENSURE_SUCCESS(rv); if (mDecoder) { mDecoder->SetSynchronous(false); // If our decoder's still open, there's still work to be done. DecodePool::Singleton()->RequestDecode(this); } // All good if no errors! return mError ? NS_ERROR_FAILURE : NS_OK; } bool RasterImage::CanQualityScale(const gfxSize& scale) { // If target size is 1:1 with original, don't scale. if (scale.width == 1.0 && scale.height == 1.0) return false; // To save memory don't quality upscale images bigger than the limit. if (scale.width > 1.0 || scale.height > 1.0) { uint32_t scaled_size = static_cast<uint32_t>(mSize.width * mSize.height * scale.width * scale.height); if (scaled_size > gHQUpscalingMaxSize) return false; } return true; } bool RasterImage::CanScale(gfxPattern::GraphicsFilter aFilter, gfxSize aScale) { // The high-quality scaler requires Skia. #ifdef MOZ_ENABLE_SKIA // We don't use the scaler for animated or multipart images to avoid doing a // bunch of work on an image that just gets thrown away. if (gHQDownscaling && aFilter == gfxPattern::FILTER_GOOD && !mAnim && mDecoded && !mMultipart && CanQualityScale(aScale)) { gfxFloat factor = gHQDownscalingMinFactor / 1000.0; return (aScale.width < factor || aScale.height < factor); } #endif return false; } void RasterImage::ScalingStart(ScaleRequest* request) { MOZ_ASSERT(request); mScaleResult.scale = request->scale; mScaleResult.status = SCALE_PENDING; mScaleRequest = request; } void RasterImage::ScalingDone(ScaleRequest* request, ScaleStatus status) { MOZ_ASSERT(status == SCALE_DONE || status == SCALE_INVALID); MOZ_ASSERT(request); if (status == SCALE_DONE) { MOZ_ASSERT(request->done); if (mStatusTracker) { imgFrame *scaledFrame = request->dstFrame.get(); scaledFrame->ImageUpdated(scaledFrame->GetRect()); mStatusTracker->FrameChanged(&request->srcRect); } mScaleResult.status = SCALE_DONE; mScaleResult.frame = request->dstFrame; mScaleResult.scale = request->scale; } else { mScaleResult.status = SCALE_INVALID; mScaleResult.frame = nullptr; } // If we were waiting for this scale to come through, forget the scale // request. Otherwise, we still have a scale outstanding that it's possible // for us to (want to) stop. if (mScaleRequest == request) { mScaleRequest = nullptr; } } void RasterImage::DrawWithPreDownscaleIfNeeded(imgFrame *aFrame, gfxContext *aContext, gfxPattern::GraphicsFilter aFilter, const gfxMatrix &aUserSpaceToImageSpace, const gfxRect &aFill, const nsIntRect &aSubimage) { imgFrame *frame = aFrame; nsIntRect framerect = frame->GetRect(); gfxMatrix userSpaceToImageSpace = aUserSpaceToImageSpace; gfxMatrix imageSpaceToUserSpace = aUserSpaceToImageSpace; imageSpaceToUserSpace.Invert(); gfxSize scale = imageSpaceToUserSpace.ScaleFactors(true); nsIntRect subimage = aSubimage; if (CanScale(aFilter, scale)) { // If scale factor is still the same that we scaled for and // ScaleWorker isn't still working, then we can use pre-downscaled frame. // If scale factor has changed, order new request. // FIXME: Current implementation doesn't support pre-downscale // mechanism for multiple sizes from same src, since we cache // pre-downscaled frame only for the latest requested scale. // The solution is to cache more than one scaled image frame // for each RasterImage. if (mScaleResult.status == SCALE_DONE && mScaleResult.scale == scale) { frame = mScaleResult.frame; userSpaceToImageSpace.Multiply(gfxMatrix().Scale(scale.width, scale.height)); // Since we're switching to a scaled image, we need to transform the // area of the subimage to draw accordingly, since imgFrame::Draw() // doesn't know about scaled frames. subimage.ScaleRoundOut(scale.width, scale.height); } // If we're not waiting for exactly this result, and there's only one // instance of this image on this page, ask for a scale. else if (!(mScaleResult.status == SCALE_PENDING && mScaleResult.scale == scale) && mLockCount == 1) { // If we have an oustanding request, signal it to stop (if it can). if (mScaleRequest) { mScaleRequest->stopped = true; } nsRefPtr<ScaleRunner> runner = new ScaleRunner(this, scale, frame); if (runner->IsOK()) { if (!sScaleWorkerThread) { NS_NewNamedThread("Image Scaler", getter_AddRefs(sScaleWorkerThread)); ClearOnShutdown(&sScaleWorkerThread); } sScaleWorkerThread->Dispatch(runner, NS_DISPATCH_NORMAL); } } } nsIntMargin padding(framerect.y, mSize.width - framerect.XMost(), mSize.height - framerect.YMost(), framerect.x); frame->Draw(aContext, aFilter, userSpaceToImageSpace, aFill, padding, subimage); } //****************************************************************************** /* [noscript] void draw(in gfxContext aContext, * in gfxGraphicsFilter aFilter, * [const] in gfxMatrix aUserSpaceToImageSpace, * [const] in gfxRect aFill, * [const] in nsIntRect aSubimage, * [const] in nsIntSize aViewportSize, * [const] in SVGImageContext aSVGContext, * in uint32_t aWhichFrame, * in uint32_t aFlags); */ NS_IMETHODIMP RasterImage::Draw(gfxContext *aContext, gfxPattern::GraphicsFilter aFilter, const gfxMatrix &aUserSpaceToImageSpace, const gfxRect &aFill, const nsIntRect &aSubimage, const nsIntSize& /*aViewportSize - ignored*/, const SVGImageContext* /*aSVGContext - ignored*/, uint32_t aWhichFrame, uint32_t aFlags) { if (aWhichFrame > FRAME_MAX_VALUE) return NS_ERROR_INVALID_ARG; if (mError) return NS_ERROR_FAILURE; // Disallowed in the API if (mInDecoder && (aFlags & imgIContainer::FLAG_SYNC_DECODE)) return NS_ERROR_FAILURE; // Illegal -- you can't draw with non-default decode flags. // (Disabling colorspace conversion might make sense to allow, but // we don't currently.) if ((aFlags & DECODE_FLAGS_MASK) != DECODE_FLAGS_DEFAULT) return NS_ERROR_FAILURE; NS_ENSURE_ARG_POINTER(aContext); // We can only draw with the default decode flags if (mFrameDecodeFlags != DECODE_FLAGS_DEFAULT) { if (!CanForciblyDiscard()) return NS_ERROR_NOT_AVAILABLE; ForceDiscard(); mFrameDecodeFlags = DECODE_FLAGS_DEFAULT; } // If this image is a candidate for discarding, reset its position in the // discard tracker so we're less likely to discard it right away. // // (We don't normally draw unlocked images, so this conditition will usually // be false. But we will draw unlocked images if image locking is globally // disabled via the content.image.allow_locking pref.) if (DiscardingActive()) { DiscardTracker::Reset(&mDiscardTrackerNode); } if (IsUnlocked() && mStatusTracker) { mStatusTracker->OnUnlockedDraw(); } // We use !mDecoded && mHasSourceData to mean discarded. if (!mDecoded && mHasSourceData) { mDrawStartTime = TimeStamp::Now(); } // If a synchronous draw is requested, flush anything that might be sitting around if (aFlags & FLAG_SYNC_DECODE) { nsresult rv = SyncDecode(); NS_ENSURE_SUCCESS(rv, rv); } uint32_t frameIndex = aWhichFrame == FRAME_FIRST ? 0 : GetCurrentImgFrameIndex(); imgFrame* frame = GetDrawableImgFrame(frameIndex); if (!frame) { return NS_OK; // Getting the frame (above) touches the image and kicks off decoding } DrawWithPreDownscaleIfNeeded(frame, aContext, aFilter, aUserSpaceToImageSpace, aFill, aSubimage); if (mDecoded && !mDrawStartTime.IsNull()) { TimeDuration drawLatency = TimeStamp::Now() - mDrawStartTime; Telemetry::Accumulate(Telemetry::IMAGE_DECODE_ON_DRAW_LATENCY, int32_t(drawLatency.ToMicroseconds())); // clear the value of mDrawStartTime mDrawStartTime = TimeStamp(); } return NS_OK; } //****************************************************************************** /* void lockImage() */ NS_IMETHODIMP RasterImage::LockImage() { if (mError) return NS_ERROR_FAILURE; // Cancel the discard timer if it's there DiscardTracker::Remove(&mDiscardTrackerNode); // Increment the lock count mLockCount++; return NS_OK; } //****************************************************************************** /* void unlockImage() */ NS_IMETHODIMP RasterImage::UnlockImage() { if (mError) return NS_ERROR_FAILURE; // It's an error to call this function if the lock count is 0 NS_ABORT_IF_FALSE(mLockCount > 0, "Calling UnlockImage with mLockCount == 0!"); if (mLockCount == 0) return NS_ERROR_ABORT; // We're locked, so discarding should not be active NS_ABORT_IF_FALSE(!DiscardingActive(), "Locked, but discarding activated"); // Decrement our lock count mLockCount--; // If we've decoded this image once before, we're currently decoding again, // and our lock count is now zero (so nothing is forcing us to keep the // decoded data around), try to cancel the decode and throw away whatever // we've decoded. if (mHasBeenDecoded && mDecoder && mLockCount == 0 && CanForciblyDiscard()) { PR_LOG(GetCompressedImageAccountingLog(), PR_LOG_DEBUG, ("RasterImage[0x%p] canceling decode because image " "is now unlocked.", this)); MutexAutoLock lock(mDecodingMutex); FinishedSomeDecoding(eShutdownIntent_NotNeeded); ForceDiscard(); return NS_OK; } // Otherwise, we might still be a candidate for discarding in the future. If // we are, add ourselves to the discard tracker. if (CanDiscard()) { nsresult rv = DiscardTracker::Reset(&mDiscardTrackerNode); CONTAINER_ENSURE_SUCCESS(rv); } return NS_OK; } //****************************************************************************** /* void requestDiscard() */ NS_IMETHODIMP RasterImage::RequestDiscard() { if (CanDiscard()) { ForceDiscard(); } return NS_OK; } // Flushes up to aMaxBytes to the decoder. nsresult RasterImage::DecodeSomeData(uint32_t aMaxBytes) { // We should have a decoder if we get here NS_ABORT_IF_FALSE(mDecoder, "trying to decode without decoder!"); mDecodingMutex.AssertCurrentThreadOwns(); // First, if we've just been called because we allocated a frame on the main // thread, let the decoder deal with the data it set aside at that time by // passing it a null buffer. if (mDecodeRequest->mAllocatedNewFrame) { mDecodeRequest->mAllocatedNewFrame = false; nsresult rv = WriteToDecoder(nullptr, 0); if (NS_FAILED(rv) || mDecoder->NeedsNewFrame()) { return rv; } } // If we have nothing else to decode, return if (mBytesDecoded == mSourceData.Length()) return NS_OK; MOZ_ASSERT(mBytesDecoded < mSourceData.Length()); // write the proper amount of data uint32_t bytesToDecode = std::min(aMaxBytes, mSourceData.Length() - mBytesDecoded); nsresult rv = WriteToDecoder(mSourceData.Elements() + mBytesDecoded, bytesToDecode); return rv; } // There are various indicators that tell us we're finished with the decode // task at hand and can shut down the decoder. // // This method may not be called if there is no decoder. bool RasterImage::IsDecodeFinished() { // Precondition mDecodingMutex.AssertCurrentThreadOwns(); NS_ABORT_IF_FALSE(mDecoder, "Can't call IsDecodeFinished() without decoder!"); // The decode is complete if we got what we wanted. if (mDecoder->IsSizeDecode()) { if (mDecoder->HasSize()) { return true; } } else if (mDecoder->GetDecodeDone()) { return true; } // If the decoder returned because it needed a new frame and we haven't // written to it since then, the decoder may be storing data that it hasn't // decoded yet. if (mDecoder->NeedsNewFrame() || (mDecodeRequest && mDecodeRequest->mAllocatedNewFrame)) { return false; } // Otherwise, if we have all the source data and wrote all the source data, // we're done. // // (NB - This can be the case even for non-erroneous images because // Decoder::GetDecodeDone() might not return true until after we call // Decoder::Finish() in ShutdownDecoder()) if (mHasSourceData && (mBytesDecoded == mSourceData.Length())) { return true; } // If we get here, assume it's not finished. return false; } // Indempotent error flagging routine. If a decoder is open, shuts it down. void RasterImage::DoError() { // If we've flagged an error before, we have nothing to do if (mError) return; // If we're mid-decode, shut down the decoder. if (mDecoder) { MutexAutoLock lock(mDecodingMutex); FinishedSomeDecoding(eShutdownIntent_Error); } // Put the container in an error state mError = true; if (mDecodeRequest) { mDecodeRequest->mStatusTracker->GetDecoderObserver()->OnError(); } else { mStatusTracker->GetDecoderObserver()->OnError(); } // Log our error LOG_CONTAINER_ERROR; } // nsIInputStream callback to copy the incoming image data directly to the // RasterImage without processing. The RasterImage is passed as the closure. // Always reads everything it gets, even if the data is erroneous. NS_METHOD RasterImage::WriteToRasterImage(nsIInputStream* /* unused */, void* aClosure, const char* aFromRawSegment, uint32_t /* unused */, uint32_t aCount, uint32_t* aWriteCount) { // Retrieve the RasterImage RasterImage* image = static_cast<RasterImage*>(aClosure); // Copy the source data. Unless we hit OOM, we squelch the return value // here, because returning an error means that ReadSegments stops // reading data, violating our invariant that we read everything we get. // If we hit OOM then we fail and the load is aborted. nsresult rv = image->AddSourceData(aFromRawSegment, aCount); if (rv == NS_ERROR_OUT_OF_MEMORY) { image->DoError(); return rv; } // We wrote everything we got *aWriteCount = aCount; return NS_OK; } bool RasterImage::ShouldAnimate() { return ImageResource::ShouldAnimate() && mFrames.Length() >= 2 && !mAnimationFinished; } /* readonly attribute uint32_t framesNotified; */ #ifdef DEBUG NS_IMETHODIMP RasterImage::GetFramesNotified(uint32_t *aFramesNotified) { NS_ENSURE_ARG_POINTER(aFramesNotified); *aFramesNotified = mFramesNotified; return NS_OK; } #endif nsresult RasterImage::FinishedSomeDecoding(eShutdownIntent aIntent /* = eShutdownIntent_Done */, DecodeRequest* aRequest /* = nullptr */) { MOZ_ASSERT(NS_IsMainThread()); mDecodingMutex.AssertCurrentThreadOwns(); nsRefPtr<DecodeRequest> request; if (aRequest) { request = aRequest; } else { request = mDecodeRequest; } // Ensure that, if the decoder is the last reference to the image, we don't // destroy it by destroying the decoder. nsRefPtr<RasterImage> image(this); bool done = false; bool wasSize = false; nsresult rv = NS_OK; if (image->mDecoder) { image->mDecoder->MarkFrameDirty(); if (request && request->mChunkCount && !image->mDecoder->IsSizeDecode()) { Telemetry::Accumulate(Telemetry::IMAGE_DECODE_CHUNKS, request->mChunkCount); } if (!image->mHasSize && image->mDecoder->HasSize()) { image->mDecoder->SetSizeOnImage(); } // If the decode finished, or we're specifically being told to shut down, // tell the image and shut down the decoder. if (image->IsDecodeFinished() || aIntent != eShutdownIntent_Done) { done = true; // Hold on to a reference to the decoder until we're done with it nsRefPtr<Decoder> decoder = image->mDecoder; wasSize = decoder->IsSizeDecode(); // We need to shut down the decoder first, in order to ensure all // decoding routines have been finished. rv = image->ShutdownDecoder(aIntent); if (NS_FAILED(rv)) { image->DoError(); } // Do some telemetry if this isn't a size decode. if (request && !decoder->IsSizeDecode()) { Telemetry::Accumulate(Telemetry::IMAGE_DECODE_TIME, int32_t(request->mDecodeTime.ToMicroseconds())); // We record the speed for only some decoders. The rest have // SpeedHistogram return HistogramCount. Telemetry::ID id = decoder->SpeedHistogram(); if (id < Telemetry::HistogramCount) { int32_t KBps = int32_t(request->mImage->mBytesDecoded / (1024 * request->mDecodeTime.ToSeconds())); Telemetry::Accumulate(id, KBps); } } } } imgStatusTracker::StatusDiff diff; if (request) { diff = image->mStatusTracker->CalculateAndApplyDifference(request->mStatusTracker); } { // Notifications can't go out with the decoding lock held. MutexAutoUnlock unlock(mDecodingMutex); // Then, tell the observers what happened in the decoder. // If we have no request, we have not yet created a decoder, but we still // need to send out notifications. if (request) { image->mStatusTracker->SyncNotifyDifference(diff); } else { image->mStatusTracker->SyncNotifyDecodeState(); } // If we were a size decode and a full decode was requested, now's the time. if (NS_SUCCEEDED(rv) && aIntent != eShutdownIntent_Error && done && wasSize && image->mWantFullDecode) { image->mWantFullDecode = false; // If we're not meant to be storing source data and we just got the size, // we need to synchronously flush all the data we got to a full decoder. // When that decoder is shut down, we'll also clear our source data. if (!image->StoringSourceData()) { rv = image->SyncDecode(); } else { rv = image->RequestDecode(); } } } return rv; } NS_IMPL_THREADSAFE_ISUPPORTS1(RasterImage::DecodePool, nsIObserver) /* static */ RasterImage::DecodePool* RasterImage::DecodePool::Singleton() { if (!sSingleton) { MOZ_ASSERT(NS_IsMainThread()); sSingleton = new DecodePool(); ClearOnShutdown(&sSingleton); } return sSingleton; } RasterImage::DecodePool::DecodePool() : mThreadPoolMutex("Thread Pool") , mShuttingDown(false) { if (gMultithreadedDecoding) { mThreadPool = do_CreateInstance(NS_THREADPOOL_CONTRACTID); if (mThreadPool) { mThreadPool->SetName(NS_LITERAL_CSTRING("ImageDecoder")); if (gDecodingThreadLimit <= 0) { mThreadPool->SetThreadLimit(std::max(PR_GetNumberOfProcessors() - 1, 1)); } else { mThreadPool->SetThreadLimit(static_cast<uint32_t>(gDecodingThreadLimit)); } nsCOMPtr<nsIObserverService> obsSvc = mozilla::services::GetObserverService(); if (obsSvc) { obsSvc->AddObserver(this, "xpcom-shutdown-threads", false); } } } } RasterImage::DecodePool::~DecodePool() { MOZ_ASSERT(NS_IsMainThread(), "Must shut down DecodePool on main thread!"); } NS_IMETHODIMP RasterImage::DecodePool::Observe(nsISupports *subject, const char *topic, const PRUnichar *data) { NS_ASSERTION(strcmp(topic, "xpcom-shutdown-threads") == 0, "oops"); nsCOMPtr<nsIThreadPool> threadPool; { MutexAutoLock threadPoolLock(mThreadPoolMutex); threadPool = mThreadPool; mThreadPool = nullptr; mShuttingDown = true; } if (threadPool) { threadPool->Shutdown(); } return NS_OK; } void RasterImage::DecodePool::RequestDecode(RasterImage* aImg) { MOZ_ASSERT(aImg->mDecoder); aImg->mDecodingMutex.AssertCurrentThreadOwns(); // If we're currently waiting on a new frame for this image, we can't do any // decoding. if (!aImg->mDecoder->NeedsNewFrame()) { // No matter whether this is currently being decoded, we need to update the // number of bytes we want it to decode. aImg->mDecodeRequest->mBytesToDecode = aImg->mSourceData.Length() - aImg->mBytesDecoded; if (aImg->mDecodeRequest->mRequestStatus == DecodeRequest::REQUEST_PENDING || aImg->mDecodeRequest->mRequestStatus == DecodeRequest::REQUEST_ACTIVE) { // The image is already in our list of images to decode, or currently being // decoded, so we don't have to do anything else. return; } aImg->mDecodeRequest->mRequestStatus = DecodeRequest::REQUEST_PENDING; nsRefPtr<DecodeJob> job = new DecodeJob(aImg->mDecodeRequest, aImg); MutexAutoLock threadPoolLock(mThreadPoolMutex); if (mShuttingDown) { // Just drop the job on the floor; we won't need it. } else if (!gMultithreadedDecoding || !mThreadPool) { NS_DispatchToMainThread(job); } else { mThreadPool->Dispatch(job, nsIEventTarget::DISPATCH_NORMAL); } } } void RasterImage::DecodePool::DecodeABitOf(RasterImage* aImg) { MOZ_ASSERT(NS_IsMainThread()); aImg->mDecodingMutex.AssertCurrentThreadOwns(); if (aImg->mDecodeRequest) { // If the image is waiting for decode work to be notified, go ahead and do that. if (aImg->mDecodeRequest->mRequestStatus == DecodeRequest::REQUEST_WORK_DONE) { aImg->FinishedSomeDecoding(); } } DecodeSomeOfImage(aImg); aImg->FinishedSomeDecoding(); // If the decoder needs a new frame, enqueue an event to get it; that event // will enqueue another decode request when it's done. if (aImg->mDecoder && aImg->mDecoder->NeedsNewFrame()) { FrameNeededWorker::GetNewFrame(aImg); } else { // If we aren't yet finished decoding and we have more data in hand, add // this request to the back of the priority list. if (aImg->mDecoder && !aImg->mError && !aImg->IsDecodeFinished() && aImg->mSourceData.Length() > aImg->mBytesDecoded) { RequestDecode(aImg); } } } /* static */ void RasterImage::DecodePool::StopDecoding(RasterImage* aImg) { aImg->mDecodingMutex.AssertCurrentThreadOwns(); // If we haven't got a decode request, we're not currently decoding. (Having // a decode request doesn't imply we *are* decoding, though.) if (aImg->mDecodeRequest) { aImg->mDecodeRequest->mRequestStatus = DecodeRequest::REQUEST_STOPPED; } } NS_IMETHODIMP RasterImage::DecodePool::DecodeJob::Run() { MutexAutoLock imglock(mImage->mDecodingMutex); // If we were interrupted, we shouldn't do any work. if (mRequest->mRequestStatus == DecodeRequest::REQUEST_STOPPED) { DecodeDoneWorker::NotifyFinishedSomeDecoding(mImage, mRequest); return NS_OK; } // If someone came along and synchronously decoded us, there's nothing for us to do. if (!mImage->mDecoder || mImage->IsDecodeFinished()) { DecodeDoneWorker::NotifyFinishedSomeDecoding(mImage, mRequest); return NS_OK; } // If we're a decode job that's been enqueued since a previous decode that // still needs a new frame, we can't do anything. Wait until the // FrameNeededWorker enqueues another frame. if (mImage->mDecoder->NeedsNewFrame()) { return NS_OK; } mRequest->mRequestStatus = DecodeRequest::REQUEST_ACTIVE; uint32_t oldByteCount = mImage->mBytesDecoded; DecodeType type = DECODE_TYPE_UNTIL_DONE_BYTES; // Multithreaded decoding can be disabled. If we've done so, we don't want to // monopolize the main thread, and will allow a timeout in DecodeSomeOfImage. if (NS_IsMainThread()) { type = DECODE_TYPE_UNTIL_TIME; } DecodePool::Singleton()->DecodeSomeOfImage(mImage, type, mRequest->mBytesToDecode); uint32_t bytesDecoded = mImage->mBytesDecoded - oldByteCount; mRequest->mRequestStatus = DecodeRequest::REQUEST_WORK_DONE; // If the decoder needs a new frame, enqueue an event to get it; that event // will enqueue another decode request when it's done. if (mImage->mDecoder && mImage->mDecoder->NeedsNewFrame()) { FrameNeededWorker::GetNewFrame(mImage); } // If we aren't yet finished decoding and we have more data in hand, add // this request to the back of the list. else if (mImage->mDecoder && !mImage->mError && !mImage->IsDecodeFinished() && bytesDecoded < mRequest->mBytesToDecode && bytesDecoded > 0) { DecodePool::Singleton()->RequestDecode(mImage); } else { // Nothing more for us to do - let everyone know what happened. DecodeDoneWorker::NotifyFinishedSomeDecoding(mImage, mRequest); } return NS_OK; } nsresult RasterImage::DecodePool::DecodeUntilSizeAvailable(RasterImage* aImg) { MOZ_ASSERT(NS_IsMainThread()); MutexAutoLock imgLock(aImg->mDecodingMutex); if (aImg->mDecodeRequest) { // If the image is waiting for decode work to be notified, go ahead and do that. if (aImg->mDecodeRequest->mRequestStatus == DecodeRequest::REQUEST_WORK_DONE) { nsresult rv = aImg->FinishedSomeDecoding(); if (NS_FAILED(rv)) { aImg->DoError(); return rv; } } } nsresult rv = DecodeSomeOfImage(aImg, DECODE_TYPE_UNTIL_SIZE); if (NS_FAILED(rv)) { return rv; } // If the decoder needs a new frame, enqueue an event to get it; that event // will enqueue another decode request when it's done. if (aImg->mDecoder && aImg->mDecoder->NeedsNewFrame()) { FrameNeededWorker::GetNewFrame(aImg); } else { rv = aImg->FinishedSomeDecoding(); } return rv; } nsresult RasterImage::DecodePool::DecodeSomeOfImage(RasterImage* aImg, DecodeType aDecodeType /* = DECODE_TYPE_UNTIL_TIME */, uint32_t bytesToDecode /* = 0 */) { NS_ABORT_IF_FALSE(aImg->mInitialized, "Worker active for uninitialized container!"); aImg->mDecodingMutex.AssertCurrentThreadOwns(); // If an error is flagged, it probably happened while we were waiting // in the event queue. if (aImg->mError) return NS_OK; // If mDecoded or we don't have a decoder, we must have finished already (for // example, a synchronous decode request came while the worker was pending). if (!aImg->mDecoder || aImg->mDecoded) return NS_OK; // If we're doing synchronous decodes, and we're waiting on a new frame for // this image, get it now. if (aImg->mDecoder->IsSynchronous() && aImg->mDecoder->NeedsNewFrame()) { MOZ_ASSERT(NS_IsMainThread()); aImg->mDecoder->AllocateFrame(); aImg->mDecodeRequest->mAllocatedNewFrame = true; } // If we're not synchronous, we can't allocate a frame right now. else if (aImg->mDecoder->NeedsNewFrame()) { return NS_OK; } nsRefPtr<Decoder> decoderKungFuDeathGrip = aImg->mDecoder; uint32_t maxBytes; if (aImg->mDecoder->IsSizeDecode()) { // Decode all available data if we're a size decode; they're cheap, and we // want them to be more or less synchronous. maxBytes = aImg->mSourceData.Length(); } else { // We're only guaranteed to decode this many bytes, so in particular, // gDecodeBytesAtATime should be set high enough for us to read the size // from most images. maxBytes = gDecodeBytesAtATime; } if (bytesToDecode == 0) { bytesToDecode = aImg->mSourceData.Length() - aImg->mBytesDecoded; } int32_t chunkCount = 0; TimeStamp start = TimeStamp::Now(); TimeStamp deadline = start + TimeDuration::FromMilliseconds(gMaxMSBeforeYield); // We keep decoding chunks until: // * we don't have any data left to decode, // * the decode completes, // * we're an UNTIL_SIZE decode and we get the size, or // * we run out of time. // We also try to decode at least one "chunk" if we've allocated a new frame, // even if we have no more data to send to the decoder. while ((aImg->mSourceData.Length() > aImg->mBytesDecoded && bytesToDecode > 0 && !aImg->IsDecodeFinished() && !(aDecodeType == DECODE_TYPE_UNTIL_SIZE && aImg->mHasSize) && !aImg->mDecoder->NeedsNewFrame()) || (aImg->mDecodeRequest && aImg->mDecodeRequest->mAllocatedNewFrame)) { chunkCount++; uint32_t chunkSize = std::min(bytesToDecode, maxBytes); nsresult rv = aImg->DecodeSomeData(chunkSize); if (NS_FAILED(rv)) { aImg->DoError(); return rv; } bytesToDecode -= chunkSize; // Yield if we've been decoding for too long. We check this _after_ decoding // a chunk to ensure that we don't yield without doing any decoding. if (aDecodeType == DECODE_TYPE_UNTIL_TIME && TimeStamp::Now() >= deadline) break; } if (aImg->mDecodeRequest) { aImg->mDecodeRequest->mDecodeTime += (TimeStamp::Now() - start); aImg->mDecodeRequest->mChunkCount += chunkCount; } // Flush invalidations (and therefore paint) now that we've decoded all the // chunks we're going to. // // However, don't paint if: // // * This was an until-size decode. Until-size decodes are always followed // by normal decodes, so don't bother painting. // // * The decoder flagged an error. The decoder may have written garbage // into the output buffer; don't paint it to the screen. // // * We have all the source data. This disables progressive display of // previously-decoded images, thus letting us finish decoding faster, // since we don't waste time painting while we decode. // Decoder::PostFrameStop() will flush invalidations once the decode is // done. if (aDecodeType != DECODE_TYPE_UNTIL_SIZE && !aImg->mDecoder->HasError() && !aImg->mHasSourceData) { aImg->mInDecoder = true; aImg->mDecoder->FlushInvalidations(); aImg->mInDecoder = false; } return NS_OK; } RasterImage::DecodeDoneWorker::DecodeDoneWorker(RasterImage* image, DecodeRequest* request) : mImage(image) , mRequest(request) {} void RasterImage::DecodeDoneWorker::NotifyFinishedSomeDecoding(RasterImage* image, DecodeRequest* request) { image->mDecodingMutex.AssertCurrentThreadOwns(); nsCOMPtr<DecodeDoneWorker> worker = new DecodeDoneWorker(image, request); NS_DispatchToMainThread(worker); } NS_IMETHODIMP RasterImage::DecodeDoneWorker::Run() { MOZ_ASSERT(NS_IsMainThread()); MutexAutoLock lock(mImage->mDecodingMutex); mImage->FinishedSomeDecoding(eShutdownIntent_Done, mRequest); return NS_OK; } RasterImage::FrameNeededWorker::FrameNeededWorker(RasterImage* image) : mImage(image) {} void RasterImage::FrameNeededWorker::GetNewFrame(RasterImage* image) { nsCOMPtr<FrameNeededWorker> worker = new FrameNeededWorker(image); NS_DispatchToMainThread(worker); } NS_IMETHODIMP RasterImage::FrameNeededWorker::Run() { MutexAutoLock lock(mImage->mDecodingMutex); nsresult rv = NS_OK; // If we got a synchronous decode in the mean time, we don't need to do // anything. if (mImage->mDecoder && mImage->mDecoder->NeedsNewFrame()) { rv = mImage->mDecoder->AllocateFrame(); mImage->mDecodeRequest->mAllocatedNewFrame = true; } if (NS_SUCCEEDED(rv) && mImage->mDecoder) { // By definition, we're not done decoding, so enqueue us for more decoding. DecodePool::Singleton()->RequestDecode(mImage); } return NS_OK; } } // namespace image } // namespace mozilla
31.572313
129
0.666818
[ "object", "transform" ]
ce434501b59fd30e2d584c000a9c0c83eeff8ba3
31,976
cpp
C++
main_windows.cpp
cohenrotem/pipe_flv2annexb
ed4be32532d2ddd58dd4dbe96e3e43790ded3937
[ "Unlicense" ]
4
2020-07-10T10:00:31.000Z
2021-12-10T14:34:58.000Z
main_windows.cpp
cohenrotem/pipe_flv2annexb
ed4be32532d2ddd58dd4dbe96e3e43790ded3937
[ "Unlicense" ]
null
null
null
main_windows.cpp
cohenrotem/pipe_flv2annexb
ed4be32532d2ddd58dd4dbe96e3e43790ded3937
[ "Unlicense" ]
null
null
null
// main_windows.cpp // ----------------- // Stream raw video frames to FFmpeg stdin PIPE, // FFmpeg encodes the video in H.264 codec and FLV(Flash Video) container format. // The code reads the FLV encoded data from FFmpeg stdout PIPE, // the AVC NAL units are extracted and converted from AVCC to Annex B format. // The output is a file containing H.264 elementary stream(in Annex B format). // Detailed documentation is included in main_linux.cpp file (the high level of Windows and Linux implementations is the same). #include <string> #include <math.h> #include <stdint.h> #include <tchar.h> #include <stdio.h> #include <stdlib.h> #include <strsafe.h> #include <windows.h> #include "opencv2/opencv.hpp" #include "opencv2/highgui.hpp" // https://docs.microsoft.com/en-us/windows/win32/procthread/creating-a-child-process-with-redirected-input-and-output //#define DO_TEST_ZERO_LATENCY // Enable for testing FFmpeg with zero frames latency (raw frame in, encoded out...) #undef DO_TEST_ZERO_LATENCY // Allow latency of multiple frames (first encoded frame is ready after multiple input raw video frames enters). #define DO_REDIRECT_STDERR_OF_CHILD_PROCESS_TO_STDOUT_OF_CURRENT_PROCESS // Enable for testing //#undef DO_REDIRECT_STDERR_OF_CHILD_PROCESS_TO_STDOUT_OF_CURRENT_PROCESS // Build synthetic "raw BGR" image for testing, image data is stored in <raw_img_bytes> output data buffer. static void MakeRawFrameAsBytes(int width, int height, int i, unsigned char raw_img_bytes[]) { int p = width / 60; cv::Mat img = cv::Mat(cv::Size(width, height), CV_8UC3, (void*)raw_img_bytes, width*3); img = cv::Scalar(60, 60, 60); std::string text = std::to_string(i + 1); int base_line; cv::Size tsize = cv::getTextSize(text, cv::FONT_HERSHEY_DUPLEX, (double)p, p * 2, &base_line); cv::putText(img, text, cv::Point((width-tsize.width)/2, (height+tsize.height)/2), cv::FONT_HERSHEY_DUPLEX, (double)p, cv::Scalar(255, 30, 30), p*2); // Blue number } // https://docs.microsoft.com/en-us/windows/win32/procthread/creating-a-child-process-with-redirected-input-and-output // Format a readable error message, display a message box, and exit from the application. void ErrorExit(const TCHAR *lpszFunction) { LPVOID lpMsgBuf; LPVOID lpDisplayBuf; DWORD dw = GetLastError(); FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, NULL, dw, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); lpDisplayBuf = (LPVOID)LocalAlloc(LMEM_ZEROINIT, (lstrlen((LPCTSTR)lpMsgBuf) + lstrlen((LPCTSTR)lpszFunction) + 40) * sizeof(TCHAR)); StringCchPrintf((LPTSTR)lpDisplayBuf, LocalSize(lpDisplayBuf) / sizeof(TCHAR), TEXT("%s failed with error %d: %s"), lpszFunction, dw, lpMsgBuf); MessageBox(NULL, (LPCTSTR)lpDisplayBuf, TEXT("Error"), MB_OK); LocalFree(lpMsgBuf); LocalFree(lpDisplayBuf); ExitProcess(1); } class CSubprocess { private: // The following members are global variables in Microsoft code sample. HANDLE m_hChildStd_IN_Rd = nullptr; HANDLE m_hChildStd_IN_Wr = nullptr; HANDLE m_hChildStd_OUT_Rd = nullptr; HANDLE m_hChildStd_OUT_Wr = nullptr; // The following members are not used in Microsoft code sample. wchar_t *m_cmd_as_wchar = nullptr; bool m_is_stdin_pipe = false; bool m_is_stdout_pipe = false; CSubprocess() { } ~CSubprocess() { if (m_cmd_as_wchar != nullptr) { delete[] m_cmd_as_wchar; } } // Create a child process that uses the previously created pipes for STDIN and STDOUT. bool createChildProcess() { // TCHAR szCmdline[] = TEXT("child"); PROCESS_INFORMATION piProcInfo; STARTUPINFO siStartInfo; BOOL bSuccess = FALSE; // Set up members of the PROCESS_INFORMATION structure. ZeroMemory(&piProcInfo, sizeof(PROCESS_INFORMATION)); // Set up members of the STARTUPINFO structure. // This structure specifies the STDIN and STDOUT handles for redirection. ZeroMemory(&siStartInfo, sizeof(STARTUPINFO)); siStartInfo.cb = sizeof(STARTUPINFO); siStartInfo.hStdError = m_hChildStd_OUT_Wr; siStartInfo.hStdOutput = m_hChildStd_OUT_Wr; siStartInfo.hStdInput = m_hChildStd_IN_Rd; siStartInfo.dwFlags |= STARTF_USESTDHANDLES; /*** Rotem ***/ #ifdef DO_REDIRECT_STDERR_OF_CHILD_PROCESS_TO_STDOUT_OF_CURRENT_PROCESS siStartInfo.hStdError = GetStdHandle(STD_OUTPUT_HANDLE); // Redirect stderr of child process to stdout of current (parent) process (for testing). #endif /*** Rotem ***/ // Create the child process. bSuccess = CreateProcess(NULL, m_cmd_as_wchar, // command line NULL, // process security attributes NULL, // primary thread security attributes TRUE, // handles are inherited 0, // creation flags NULL, // use parent's environment NULL, // use parent's current directory &siStartInfo, // STARTUPINFO pointer &piProcInfo); // receives PROCESS_INFORMATION // If an error occurs, exit the application. if (!bSuccess) { //ErrorExit(TEXT("CreateProcess")); return false; } else { // Close handles to the child process and its primary thread. // Some applications might keep these handles to monitor the status // of the child process, for example. CloseHandle(piProcInfo.hProcess); CloseHandle(piProcInfo.hThread); // Close handles to the stdin and stdout pipes no longer needed by the child process. // If they are not explicitly closed, there is no way to recognize that the child process has ended. CloseHandle(m_hChildStd_OUT_Wr); CloseHandle(m_hChildStd_IN_Rd); return true; } } public: // Executes child process with (optional) stdin and stdout pipes. // Return pointer to CSubprocess object in case of success, and nullptr in case of failure. // Remark: using std::wstring instead of std::string is not very useful here (cmd may contain unicode charcters). static CSubprocess *Popen(const std::wstring cmd, const bool is_stdin_pipe = false, const bool is_stdout_pipe = false, const int buf_size = 0) { CSubprocess *sp = new CSubprocess(); sp->m_cmd_as_wchar = new wchar_t[cmd.length() + 1]; wcscpy_s(sp->m_cmd_as_wchar, cmd.length() + 1, cmd.c_str()); sp->m_is_stdin_pipe = is_stdin_pipe; sp->m_is_stdout_pipe = is_stdout_pipe; // Set the bInheritHandle flag so pipe handles are inherited. SECURITY_ATTRIBUTES saAttr; saAttr.nLength = sizeof(SECURITY_ATTRIBUTES); saAttr.bInheritHandle = TRUE; saAttr.lpSecurityDescriptor = NULL; BOOL success; if (is_stdout_pipe) { // Create a pipe for the child process's STDOUT. success = CreatePipe(&sp->m_hChildStd_OUT_Rd, &sp->m_hChildStd_OUT_Wr, &saAttr, (DWORD)buf_size); if (!success) { // ErrorExit(TEXT("StdoutRd CreatePipe")); fprintf(stderr, "Error: StdoutRd CreatePipe\n"); delete sp; return nullptr; } // Ensure the read handle to the pipe for STDOUT is not inherited. success = SetHandleInformation(sp->m_hChildStd_OUT_Rd, HANDLE_FLAG_INHERIT, 0); if (!success) { // ErrorExit(TEXT("StdoutRd CreatePipe")); fprintf(stderr, "Error: Stdout SetHandleInformation\n"); delete sp; return nullptr; } } if (is_stdin_pipe) { // Create a pipe for the child process's STDIN. success = CreatePipe(&sp->m_hChildStd_IN_Rd, &sp->m_hChildStd_IN_Wr, &saAttr, (DWORD)buf_size); if (!success) { // ErrorExit(TEXT("Stdin CreatePipe")); fprintf(stderr, "Error: Stdin CreatePipe\n"); delete sp; return nullptr; } // Ensure the write handle to the pipe for STDIN is not inherited. success = SetHandleInformation(sp->m_hChildStd_IN_Wr, HANDLE_FLAG_INHERIT, 0); if (!success) { // ErrorExit(TEXT("Stdin SetHandleInformation")); fprintf(stderr, "Error: Stdin SetHandleInformation\n"); delete sp; return nullptr; } } // Create the child process. bool is_success = sp->createChildProcess(); if (!is_success) { // If an error occurs, exit the application. delete sp; return nullptr; } return sp; } // Close sdtin PIPE and delete sp. static bool ClosePipeAndDeleteObj(CSubprocess *sp) { if (sp != nullptr) { if (sp->m_hChildStd_IN_Wr != nullptr) { BOOL success = CloseHandle(sp->m_hChildStd_IN_Wr); if (!success) { return false; } } delete sp; } return true; } // Write to stdin PIPE and flush bool stdinWrite(const unsigned char *data_bytes, const unsigned int len) { DWORD dwWritten = 0; BOOL success = WriteFile(m_hChildStd_IN_Wr, (LPCVOID)data_bytes, (DWORD)len, &dwWritten, NULL); if (!success) { return false; } else { if (dwWritten != (DWORD)len) { fprintf(stderr, "len = %d, dwWritten = %d Why???\n", len, (int)dwWritten); } } success = FlushFileBuffers(m_hChildStd_IN_Wr); if (!success) { fprintf(stderr, "FlushFileBuffers failed\n"); return false; } return true; } // Read from stdout PIPE bool stdoutRead(const unsigned int len, unsigned char *data_bytes) { DWORD dwRead = 0; // The third argument of ReadFile is nNumberOfBytesToRead is the "The maximum number of bytes to be read." // We must use a loop for reading exactly <len> bytes from the pipe. int remain_len = (int)len; unsigned char *data_bytes_ptr = data_bytes; // Keep reading until finish reading <len> bytes from the PIPE. while (remain_len > 0) { BOOL success = ReadFile(m_hChildStd_OUT_Rd, data_bytes_ptr, (DWORD)remain_len, &dwRead, NULL); if (!success) { return false; } remain_len -= (int)dwRead; // Subtract number of bytes read from remain_len data_bytes_ptr += dwRead; // Advance pointer by number of bytes read. } return true; } // Close stdin PIPE // Note: there is some code duplication from ClosePipeAndDeleteObj function (but ClosePipeAndDeleteObj was [kind of] taken from Microsoft code sample, and just kept) bool stdinClose() { if (m_hChildStd_IN_Wr != nullptr) { BOOL success = CloseHandle(m_hChildStd_IN_Wr); m_hChildStd_IN_Wr = nullptr; // Mark as "closed", even if not success. if (!success) { return false; } } return true; } }; // Read header of FLV packet and return FLV payload size // After the header, the file is split into packets called "FLV tags", // which have 15 - byte packet headers. // The first four bytes denote the size of the previous packet / tag // (including the header without the first field), and aid in seeking backward // <buf> - Pointer to sketch buffer - must be large enough (width*height*3 assumed to be large enough), but there is no size checking. // Return -1 in case of an error. // Return flv_payload_size if success. static int ReadFlvPacketHeader(CSubprocess *ffmpeg_process, unsigned char *buf) { // Read size_of_previous_packet, packet_type, flv_payload_size, timestamp_lower, timestamp_upper, stream_id bool success = ffmpeg_process->stdoutRead(4 + 1 + 3 + 3 + 1 + 3, buf); if (!success) { fprintf(stderr, "Unsuccessful ffmpeg_process read from PIPE in ReadFlvPacketHeader\n"); return -1; } //size_of_previous_packet = f.read(4) # For first packet set to NULL(uint32 big - endian) //packet_type = f.read(1) # For first packet set to AMF Metadata //flv_payload_size = f.read(3) # For first packet set to AMF Metadata(uint24 big - endian) //timestamp_lower = f.read(3) # For first packet set to NULL(uint24 big - endian) //timestamp_upper = f.read(1) # Extension to create a uint32_be value(0) //stream_id = f.read(3) # For first stream of same type set to NULL(uint24 big - endian) //if len(flv_payload_size) < 3: return 0 # End of file. int flv_payload_size = ((int)buf[5] << 16) + ((int)buf[6] << 8) + (int)buf[7]; // Convert uint24 big - endian to integer value return flv_payload_size; } // FLV files start with a standard header (9 bytes). // After the header comes the first payload, which contains irrelevant data. // The function reads the header and the first payload data. // <buf> - Pointer to sketch buffer - must be large enough (width*height*3 assumed to be large enough), but there is no size checking. static bool ReadFlvFileHeaderAndFirstPayload(CSubprocess *ffmpeg_process, unsigned char *buf) { // https ://en.wikipedia.org/wiki/Flash_Video // Read FLV signature, version, flag byte and 4 bytes "used to skip a newer expanded header". bool success = ffmpeg_process->stdoutRead(5+4, buf); if (!success) { fprintf(stderr, "Unsuccessful ffmpeg_process read from PIPE in ReadFlvFileHeaderAndFirstPayload\n"); return false; } if (((char)buf[0] != 'F') || ((char)buf[1] != 'L') || ((char)buf[2] != 'V')) { // FLV file must start with "FLV" letters. fprintf(stderr, "Bad signature: FLV stream doesn't start with FLV letters\n"); return false; } unsigned char version_byte = buf[3]; if (version_byte != 1) { // Version byte must be 1 fprintf(stderr, "Bad version: FLV version is not 1\n"); return false; } unsigned char flags_byte = buf[4]; if (flags_byte != 1) { fprintf(stderr, "Bad flag byte: flags_byte = %d ... Bitmask: 0x04 is audio, 0x01 is video (so 0x05 is audio+video), but we expect video only\n", (int)flags_byte); return false; } // Read first packet(and ignore it). int flv_payload_size = ReadFlvPacketHeader(ffmpeg_process, buf); if (flv_payload_size < 0) { fprintf(stderr, "Error: ReadFlvPacketHeader (in ReadFlvFileHeaderAndFirstPayload) returned negative value (marking an error)\n"); return false; } // Read "frame_type and _codec_id" byte and "AVC packet type" and payload data. success = ffmpeg_process->stdoutRead(flv_payload_size, buf); if (!success) { fprintf(stderr, "Unsuccessful ffmpeg_process read from PIPE in ReadFlvFileHeaderAndFirstPayload\n"); return false; } int codec_id = (int)buf[0] & 0xF; //int frame_type = (int)buf[0] >> 4; // 1 - keyframe, 2 - inter frame if (codec_id != 7) { fprintf(stderr, "Bad codec ID: Codec ID is not AVC. codec_id = %d, instead of 7\n", (int)codec_id); return false; } // Read AVC packet type for testing //int avc_packet_type = (int)buf[1] // 0 - AVC sequence header, 1 - AVC NALU, 2 - AVC end of sequence // Ignore the data of the first payload (the first payload is just "meta data"). return true; } // Read the 5 bytes of FLV packet header, and return codec_id // https://www.adobe.com/content/dam/acom/en/devnet/flv/video_file_format_spec_v10.pdf // <buf> - Pointer to sketch buffer - must be large enough (width*height*3 assumed to be large enough), but there is no size checking. // <annexb_payload_buf> - Pointer to output buffer (Annex B payload) - must be large enough (width*height*3 assumed to be large enough), but there is no size checking. // Return -1 in case of an error. // Return Codec ID if success. static int ReadPacket5BytesHeader(CSubprocess *ffmpeg_process, unsigned char *buf) { // Read "frame_type and _codec_id" byte and avc_packet_type and composition_time. // According to video_file_format_spec_v10.pdf, if codec_id = 7, next comes AVCVIDEOPACKET bool success = ffmpeg_process->stdoutRead(5, buf); if (!success) { fprintf(stderr, "Unsuccessful ffmpeg_process read from PIPE in ReadPacket5BytesHeader\n"); return -1; } int codec_id = (int)buf[0] & 0xF; //int frame_type = (int)buf[0] >> 4; // 1 - keyframe, 2 - inter frame if (codec_id != 7) { fprintf(stderr, "Bad codec ID: Codec ID is not AVC. codec_id = %d, instead of 7\n", (int)codec_id); return -1; } unsigned char avc_packet_type = buf[1]; // 0 - AVC sequence header, 1 - AVC NALU, 2 - AVC end of sequence if (avc_packet_type != 1) { fprintf(stderr, "Bad packet type: avc_packet_type = %d instead of 1\n", (int)codec_id); return -1; } return codec_id; } // Read FLV payload, and convert it to AVC Annex B format. // Return Annex B data as bytes array(return None if end of file). // The FLV payload may contain several AVC NAL units(in AVCC format). // https://yumichan.net/video-processing/video-compression/introduction-to-h264-nal-unit/ """ // <buf> - Pointer to sketch buffer - must be large enough (width*height*3 assumed to be large enough), but there is no size checking. // <annexb_payload_buf> - Pointer to output buffer (Annex B payload) - must be large enough (width*height*3 assumed to be large enough), but there is no size checking. // Return -1 in case of an error. // Return Annex B payload size if success. static int ReadFlvPayloadAndConvertToAnnexB(CSubprocess *ffmpeg_process, unsigned char *buf, unsigned char *annexb_payload_buf) { int annexb_payload_idx = 0; // Index in annexb_payload_buf // Read first packet(and ignore it). int flv_payload_size = ReadFlvPacketHeader(ffmpeg_process, buf); if (flv_payload_size < 0) { fprintf(stderr, "Error: ReadFlvPacketHeader returned negative value (marking an error)\n"); return -1; } int codec_id = ReadPacket5BytesHeader(ffmpeg_process, buf); if (codec_id < 0) { fprintf(stderr, "Error: ReadPacket5BytesHeader failed\n"); return -1; } flv_payload_size -= 5; // After reading the "5 Bytes Header", remaining size is 5 bytes less // Keep reading AVC NAL units, until flv_payload_size is zero (flv_payload_size holds the remaining size). while (flv_payload_size > 0) { bool success = ffmpeg_process->stdoutRead(4, buf); // Read NAL unit size(uin32, big endian). if (!success) { fprintf(stderr, "Unsuccessful ffmpeg_process read from PIPE in ReadFlvPayloadAndConvertToAnnexB\n"); return -1; } flv_payload_size -= 4; // Remaining size is 4 bytes less // Convert uint32 big - endian to integer value int nal_size = ((int)buf[0] << 24) + ((int)buf[1] << 16) + ((int)buf[2] << 8) + (int)buf[3]; success = ffmpeg_process->stdoutRead(nal_size, buf); // Read NAL unit data if (!success) { fprintf(stderr, "Unsuccessful ffmpeg_process read from PIPE in ReadFlvPayloadAndConvertToAnnexB\n"); return -1; } flv_payload_size -= nal_size; // Remaining size is nal_size bytes less // The number of leading zeros(2 or 3) has minor differences between encoders(the implementation tries to match the selected encoder). // if do_use_intel_quick_sync if ((nal_data[0] & 0xF) == 5) or (nal_data[0] & 0xF == 1)... See Python code sample... if (((buf[0] & 0xF) == 5) || ((buf[0] & 0xF) == 6)) { // Coded slice of an IDR picture(for some reason begins with only 2 zeros when encoding with libx264) // SEI NAL unit(nal_data[0] == 6) is also begin with only 2 zeros. // annexb_payload_head = b'\x00\x00\x01' # Concatenate[0, 0, 1] to end of annexb_payload, and then NAL data annexb_payload_buf[annexb_payload_idx] = 0; annexb_payload_buf[annexb_payload_idx+1] = 0; annexb_payload_buf[annexb_payload_idx+2] = 1; annexb_payload_idx += 3; // Advance index by 3 (3 bytes were inserted). } else { // Other NAL units begins with 0 0 0 0 1 (for matching FFmpeg Annex B encoded stream) // annexb_payload_head = b'\x00\x00\x00\x01' # Concatenate[0, 0, 0, 1] to end of annexb_payload, and then NAL data annexb_payload_buf[annexb_payload_idx] = 0; annexb_payload_buf[annexb_payload_idx + 1] = 0; annexb_payload_buf[annexb_payload_idx + 2] = 0; annexb_payload_buf[annexb_payload_idx + 3] = 1; annexb_payload_idx += 4; // Advance index by 4 (4 bytes were inserted). } // Concatenate NAL data in Annex B format to annexb_payload // Copy NAL unit data from buf to annexb_payload_buf (not most efficient solution, but probably negligible). memcpy(&annexb_payload_buf[annexb_payload_idx], buf, nal_size); annexb_payload_idx += nal_size; // Advance index by nal_size bytes. } // The value of annexb_payload_idx equals the number of bytes copied to annexb_payload_buf. return annexb_payload_idx; } int main() { // 100 frames, resolution 1280x720, and 25 fps const int width = 1280; const int height = 720; const int n_frames = 100; const int fps = 25; const int raw_image_size_in_bytes = width * height * 3; bool success; int annexb_payload_len; FILE *out_f = nullptr; unsigned char *raw_img_bytes = new unsigned char[raw_image_size_in_bytes]; unsigned char *flv_bytes = new unsigned char[raw_image_size_in_bytes]; // Allocate much larger buffer than necessary. unsigned char *annexb_payload_buf = new unsigned char[raw_image_size_in_bytes]; // Allocate much larger buffer than necessary. if ((raw_img_bytes == nullptr) || (flv_bytes == nullptr) || (annexb_payload_buf == nullptr)) { ErrorExit(TEXT("Memory allocation error???")); } #ifdef DO_TEST_ZERO_LATENCY const int n_frames_latency = 0; // Latency of zero frames // FFmpeg subprocess with input PIPE (raw BGR video frames) and output PIPE (H.264 encoded stream in FLV container). const std::wstring ffmpeg_cmd = L"ffmpeg.exe -hide_banner -threads 1 -framerate " + std::to_wstring(fps) + L" -video_size " + std::to_wstring(width) + L"x" + std::to_wstring(height) + L" -pixel_format bgr24 -f rawvideo -an -sn -dn -i pipe: -threads 1 -vcodec libx264 " + L"-x264-params bframes=0:force-cfr=1:no-mbtree=1:sync-lookahead=0:sliced-threads=1:rc-lookahead=0 " + L"-g 10 -pix_fmt yuv444p -crf 10 " + L"-f flv -flvflags no_sequence_end+no_metadata+no_duration_filesize -bsf:v dump_extra -an -sn -dn pipe:"; // FFmpeg subprocess with same arguments, but without FLV container, and save output to a file (instead of stdout PIPE) for testing. const std::wstring ffmpeg_test_cmd = L"ffmpeg.exe -y -hide_banner -threads 1 -framerate " + std::to_wstring(fps) + L" -video_size " + std::to_wstring(width) + L"x" + std::to_wstring(height) + L" -pixel_format bgr24 -f rawvideo -an -sn -dn -i pipe: -threads 1 -vcodec libx264 " + L"-x264-params bframes=0:force-cfr=1:no-mbtree=1:sync-lookahead=0:sliced-threads=1:rc-lookahead=0 " + L"-g 10 -pix_fmt yuv444p -crf 10 -f h264 -an -sn -dn out.264"; #else // Using the following setting results latency of many frames const int n_frames_latency = 26; // The exact value was found by trial and error // FFmpeg subprocess with input PIPE (raw BGR video frames) and output PIPE (H.264 encoded stream in FLV container). const std::wstring ffmpeg_cmd = L"ffmpeg.exe -hide_banner -threads 1 -framerate " + std::to_wstring(fps) + L" -video_size " + std::to_wstring(width) + L"x" + std::to_wstring(height) + L" -pixel_format bgr24 -f rawvideo -an -sn -dn -i pipe: -threads 1 -vcodec libx264 " + L"-g 25 -bf 3 -pix_fmt yuv444p -crf 10 " + L"-f flv -flvflags no_sequence_end+no_metadata+no_duration_filesize -bsf:v dump_extra -an -sn -dn pipe:"; // FFmpeg subprocess with same arguments, but without FLV container, and save output to a file (instead of stdout PIPE) for testing. const std::wstring ffmpeg_test_cmd = L"ffmpeg.exe -y -hide_banner -threads 1 -framerate " + std::to_wstring(fps) + L" -video_size " + std::to_wstring(width) + L"x" + std::to_wstring(height) + L" -pixel_format bgr24 -f rawvideo -an -sn -dn -i pipe: -threads 1 -vcodec libx264 " + L"-g 25 -bf 3 -pix_fmt yuv444p -crf 10 -f h264 -an -sn -dn out.264"; #endif // Create subprocess with stdin PIPE and stdout PIPE CSubprocess *ffmpeg_process = CSubprocess::Popen(ffmpeg_cmd, true, true, raw_image_size_in_bytes); if (ffmpeg_process == nullptr) { ErrorExit(TEXT("CreateProcess ffmpeg_process")); } // Create subprocess with stdin PIPE (used for testing). CSubprocess *ffmpeg_test_process = CSubprocess::Popen(ffmpeg_test_cmd, true, false, raw_image_size_in_bytes); if (ffmpeg_test_process == nullptr) { ErrorExit(TEXT("CreateProcess ffmpeg_test_process")); } bool was_broken_by_error = false; for (int i = 0; i < n_frames; i++) { MakeRawFrameAsBytes(width, height, i, raw_img_bytes); success = ffmpeg_process->stdinWrite(raw_img_bytes, raw_image_size_in_bytes); if (!success) { fprintf(stderr, "Unsuccessful ffmpeg_process write to PIPE\n"); was_broken_by_error = true; break; } // For testing success = ffmpeg_test_process->stdinWrite(raw_img_bytes, raw_image_size_in_bytes); if (!success) { fprintf(stderr, "Unsuccessful ffmpeg_test_process write to PIPE\n"); was_broken_by_error = true; break; } if (i == 0) { // Read FLV header that should be ignored. success = ReadFlvFileHeaderAndFirstPayload(ffmpeg_process, flv_bytes); if (!success) { fprintf(stderr, "ReadFlvFileHeaderAndFirstPayload failed\n"); was_broken_by_error = true; break; } // Open output file(Annex B stream format) fopen_s(&out_f, "out_avcc.264", "wb"); if (out_f == nullptr) { fprintf(stderr, "Error: failed to open file out_avcc.264 for writing\n"); was_broken_by_error = true; break; } } // Assume <n_frames_latency> frames latency // Note: the reading process is supposed to be in a separate thread (performed here for simplicity). if (i >= n_frames_latency) { // Read FLV payload data and convert the AVC NAL unit / units from AVCC format to Annex B format. annexb_payload_len = ReadFlvPayloadAndConvertToAnnexB(ffmpeg_process, flv_bytes, annexb_payload_buf); if (annexb_payload_len < 0) { fprintf(stderr, "ReadFlvPayloadAndConvertToAnnexB failed\n"); was_broken_by_error = true; break; } // Write encoded frame to output file. // Note: "encoded frame" may contain few NAL units, but each FLV payload applies one "encoded frame" (one "access unit"). fwrite(annexb_payload_buf, 1, annexb_payload_len, out_f); // Write to file for testing. } } // Close the "test process" (close the FFmpeg process that writes to out.264 file and used as reference). ////////////////////////////////////////////////////////////////////////// success = ffmpeg_test_process->stdinClose(); if (!success) { ErrorExit(TEXT("ffmpeg_test_process->stdinClose")); } success = CSubprocess::ClosePipeAndDeleteObj(ffmpeg_test_process); if (!success) { ErrorExit(TEXT("StdInWr CloseHandle")); } ////////////////////////////////////////////////////////////////////////// if (!was_broken_by_error) { // Closing stdin "pushes" all the remaining frames from the encoder to stdout (FFmpeg feature). success = ffmpeg_process->stdinClose(); if (!success) { ErrorExit(TEXT("ffmpeg_process->stdinClose")); } //Handle the last(delayed) "encoded frames". for (int i = 0; i < n_frames_latency; i++) { // Read FLV payload data and convert the AVC NAL unit / units from AVCC format to Annex B format. annexb_payload_len = ReadFlvPayloadAndConvertToAnnexB(ffmpeg_process, flv_bytes, annexb_payload_buf); if (annexb_payload_len < 0) { fprintf(stderr, "ReadFlvPayloadAndConvertToAnnexB failed\n"); was_broken_by_error = true; break; } fwrite(annexb_payload_buf, 1, annexb_payload_len, out_f); // Write to file for testing. } } if (out_f != nullptr) { fclose(out_f); } if (!was_broken_by_error) { // Read extra trailing 4 bytes(FFmpeg puts the 4 bytes as a footer [instead of a header of the next frame]). success = ffmpeg_process->stdoutRead(4, flv_bytes); if (!success) { fprintf(stderr, "Failed reading extra 4 footer bytes from sdtin???\n"); } } delete[] raw_img_bytes; delete[] flv_bytes; delete[] annexb_payload_buf; success = CSubprocess::ClosePipeAndDeleteObj(ffmpeg_process); if (!success) { ErrorExit(TEXT("StdInWr CloseHandle")); } return 0; }
38.852977
171
0.60805
[ "object" ]
ce4444f165a93fa4ede9ad74dc4ef5c1ae52e043
17,718
cpp
C++
server/src/log4cxx/apache-log4cxx-0.10.0/src/test/cpp/net/socketservertestcase.cpp
Steven0917/TT
64f16dc11e222ca46170e571c656375b5dd95392
[ "Apache-2.0" ]
249
2015-01-15T16:50:53.000Z
2022-03-24T13:23:34.000Z
server/src/log4cxx/apache-log4cxx-0.10.0/src/test/cpp/net/socketservertestcase.cpp
catkic/TeamChat
eeed62f2abd40b3cc0d96d887f5ab174fbe537e4
[ "Apache-2.0" ]
2,917
2015-01-12T16:17:49.000Z
2022-03-31T11:57:47.000Z
server/src/log4cxx/apache-log4cxx-0.10.0/src/test/cpp/net/socketservertestcase.cpp
catkic/TeamChat
eeed62f2abd40b3cc0d96d887f5ab174fbe537e4
[ "Apache-2.0" ]
306
2015-01-12T09:23:20.000Z
2022-01-28T18:06:30.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 <log4cxx/logger.h> #include <log4cxx/net/socketappender.h> #include <log4cxx/ndc.h> #include <log4cxx/mdc.h> #include <log4cxx/asyncappender.h> #include "socketservertestcase.h" #include "../util/compare.h" #include "../util/transformer.h" #include "../util/controlfilter.h" #include "../util/absolutedateandtimefilter.h" #include "../util/threadfilter.h" #include "../util/filenamefilter.h" #include <apr_time.h> #include <log4cxx/file.h> #include <iostream> #include <log4cxx/helpers/transcoder.h> #include <log4cxx/helpers/stringhelper.h> #include "../testchar.h" #include "../logunit.h" #include <log4cxx/spi/loggerrepository.h> //Define INT64_C for compilers that don't have it #if (!defined(INT64_C)) #define INT64_C(value) value ## LL #endif #if defined(WIN32) || defined(_WIN32) #include <windows.h> #endif using namespace log4cxx; using namespace log4cxx::helpers; using namespace log4cxx::net; #define REGEX_STR(x) x // %5p %x [%t] %c %m%n // DEBUG T1 [thread] org.apache.log4j.net.SocketAppenderTestCase Message 1 #define PAT1 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T1 \\[0x[0-9A-F]*]\\ ") \ REGEX_STR(".* Message [0-9]\\{1,2\\}") // DEBUG T2 [thread] patternlayouttest.cpp(?) Message 1 #define PAT2 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T2 \\[0x[0-9A-F]*]\\ ") \ REGEX_STR(".*socketservertestcase.cpp\\([0-9]\\{1,4\\}\\) Message [0-9]\\{1,2\\}") // DEBUG T3 [thread] patternlayouttest.cpp(?) Message 1 #define PAT3 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) T3 \\[0x[0-9A-F]*]\\ ") \ REGEX_STR(".*socketservertestcase.cpp\\([0-9]\\{1,4\\}\\) Message [0-9]\\{1,2\\}") // DEBUG some T4 MDC-TEST4 [thread] SocketAppenderTestCase - Message 1 // DEBUG some T4 MDC-TEST4 [thread] SocketAppenderTestCase - Message 1 #define PAT4 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some T4 MDC-TEST4 \\[0x[0-9A-F]*]\\") \ REGEX_STR(" (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}") #define PAT5 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some5 T5 MDC-TEST5 \\[0x[0-9A-F]*]\\") \ REGEX_STR(" (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}") #define PAT6 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some6 T6 client-test6 MDC-TEST6") \ REGEX_STR(" \\[0x[0-9A-F]*]\\ (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}") #define PAT7 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some7 T7 client-test7 MDC-TEST7") \ REGEX_STR(" \\[0x[0-9A-F]*]\\ (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}") // DEBUG some8 T8 shortSocketServer MDC-TEST7 [thread] SocketServerTestCase - Message 1 #define PAT8 \ REGEX_STR("^(DEBUG| INFO| WARN|ERROR|FATAL|LETHAL) some8 T8 shortSocketServer") \ REGEX_STR(" MDC-TEST8 \\[0x[0-9A-F]*]\\ (root|SocketServerTestCase) - Message [0-9]\\{1,2\\}") /** * This test checks receipt of SocketAppender messages by the ShortSocketServer * class from log4j. That class must be started externally to this class * for this test to succeed. */ LOGUNIT_CLASS(SocketServerTestCase) { LOGUNIT_TEST_SUITE(SocketServerTestCase); LOGUNIT_TEST(test1); LOGUNIT_TEST(test2); LOGUNIT_TEST(test3); LOGUNIT_TEST(test4); LOGUNIT_TEST(test5); LOGUNIT_TEST(test6); LOGUNIT_TEST(test7); LOGUNIT_TEST(test8); LOGUNIT_TEST_SUITE_END(); SocketAppenderPtr socketAppender; LoggerPtr logger; LoggerPtr root; class LineNumberFilter : public Filter { public: LineNumberFilter() { patterns.push_back(PatternReplacement("cpp:[0-9]*", "cpp:XXX")); } }; public: void setUp() { logger = Logger::getLogger(LOG4CXX_STR("org.apache.log4j.net.SocketServerTestCase")); root = Logger::getRootLogger(); } void tearDown() { socketAppender = 0; root->getLoggerRepository()->resetConfiguration(); logger = 0; root = 0; } /** The pattern on the server side: %5p %x [%t] %c %m%n. We are testing NDC functionality across the wire. */ void test1() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); root->addAppender(socketAppender1); common("test1", LOG4CXX_STR("T1"), LOG4CXX_STR("key1"), LOG4CXX_STR("MDC-TEST1")); delay(1); ControlFilter cf; cf << PAT1; ThreadFilter threadFilter; std::vector<Filter *> filters; filters.push_back(&cf); filters.push_back(&threadFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.1"))); } void test2() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); root->addAppender(socketAppender1); common("test2", LOG4CXX_STR("T2"), LOG4CXX_STR("key2"), LOG4CXX_STR("MDC-TEST2")); delay(1); ControlFilter cf; cf << PAT2; ThreadFilter threadFilter; LineNumberFilter lineNumberFilter; LogString thisFile; FilenameFilter filenameFilter(__FILE__, "socketservertestcase.cpp"); std::vector<Filter *> filters; filters.push_back(&filenameFilter); filters.push_back(&cf); filters.push_back(&threadFilter); filters.push_back(&lineNumberFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.2"))); } void test3() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); root->addAppender(socketAppender1); common("test3", LOG4CXX_STR("T3"), LOG4CXX_STR("key3"), LOG4CXX_STR("MDC-TEST3")); delay(1); ControlFilter cf; cf << PAT3; ThreadFilter threadFilter; LineNumberFilter lineNumberFilter; LogString thisFile; FilenameFilter filenameFilter(__FILE__, "socketservertestcase.cpp"); std::vector<Filter *> filters; filters.push_back(&filenameFilter); filters.push_back(&cf); filters.push_back(&threadFilter); filters.push_back(&lineNumberFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.3"))); } void test4() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); root->addAppender(socketAppender1); NDC::push(LOG4CXX_TEST_STR("some")); common("test4", LOG4CXX_STR("T4"), LOG4CXX_STR("key4"), LOG4CXX_STR("MDC-TEST4")); NDC::pop(); delay(1); ControlFilter cf; cf << PAT4; ThreadFilter threadFilter; std::vector<Filter *> filters; filters.push_back(&cf); filters.push_back(&threadFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.4"))); } void test5() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); AsyncAppenderPtr asyncAppender = new AsyncAppender(); root->addAppender(socketAppender1); root->addAppender(asyncAppender); NDC::push(LOG4CXX_TEST_STR("some5")); common("test5", LOG4CXX_STR("T5"), LOG4CXX_STR("key5"), LOG4CXX_STR("MDC-TEST5")); NDC::pop(); delay(2); ControlFilter cf; cf << PAT5; ThreadFilter threadFilter; std::vector<Filter *> filters; filters.push_back(&cf); filters.push_back(&threadFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.5"))); } void test6() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); AsyncAppenderPtr asyncAppender = new AsyncAppender(); root->addAppender(socketAppender1); root->addAppender(asyncAppender); NDC::push(LOG4CXX_TEST_STR("some6")); MDC::put(LOG4CXX_TEST_STR("hostID"), LOG4CXX_TEST_STR("client-test6")); common("test6", LOG4CXX_STR("T6"), LOG4CXX_STR("key6"), LOG4CXX_STR("MDC-TEST6")); NDC::pop(); MDC::remove(LOG4CXX_TEST_STR("hostID")); delay(2); ControlFilter cf; cf << PAT6; ThreadFilter threadFilter; std::vector<Filter *> filters; filters.push_back(&cf); filters.push_back(&threadFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.6"))); } void test7() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); AsyncAppenderPtr asyncAppender = new AsyncAppender(); root->addAppender(socketAppender1); root->addAppender(asyncAppender); NDC::push(LOG4CXX_TEST_STR("some7")); MDC::put(LOG4CXX_TEST_STR("hostID"), LOG4CXX_TEST_STR("client-test7")); common("test7", LOG4CXX_STR("T7"), LOG4CXX_STR("key7"), LOG4CXX_STR("MDC-TEST7")); NDC::pop(); MDC::remove(LOG4CXX_TEST_STR("hostID")); delay(2); ControlFilter cf; cf << PAT7; ThreadFilter threadFilter; std::vector<Filter *> filters; filters.push_back(&cf); filters.push_back(&threadFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.7"))); } void test8() { SocketAppenderPtr socketAppender1 = new SocketAppender(LOG4CXX_STR("localhost"), PORT); root->addAppender(socketAppender1); NDC::push(LOG4CXX_TEST_STR("some8")); common("test8", LOG4CXX_STR("T8"), LOG4CXX_STR("key8"), LOG4CXX_STR("MDC-TEST8")); NDC::pop(); delay(2); ControlFilter cf; cf << PAT8; ThreadFilter threadFilter; std::vector<Filter *> filters; filters.push_back(&cf); filters.push_back(&threadFilter); try { Transformer::transform(TEMP, FILTERED, filters); } catch(UnexpectedFormatException& e) { std::cout << "UnexpectedFormatException :" << e.what() << std::endl; throw; } LOGUNIT_ASSERT(Compare::compare(FILTERED, LOG4CXX_FILE("witness/socketServer.8"))); } void common(const std::string& testName, const LogString& dc, const LogString& key, const LogString& val) { int i = -1; NDC::push(dc); MDC::put(key, val); logger->setLevel(Level::getDebug()); root->setLevel(Level::getDebug()); LOG4CXX_TRACE(logger, "Message " << i); i++; logger->setLevel(Level::getTrace()); root->setLevel(Level::getTrace()); LOG4CXX_TRACE(logger, "Message " << ++i); LOG4CXX_TRACE(root, "Message " << ++i); LOG4CXX_DEBUG(logger, "Message " << ++i); LOG4CXX_DEBUG(root, "Message " << ++i); LOG4CXX_INFO(logger, "Message " << ++i); LOG4CXX_WARN(logger, "Message " << ++i); LOG4CXX_FATAL(logger, "Message " << ++i); //5 std::string exceptionMsg("\njava.lang.Exception: Just testing\n" "\tat org.apache.log4j.net.SocketServerTestCase.common(SocketServerTestCase.java:XXX)\n" "\tat org.apache.log4j.net.SocketServerTestCase."); exceptionMsg.append(testName); exceptionMsg.append("(SocketServerTestCase.java:XXX)\n" "\tat junit.framework.TestCase.runTest(TestCase.java:XXX)\n" "\tat junit.framework.TestCase.runBare(TestCase.java:XXX)\n" "\tat junit.framework.TestResult$1.protect(TestResult.java:XXX)\n" "\tat junit.framework.TestResult.runProtected(TestResult.java:XXX)\n" "\tat junit.framework.TestResult.run(TestResult.java:XXX)\n" "\tat junit.framework.TestCase.run(TestCase.java:XXX)\n" "\tat junit.framework.TestSuite.runTest(TestSuite.java:XXX)\n" "\tat junit.framework.TestSuite.run(TestSuite.java:XXX)"); LOG4CXX_DEBUG(logger, "Message " << ++i << exceptionMsg); LOG4CXX_ERROR(root, "Message " << ++i << exceptionMsg); NDC::pop(); MDC::remove(key); } void delay(int secs) { apr_sleep(APR_USEC_PER_SEC * secs); } private: static const File TEMP; static const File FILTERED; }; const File SocketServerTestCase::TEMP("output/temp"); const File SocketServerTestCase::FILTERED("output/filtered"); LOGUNIT_TEST_SUITE_REGISTRATION_DISABLED(SocketServerTestCase)
36.759336
113
0.533074
[ "vector", "transform" ]
ce46f0822c1f1f4a80b0418ca257d36bd6812f6e
9,153
cxx
C++
test/itkOpenSlideTestMetaData.cxx
mseng10/ITKIOOpenSlide
c0c2cf39f764c496ddb12108c4103740664975b0
[ "Apache-2.0" ]
5
2016-04-08T03:02:21.000Z
2022-03-04T22:53:07.000Z
test/itkOpenSlideTestMetaData.cxx
mseng10/ITKIOOpenSlide
c0c2cf39f764c496ddb12108c4103740664975b0
[ "Apache-2.0" ]
18
2016-03-27T01:17:36.000Z
2021-01-09T02:50:32.000Z
test/itkOpenSlideTestMetaData.cxx
mseng10/ITKIOOpenSlide
c0c2cf39f764c496ddb12108c4103740664975b0
[ "Apache-2.0" ]
6
2016-03-26T23:28:20.000Z
2019-08-21T17:02:01.000Z
/*========================================================================= * * Copyright NumFOCUS * * 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.txt * * 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 <cstring> #include <algorithm> #include <iostream> #include <fstream> #include <vector> #include "itkOpenSlideImageIO.h" #include "itkOpenSlideImageIOFactory.h" #include "itkImage.h" #include "itkMetaDataObject.h" #define SPECIFIC_IMAGEIO_MODULE_TEST namespace { class ReplaceStream { public: ReplaceStream(std::ios &stream, const std::ios &newStream) : m_Stream(stream), m_OriginalBuf(stream.rdbuf(newStream.rdbuf())) { } ~ReplaceStream() { m_Stream.rdbuf(m_OriginalBuf); } private: std::ios &m_Stream; std::streambuf * const m_OriginalBuf; }; bool ReadFileStripCR(const char *p_cFileName, std::vector<char> &vBuffer) { vBuffer.clear(); std::ifstream fileStream(p_cFileName); if (!fileStream) return false; fileStream.seekg(0, std::ifstream::end); const size_t length = fileStream.tellg(); fileStream.seekg(0, std::ifstream::beg); vBuffer.resize(length); if (!fileStream.read(&vBuffer[0], vBuffer.size())) return false; size_t j = 0; for (size_t i = 0; i < vBuffer.size(); ++i) { if (vBuffer[i] != '\r') { vBuffer[j] = vBuffer[i]; ++j; } } vBuffer.resize(j); return true; } } // End anonymous namespace int itkOpenSlideTestMetaData( int argc, char * argv[] ) { using ImageIOType = itk::OpenSlideImageIO; using PixelType = itk::RGBAPixel<unsigned char>; using ImageType = itk::Image<PixelType, 2>; using SizeType = ImageType::SizeType; using SpacingType = ImageType::SpacingType; if (argc < 2 || argc > 4) { std::cerr << "Usage: " << argv[0] << " slideFile [outputLog] [comparisonLog]" << std::endl; return EXIT_FAILURE; } const char * const p_cSlideFile = argv[1]; const char * const p_cOutputLog = argc > 2 ? argv[2] : "stdout"; const char * const p_cCompareLog = argc > 3 ? argv[3] : NULL; std::ofstream logFileStream; std::ostream *p_outStream = &std::cout; if (strcmp(p_cOutputLog, "stdout") != 0) { logFileStream.open(p_cOutputLog, std::ofstream::out | std::ofstream::trunc); if (!logFileStream) { std::cerr << "Error: Could not open output log '" << p_cOutputLog << "'." << std::endl; return EXIT_FAILURE; } p_outStream = &logFileStream; } // RAII trick ReplaceStream clStreamGuard(std::cout, *p_outStream); ImageIOType::Pointer p_clImageIO = ImageIOType::New(); p_clImageIO->SetFileName(p_cSlideFile); try { p_clImageIO->ReadImageInformation(); } catch (itk::ExceptionObject &e) { std::cerr << "Error: " << e << std::endl; return EXIT_FAILURE; } const std::string strComponentType = itk::ImageIOBase::GetComponentTypeAsString(p_clImageIO->GetComponentType()); const std::string strPixelType = itk::ImageIOBase::GetPixelTypeAsString(p_clImageIO->GetPixelType()); std::cout << "\nImage Information:\n" << std::endl; std::cout << "Dimensions: " << p_clImageIO->GetNumberOfDimensions() << std::endl; std::cout << "Component type: " << strComponentType << std::endl; std::cout << "Pixel type: " << strPixelType << std::endl; std::cout << "Vendor: " << p_clImageIO->GetVendor() << std::endl; // Some sanity checks // Check dimensions if (p_clImageIO->GetNumberOfDimensions() != ImageType::GetImageDimension()) { std::cerr << "Error: ImageIO should report dimension " << ImageType::GetImageDimension() << " but reports " << p_clImageIO->GetNumberOfDimensions() << '.' << std::endl; return EXIT_FAILURE; } // Check pixel type { // Let's use an ImageIOType to form the expected pixel information ImageIOType::Pointer p_clTmpIO = ImageIOType::New(); PixelType clTmpPixel; p_clTmpIO->SetPixelTypeInfo(&clTmpPixel); const std::string strExpectedComponentType = itk::ImageIOBase::GetComponentTypeAsString(p_clTmpIO->GetComponentType()); const std::string strExpectedPixelType = itk::ImageIOBase::GetPixelTypeAsString(p_clTmpIO->GetPixelType()); if (strExpectedComponentType != strComponentType) { std::cerr << "Error: ImageIO should report a component type of " << strExpectedComponentType << " but reports " << strComponentType << '.' << std::endl; return EXIT_FAILURE; } if (strExpectedPixelType != strPixelType) { std::cerr << "Error: ImageIO should report a pixel type of " << strExpectedPixelType << " but reports " << strPixelType << '.' << std::endl; return EXIT_FAILURE; } } // Sanity checks passed std::cout << "\nMeta Data:\n" << std::endl; itk::MetaDataDictionary &clTags = p_clImageIO->GetMetaDataDictionary(); std::vector<std::string> vKeys = clTags.GetKeys(); std::cout << "Number of keys: " << vKeys.size() << std::endl; std::cout << "Entries:" << std::endl; for (size_t i = 0; i < vKeys.size(); ++i) { const std::string &strKey = vKeys[i]; std::string strValue; if (itk::ExposeMetaData(clTags, strKey, strValue)) std::cout << strKey << " = " << strValue << std::endl; } std::cout << "\nLevel Information:\n" << std::endl; const int iLevelCount = p_clImageIO->GetLevelCount(); std::cout << "Level count: " << iLevelCount << std::endl; std::cout << "Levels:" << std::endl; for (int iLevel = 0; iLevel < iLevelCount; ++iLevel) { p_clImageIO->SetLevel(iLevel); try { p_clImageIO->ReadImageInformation(); } catch (itk::ExceptionObject &e) { std::cerr << "Error: " << e << std::endl; return EXIT_FAILURE; } SizeType clSize; clSize[0] = p_clImageIO->GetDimensions(0); clSize[1] = p_clImageIO->GetDimensions(1); SpacingType clSpacing; clSpacing[0] = p_clImageIO->GetSpacing(0); clSpacing[1] = p_clImageIO->GetSpacing(1); const size_t sizeInBytes = p_clImageIO->GetImageSizeInBytes(); const int iCurrentLevel = p_clImageIO->GetLevel(); std::cout << "Level " << iCurrentLevel << ": dimensions = " << clSize << ", spacing = " << clSpacing << ", size in bytes = " << sizeInBytes << std::endl; } std::cout << "\nAssociated image information:\n" << std::endl; ImageIOType::AssociatedImageNameContainer vAssociatedImages = p_clImageIO->GetAssociatedImageNames(); std::cout << "Number of associated images: " << vAssociatedImages.size() << std::endl; std::cout << "Associated image names:" << std::endl; const size_t numWordsPerLine = 3; for (size_t i = 0; i < vAssociatedImages.size(); i += numWordsPerLine) { const size_t jBegin = i; const size_t jEnd = std::min(vAssociatedImages.size(), jBegin + numWordsPerLine); std::cout << '\'' << vAssociatedImages[jBegin] << '\''; for (size_t j = jBegin+1; j < jEnd; ++j) std::cout << ", '" << vAssociatedImages[j] << '\''; if (i + numWordsPerLine < vAssociatedImages.size()) std::cout << ','; std::cout << std::endl; } std::cout << "\nAssociated images:" << std::endl; for (size_t i = 0; i < vAssociatedImages.size(); ++i) { const std::string &strAssociatedImage = vAssociatedImages[i]; p_clImageIO->SetAssociatedImageName(strAssociatedImage); try { p_clImageIO->ReadImageInformation(); } catch (itk::ExceptionObject &e) { std::cerr << "Error: " << e << std::endl; return EXIT_FAILURE; } SizeType clSize; clSize[0] = p_clImageIO->GetDimensions(0); clSize[1] = p_clImageIO->GetDimensions(1); SpacingType clSpacing; clSpacing[0] = p_clImageIO->GetSpacing(0); clSpacing[1] = p_clImageIO->GetSpacing(1); const size_t sizeInBytes = p_clImageIO->GetImageSizeInBytes(); const std::string strCurrentAssociatedImage = p_clImageIO->GetAssociatedImageName(); std::cout << strCurrentAssociatedImage << ": dimensions = " << clSize << ", spacing = " << clSpacing << ", size in bytes = " << sizeInBytes << std::endl; } if (p_cCompareLog != NULL) { logFileStream.close(); std::vector<char> vBuffer1, vBuffer2; if (!ReadFileStripCR(p_cOutputLog, vBuffer1)) { std::cerr << "Error: Could not read output log file '" << p_cOutputLog << "'." << std::endl; return EXIT_FAILURE; } if (!ReadFileStripCR(p_cCompareLog, vBuffer2)) { std::cerr << "Error: Could not read comparison log file '" << p_cCompareLog << "'." << std::endl; return EXIT_FAILURE; } if (vBuffer1.size() != vBuffer2.size() || std::memcmp(&vBuffer1[0], &vBuffer2[0], vBuffer1.size()) != 0) return EXIT_FAILURE; } return EXIT_SUCCESS; }
32.342756
172
0.646127
[ "vector" ]
ce4d71bc7fc7ca396a6988f3450cad551dd4728f
8,742
cpp
C++
be/src/exec/odbc_scan_node.cpp
chaegumi/incubator-doris
ca9e5c4785e932f9253722e6990c9d2128c0f48a
[ "Apache-2.0" ]
3
2021-08-18T01:37:38.000Z
2022-02-14T15:33:36.000Z
be/src/exec/odbc_scan_node.cpp
EmmyMiao87/incubator-doris
af06adb57fbaf306534971bae8cf11162d714404
[ "Apache-2.0" ]
null
null
null
be/src/exec/odbc_scan_node.cpp
EmmyMiao87/incubator-doris
af06adb57fbaf306534971bae8cf11162d714404
[ "Apache-2.0" ]
null
null
null
// 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 "odbc_scan_node.h" #include <sstream> #include "exec/text_converter.hpp" #include "gen_cpp/PlanNodes_types.h" #include "runtime/row_batch.h" #include "runtime/runtime_state.h" #include "runtime/string_value.h" #include "runtime/tuple_row.h" #include "util/runtime_profile.h" namespace doris { OdbcScanNode::OdbcScanNode(ObjectPool* pool, const TPlanNode& tnode, const DescriptorTbl& descs) : ScanNode(pool, tnode, descs), _is_init(false), _table_name(tnode.odbc_scan_node.table_name), _connect_string(std::move(tnode.odbc_scan_node.connect_string)), _query_string(std::move(tnode.odbc_scan_node.query_string)), _tuple_id(tnode.odbc_scan_node.tuple_id), _tuple_desc(nullptr) {} OdbcScanNode::~OdbcScanNode() {} Status OdbcScanNode::prepare(RuntimeState* state) { VLOG(1) << "OdbcScanNode::Prepare"; if (_is_init) { return Status::OK(); } if (NULL == state) { return Status::InternalError("input pointer is NULL."); } RETURN_IF_ERROR(ScanNode::prepare(state)); // get tuple desc _tuple_desc = state->desc_tbl().get_tuple_descriptor(_tuple_id); if (NULL == _tuple_desc) { return Status::InternalError("Failed to get tuple descriptor."); } _slot_num = _tuple_desc->slots().size(); _odbc_param.connect_string = std::move(_connect_string); _odbc_param.query_string = std::move(_query_string); _odbc_param.tuple_desc = _tuple_desc; _odbc_scanner.reset(new (std::nothrow) ODBCScanner(_odbc_param)); if (_odbc_scanner.get() == nullptr) { return Status::InternalError("new a odbc scanner failed."); } _tuple_pool.reset(new (std::nothrow) MemPool(mem_tracker().get())); if (_tuple_pool.get() == NULL) { return Status::InternalError("new a mem pool failed."); } _text_converter.reset(new (std::nothrow) TextConverter('\\')); if (_text_converter.get() == NULL) { return Status::InternalError("new a text convertor failed."); } _is_init = true; return Status::OK(); } Status OdbcScanNode::open(RuntimeState* state) { RETURN_IF_ERROR(ExecNode::open(state)); VLOG(1) << "OdbcScanNode::Open"; if (NULL == state) { return Status::InternalError("input pointer is NULL."); } if (!_is_init) { return Status::InternalError("used before initialize."); } RETURN_IF_ERROR(exec_debug_action(TExecNodePhase::OPEN)); RETURN_IF_CANCELLED(state); SCOPED_TIMER(_runtime_profile->total_time_counter()); RETURN_IF_ERROR(_odbc_scanner->open()); RETURN_IF_ERROR(_odbc_scanner->query()); // check materialize slot num return Status::OK(); } Status OdbcScanNode::write_text_slot(char* value, int value_length, SlotDescriptor* slot, RuntimeState* state) { if (!_text_converter->write_slot(slot, _tuple, value, value_length, true, false, _tuple_pool.get())) { std::stringstream ss; ss << "fail to convert odbc value '" << value << "' TO " << slot->type(); return Status::InternalError(ss.str()); } return Status::OK(); } Status OdbcScanNode::get_next(RuntimeState* state, RowBatch* row_batch, bool* eos) { VLOG(1) << "OdbcScanNode::GetNext"; if (NULL == state || NULL == row_batch || NULL == eos) { return Status::InternalError("input is NULL pointer"); } if (!_is_init) { return Status::InternalError("used before initialize."); } RETURN_IF_ERROR(exec_debug_action(TExecNodePhase::GETNEXT)); RETURN_IF_CANCELLED(state); SCOPED_TIMER(_runtime_profile->total_time_counter()); if (reached_limit()) { *eos = true; return Status::OK(); } // create new tuple buffer for row_batch int tuple_buffer_size = row_batch->capacity() * _tuple_desc->byte_size(); void* tuple_buffer = _tuple_pool->allocate(tuple_buffer_size); if (NULL == tuple_buffer) { return Status::InternalError("Allocate memory failed."); } _tuple = reinterpret_cast<Tuple*>(tuple_buffer); // Indicates whether there are more rows to process. Set in _odbc_scanner.next(). bool odbc_eos = false; while (true) { RETURN_IF_CANCELLED(state); if (reached_limit() || row_batch->is_full()) { // hang on to last allocated chunk in pool, we'll keep writing into it in the // next get_next() call row_batch->tuple_data_pool()->acquire_data(_tuple_pool.get(), !reached_limit()); *eos = reached_limit(); return Status::OK(); } RETURN_IF_ERROR(_odbc_scanner->get_next_row(&odbc_eos)); if (odbc_eos) { row_batch->tuple_data_pool()->acquire_data(_tuple_pool.get(), false); *eos = true; return Status::OK(); } int row_idx = row_batch->add_row(); TupleRow* row = row_batch->get_row(row_idx); // scan node is the first tuple of tuple row row->set_tuple(0, _tuple); memset(_tuple, 0, _tuple_desc->num_null_bytes()); int j = 0; for (int i = 0; i < _slot_num; ++i) { auto slot_desc = _tuple_desc->slots()[i]; // because the fe planner filter the non_materialize column if (!slot_desc->is_materialized()) { continue; } const auto& column_data = _odbc_scanner->get_column_data(j); if (column_data.strlen_or_ind == SQL_NULL_DATA) { if (slot_desc->is_nullable()) { _tuple->set_null(slot_desc->null_indicator_offset()); } else { std::stringstream ss; ss << "nonnull column contains NULL. table=" << _table_name << ", column=" << slot_desc->col_name(); return Status::InternalError(ss.str()); } } else if (column_data.strlen_or_ind > column_data.buffer_length) { std::stringstream ss; ss << "nonnull column contains NULL. table=" << _table_name << ", column=" << slot_desc->col_name(); return Status::InternalError(ss.str()); } else { RETURN_IF_ERROR(write_text_slot(static_cast<char*>(column_data.target_value_ptr), column_data.strlen_or_ind, slot_desc, state)); } j++; } ExprContext* const* ctxs = &_conjunct_ctxs[0]; int num_ctxs = _conjunct_ctxs.size(); // ODBC scanner can not filter conjunct with function, need check conjunct again. if (ExecNode::eval_conjuncts(ctxs, num_ctxs, row)) { row_batch->commit_last_row(); ++_num_rows_returned; COUNTER_SET(_rows_returned_counter, _num_rows_returned); char* new_tuple = reinterpret_cast<char*>(_tuple); new_tuple += _tuple_desc->byte_size(); _tuple = reinterpret_cast<Tuple*>(new_tuple); } } } Status OdbcScanNode::close(RuntimeState* state) { if (is_closed()) { return Status::OK(); } RETURN_IF_ERROR(exec_debug_action(TExecNodePhase::CLOSE)); SCOPED_TIMER(_runtime_profile->total_time_counter()); _tuple_pool.reset(); return ExecNode::close(state); } void OdbcScanNode::debug_string(int indentation_level, std::stringstream* out) const { *out << string(indentation_level * 2, ' '); *out << "OdbcScanNode(tupleid=" << _tuple_id << " table=" << _table_name; *out << ")" << std::endl; for (int i = 0; i < _children.size(); ++i) { _children[i]->debug_string(indentation_level + 1, out); } } Status OdbcScanNode::set_scan_ranges(const std::vector<TScanRangeParams>& scan_ranges) { return Status::OK(); } } // namespace doris
34.417323
97
0.630977
[ "vector" ]
ce521d2e89548f1dc21784b3a21698c0e7f8e633
8,469
cpp
C++
common/tcp_utils.cpp
zteo-phd-software/ironstack
649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0
[ "BSD-3-Clause" ]
null
null
null
common/tcp_utils.cpp
zteo-phd-software/ironstack
649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0
[ "BSD-3-Clause" ]
null
null
null
common/tcp_utils.cpp
zteo-phd-software/ironstack
649f82ddcbb82831796fa2a1e1d1b8cc0f94a8e0
[ "BSD-3-Clause" ]
null
null
null
#include "tcp_utils.h" // constructor to initialize inspector object __transfer_data::__transfer_data() { filename = ""; file_hash = 0; error = true; completed = false; bytes_transferred = 0; bytes_total = 0; percentage_complete = 0; transfer_rate = 0; transfer_time = 0; estimated_time_remaining = 0; } // constructor to initialize synchronization stuff transfer_progress::transfer_progress() { completed = false; pthread_mutex_init(&lock, NULL); pthread_cond_init(&cond, NULL); } // destructor removes synchronization stuff transfer_progress::~transfer_progress() { pthread_mutex_destroy(&lock); pthread_cond_destroy(&cond); } // used to get async updates about the file transfer __transfer_data transfer_progress::get_data_async() { __transfer_data result; if (completed) return status; pthread_mutex_lock(&lock); result = status; pthread_mutex_unlock(&lock); return result; } // blocks until the next update is available __transfer_data transfer_progress::get_data_blocked() { __transfer_data result; pthread_mutex_lock(&lock); if (completed) result = status; else { pthread_cond_wait(&cond, &lock); result = status; } pthread_mutex_unlock(&lock); return result; } // performs a file transfer, blocking until either the file completes or an error occurs int tcp_utils::transfer_file_blocked(tcp* connection, const std::string& filename) { long file_size = filesystem::get_file_size(filename); uint32_t file_hash = hash::get_generic_hash_from_file(filename); long bytes_processed = 0; long resume_offset = 0; int chunk_size; char buf[2048]; std::string response; if (file_size < 0 || file_hash == 0) return -2; FILE* fp = fopen(filename.c_str(), "r"); if (fp == NULL) return -2; // tell the remote file name, hash and filesize sprintf(buf, "%ld", file_size); if (connection->write_string(filename.c_str()) < 0 || connection->write_uint32(file_hash) < 0 || connection->write_string(buf) < 0) goto fail; // wait for remote to respond if (connection->read_string(response) < 0) goto fail; // check if starting from the beginning or resuming if (response.compare("OK") == 0) {} else if (response.compare("CONTINUE") == 0) { // read in resume value if (connection->read_string(response) < 0 || sscanf(response.c_str(), "%ld", &resume_offset) != 1) goto fail; // scroll to the point in the file if (fseek(fp, resume_offset, SEEK_SET) < 0) goto fail; bytes_processed = resume_offset; } else goto fail; // read in file blocks, 2k at a time if possible while (bytes_processed < file_size) { chunk_size = (int) (file_size - bytes_processed >= (int) sizeof(buf) ? sizeof(buf) : file_size - bytes_processed); if (feof(fp) || fread(buf, 1, chunk_size, fp) < (size_t) chunk_size) { // file contents changed! wtf. goto fail; } // transmit to remote if (connection->write_data_item(buf, sizeof(buf)) < 0) goto fail; } // everything sent return 0; fail: connection->write_string("ERROR"); fclose(fp); return -1; } // performs an async file transfer in the background, updating as the file transfer proceeds transfer_progress* tcp_utils::transfer_file_async(tcp* connection, const std::string& filename) { pthread_t tid; // setup transfer object transfer_progress* progress = new transfer_progress(); progress->status.filename = filename; progress->status.file_hash = hash::get_generic_hash_from_file(filename); progress->status.error = false; progress->status.completed = false; progress->status.bytes_transferred = 0; progress->status.bytes_total = filesystem::get_file_size(filename); progress->status.percentage_complete = 0; progress->status.transfer_rate = 0; progress->status.transfer_time = 0; progress->status.estimated_time_remaining = -1; // create thread parameters typedef struct { transfer_progress* progress; tcp* connection; } params_t; params_t* params = (params_t*) malloc(sizeof(params)); params->progress = progress; params->connection = connection; // sanity check if (progress->status.bytes_total < 0 || progress->status.file_hash == 0 || pthread_create(&tid, NULL, transfer_file_async_entrypoint, params) != 0) { free(params); delete progress; return NULL; } return progress; } // thread entrypoint to transfer the file void* tcp_utils::transfer_file_async_entrypoint(void* args) { typedef struct { transfer_progress* progress; tcp* connection; } params_t; // copy out parameters and free the struct transfer_progress* progress = ((params_t*)args)->progress; tcp* connection = ((params_t*)args)->connection; free(args); // detach thread pthread_detach(pthread_self()); // now transfer the file long file_size = filesystem::get_file_size(progress->status.filename); uint32_t file_hash = hash::get_generic_hash_from_file(progress->status.filename); long bytes_processed = 0; long resume_offset = 0; int chunk_size; char buf[2048]; std::string response; struct timeval current_time; float chunk_elapsed_time; int chunk_round; FILE* fp = fopen(progress->status.filename.c_str(), "r"); // sanity checks if (file_size < 0 || file_hash == 0 || fp == NULL) goto fail; // tell the remote file name, hash and filesize sprintf(buf, "%ld", file_size); if (connection->write_string(progress->status.filename.c_str()) < 0 || connection->write_uint32(file_hash) < 0 || connection->write_string(buf) < 0) goto fail; // wait for remote to respond if (connection->read_string(response) < 0) goto fail; // check if starting from the beginning or resuming if (response.compare("OK") == 0) {} else if (response.compare("CONTINUE") == 0) { // read in resume value if (connection->read_string(response) < 0 || sscanf(response.c_str(), "%ld", &resume_offset) != 1) goto fail; // scroll to the point in the file if (fseek(fp, resume_offset, SEEK_SET) < 0) goto fail; bytes_processed = resume_offset; } else goto fail; // update progress gettimeofday(&current_time, NULL); chunk_elapsed_time = 0.0; chunk_round = 0; pthread_mutex_lock(&progress->lock); progress->status.bytes_transferred = bytes_processed; progress->status.percentage_complete = (float) bytes_processed / (float) file_size * 100.0f; gettimeofday(&progress->start_time, NULL); pthread_mutex_unlock(&progress->lock); // read in file blocks, 2k at a time if possible while (bytes_processed < file_size) { chunk_size = (int) (file_size - bytes_processed >= (int) sizeof(buf) ? sizeof(buf) : file_size - bytes_processed); if (feof(fp) || fread(buf, 1, chunk_size, fp) < (size_t) chunk_size) { // file contents changed! wtf. goto fail; } // transmit to remote if (connection->write_data_item(buf, sizeof(buf)) < 0) goto fail; // update progress pthread_mutex_lock(&progress->lock); progress->status.bytes_transferred += chunk_size; progress->status.percentage_complete = (float) bytes_processed / (float) file_size * 100.0f; progress->status.transfer_time = cu_get_time_elapsed_to_now(progress->start_time); chunk_round++; if (chunk_round == 5) { chunk_round = 0; chunk_elapsed_time = cu_get_time_elapsed_to_now(current_time); if (chunk_elapsed_time > 0.0) progress->status.transfer_rate = (4*sizeof(buf) + chunk_size) / (1024.0 * cu_get_time_elapsed_to_now(current_time)); else progress->status.transfer_rate = -1; // transfer rate too high gettimeofday(&current_time, NULL); } if (progress->status.transfer_rate > 0.0) progress->status.estimated_time_remaining = (file_size - progress->status.bytes_transferred) / progress->status.transfer_rate; else progress->status.estimated_time_remaining = -1; pthread_cond_broadcast(&progress->cond); pthread_mutex_unlock(&progress->lock); } // everything sent, update the transfer information one last time pthread_mutex_lock(&progress->lock); progress->status.completed = true; progress->status.estimated_time_remaining = 0; progress->status.transfer_time = cu_get_time_elapsed_to_now(progress->start_time); progress->status.percentage_complete = 100.0; pthread_cond_broadcast(&progress->cond); pthread_mutex_unlock(&progress->lock); progress->completed = true; return NULL; fail: connection->write_string("ERROR"); fclose(fp); progress->status.error = true; pthread_mutex_lock(&progress->lock); pthread_cond_broadcast(&progress->cond); pthread_mutex_unlock(&progress->lock); return NULL; }
26.632075
129
0.725706
[ "object" ]
ce61a3c8e94a4fd40ab5ae0e26030fea9dc30ac8
34,161
cpp
C++
nntrainer/tensor/tensor.cpp
gichan-jang/nntrainer
273ca7d6ecb3077d93539b81a9d9340e0c1dc812
[ "Apache-2.0" ]
null
null
null
nntrainer/tensor/tensor.cpp
gichan-jang/nntrainer
273ca7d6ecb3077d93539b81a9d9340e0c1dc812
[ "Apache-2.0" ]
2
2021-04-19T11:42:07.000Z
2021-04-21T10:26:04.000Z
nntrainer/tensor/tensor.cpp
gichan-jang/nntrainer
273ca7d6ecb3077d93539b81a9d9340e0c1dc812
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2019 Samsung Electronics Co., Ltd. All Rights Reserved. * * 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. * * * @file tensor.cpp * @date 04 December 2019 * @brief This is Tensor class for calculation * @see https://github.com/nnstreamer/nntrainer * @author Jijoong Moon <jijoong.moon@samsung.com> * @bug No known bugs except for NYI items * */ #include <assert.h> #include <cmath> #include <cstring> #include <fstream> #include <iomanip> #include <iterator> #include <random> #include <regex> #include <sstream> #include <stdio.h> #include <blas_interface.h> #include <lazy_tensor.h> #include <nntrainer_error.h> #include <nntrainer_log.h> #include <parse_util.h> #include <tensor.h> #include <util_func.h> #define transposeloop(cl, ci, cj, ck, sl, si, sj, sk) \ do { \ unsigned int i, j, k, l; \ int inidx = 0, outidx = 0; \ for (cl = 0; cl < sl; cl++) \ for (ci = 0; ci < si; ci++) \ for (cj = 0; cj < sj; cj++) \ for (ck = 0; ck < sk; ck++) { \ outidx = si * sj * sk * cl + sj * sk * ci + sk * cj + ck; \ inidx = l * SI * SJ * SK + i * SJ * SK + j * SK + k; \ outptr[outidx] = inptr[inidx]; \ } \ } while (0); #define CREATE_IF_EMPTY_DIMS(tensor, ...) \ do { \ if (tensor.uninitialized()) \ tensor = Tensor(__VA_ARGS__); \ } while (0); namespace nntrainer { /** * @struct External Loop Info for broadcasted info * @brief External Loop Info for broadcasted iteration. Please refer to * DISABLED_private_external_loop_n in unittest_nntrainer_tensor. * @note This should better be implemented in iterator fashion before used * extensively. */ struct Tensor::BroadcastInfo { /** * @brief Construct a new External Loop Info object * */ BroadcastInfo() : buffer_size(0), buffer_axis(-1), strides{0, 0, 0, 0} {} unsigned int buffer_size; /**< virtual size of the buffer */ int buffer_axis; /**< the smallest axis that should be looped. -1 means no loop needed*/ std::array<unsigned int, MAXDIM> strides; /**< modified strides for the loop */ }; static auto rng = [] { std::mt19937 rng; rng.seed(getSeed()); return rng; }(); Tensor::Tensor(const TensorDim &d, const float *buf) : Tensor() { if (d.getDataLen() != 0) { dim = d; strides = d.computeStrides(); allocate(); if (buf != nullptr) copy(buf); } } Tensor::Tensor(const TensorDim &d, bool alloc_now) : Tensor() { if (d.getDataLen() != 0) { dim = d; strides = d.computeStrides(); if (alloc_now) allocate(); } } /** * @class SrcSharedTensor * @brief Source of the shared tensor */ class SrcSharedTensor { public: /** * @brief Constructor for the class */ SrcSharedTensor() : src(nullptr), off(0) {} SrcSharedTensor(const Tensor *tensor, unsigned int offset) : src(tensor), off(offset) {} /** * @brief Get the allocated src tensor */ const Tensor *tensor() const { if (!src) throw std::runtime_error("Accessing empty src tensor"); return src; } /** * @brief Get the offset from the source tensor */ unsigned int offset() const { return off; } private: const Tensor *src; /**< Tensor of the source */ unsigned int off; /**< offset from the source data ptr */ }; void Tensor::allocate() { if (data) /// already allocated return; if (src_tensor) { /// allocate data based on the source tensor data = std::shared_ptr<float>(src_tensor->tensor()->data, src_tensor->tensor()->data.get() + src_tensor->offset()); } else { /// allocate new memory for the tensor data data = std::shared_ptr<float>(new float[dim.getDataLen()], std::default_delete<float[]>()); } } Tensor Tensor::Map(float *buf, unsigned int size, const TensorDim &d, int offset) { if (d.getDataLen() == 0 || buf == nullptr) { throw std::invalid_argument( "[Tensor::Map] empty tensor dim is not allowed"); } if (d.getDataLen() + offset > size) { throw std::invalid_argument( "Creating shared tensor of size bigger than tensor memory."); } Tensor tmp; tmp.dim = d; tmp.strides = d.computeStrides(); /// Tensor does not own the memory tmp.data = std::shared_ptr<float>(buf + offset, [](void *) {}); return tmp; } Tensor Tensor::Map(std::shared_ptr<float> buf, unsigned int size, const TensorDim &d, int offset) { if (d.getDataLen() == 0 || buf == nullptr) { throw std::invalid_argument( "[Tensor::Map] empty tensor dim is not allowed"); } if (d.getDataLen() + offset > size) { throw std::invalid_argument( "Creating shared tensor of size bigger than tensor memory."); } Tensor tmp; tmp.dim = d; tmp.data = std::shared_ptr<float>(buf, buf.get() + offset); return tmp; } bool Tensor::operator==(const Tensor &rhs) const { if (this->dim != rhs.dim) return false; size_t len = length(); if (len != rhs.length()) return false; const float *data = getData(); const float *rdata = rhs.getData(); for (size_t i = 0; i < len; ++i) { if (std::isnan(data[i]) || std::isnan(rdata[i]) || std::fabs(data[i] - rdata[i]) > epsilon) return false; } return true; } template <typename T> void Tensor::setDist(T dist) { float *data = getData(); unsigned int len = length(); for (unsigned int i = 0; i < len; ++i) { data[i] = dist(rng); } } void Tensor::setRandNormal(float mean, float std) { setDist<std::normal_distribution<float>>( std::normal_distribution<float>(mean, std)); } void Tensor::setRandUniform(float min, float max) { setDist<std::uniform_real_distribution<float>>( std::uniform_real_distribution<float>(min, max)); } Tensor::Tensor( std::vector<std::vector<std::vector<std::vector<float>>>> const &d) { if (d.empty() || d[0].empty() || d[0][0].empty() || d[0][0][0].empty()) { throw std::out_of_range( "[Tensor] trying to initialize Tensor from empty vector"); } dim.batch(d.size()); dim.channel(d[0].size()); dim.height(d[0][0].size()); dim.width(d[0][0][0].size()); strides = dim.computeStrides(); data = std::shared_ptr<float>(new float[dim.getDataLen()], std::default_delete<float[]>()); is_contiguous = true; for (unsigned int i = 0; i < dim.batch(); ++i) for (unsigned int j = 0; j < dim.channel(); ++j) for (unsigned int k = 0; k < dim.height(); ++k) for (unsigned int l = 0; l < dim.width(); ++l) this->setValue(i, j, k, l, d[i][j][k][l]); } int Tensor::multiply_i(float const &value) { /// @note this is not depending on multiply_i as there is an optimized /// version for multiply_i float *data = getData(); unsigned int len = length(); sscal(len, value, data, 1); return ML_ERROR_NONE; } Tensor Tensor::multiply(float const &value) const { Tensor t; return multiply(value, t); } Tensor &Tensor::multiply(float const &value, Tensor &out) const { /// @todo add unittest auto f = std::bind(std::multiplies<float>(), std::placeholders::_1, value); return apply(f, out); } int Tensor::multiply_i(Tensor const &m) { try { this->multiply(m, *this); } catch (std::exception &err) { ml_loge("%s %s", typeid(err).name(), err.what()); return ML_ERROR_INVALID_PARAMETER; } return ML_ERROR_NONE; } Tensor Tensor::multiply(Tensor const &m) const { Tensor t; return this->multiply(m, t); } Tensor &Tensor::multiply(Tensor const &m, Tensor &output) const { auto f = [&](const BroadcastInfo &e, const float *buf, const float *m_buf, float *out_buf) { for (unsigned int i = 0; i < e.buffer_size; ++i) { *out_buf = *buf * *m_buf; buf += strides[3]; m_buf += e.strides[3]; out_buf += strides[3]; } }; apply_broadcast(m, f, output); return output; } int Tensor::divide_i(float const &value) { if (value == 0.0f) { return ML_ERROR_INVALID_PARAMETER; } this->divide(value, *this); return ML_ERROR_NONE; } Tensor Tensor::divide(float const &value) const { Tensor t; return divide(value, t); } Tensor &Tensor::divide(float const &value, Tensor &out) const { auto f = std::bind(std::divides<float>(), std::placeholders::_1, value); /// @todo add unittest if (value == 0.0f) { std::stringstream ss; ss << "[Tensor] divide by value failed, value: " << value; throw std::invalid_argument(ss.str().c_str()); } return apply(f, out); } int Tensor::divide_i(Tensor const &m) { try { this->divide(m, *this); } catch (std::exception &err) { ml_loge("%s %s", typeid(err).name(), err.what()); return ML_ERROR_INVALID_PARAMETER; } return ML_ERROR_NONE; } Tensor Tensor::divide(Tensor const &m) const { Tensor t; return this->divide(m, t); } Tensor &Tensor::divide(Tensor const &m, Tensor &output) const { auto f = [&](const BroadcastInfo &e, const float *buf, const float *m_buf, float *out_buf) { for (unsigned int i = 0; i < e.buffer_size; ++i) { *out_buf = *buf / *m_buf; buf += strides[3]; m_buf += e.strides[3]; out_buf += strides[3]; } }; apply_broadcast(m, f, output); return output; } int Tensor::add_i(float const &value) { this->add(value, *this); return ML_ERROR_NONE; } Tensor Tensor::add(float const &value) const { Tensor t; return add(value, t); } Tensor &Tensor::add(float const &value, Tensor &out) const { /// @todo add unittest auto f = std::bind(std::plus<float>(), std::placeholders::_1, value); return apply(f, out); } int Tensor::add_i(Tensor const &m, float const alpha) { /// @TODO: add axis rather doing add over the last two dimensions always /// operator i has optimized version auto f = [&](const BroadcastInfo &e, const float *buf, const float *m_buf, float *out_buf) { saxpy(e.buffer_size, alpha, m_buf, e.strides[3], out_buf, strides[3]); }; try { apply_broadcast(m, f, *this); } catch (std::exception &err) { ml_loge("%s %s", typeid(err).name(), err.what()); return ML_ERROR_INVALID_PARAMETER; } return ML_ERROR_NONE; } Tensor Tensor::add(Tensor const &m, float const alpha) const { Tensor t; return this->add(m, t, alpha); } Tensor &Tensor::add(Tensor const &m, Tensor &out, float const alpha) const { auto f = [&](const BroadcastInfo &e, const float *buf, const float *m_buf, float *out_buf) { for (unsigned int i = 0; i < e.buffer_size; ++i) { *out_buf = *buf + *m_buf * alpha; buf += strides[3]; m_buf += e.strides[3]; out_buf += strides[3]; } }; apply_broadcast(m, f, out); return out; } int Tensor::subtract_i(float const &value) { this->subtract(value, *this); return ML_ERROR_NONE; } Tensor Tensor::subtract(float const &value) const { Tensor t; return subtract(value, t); } Tensor &Tensor::subtract(float const &value, Tensor &out) const { /// @todo add unittest auto f = std::bind(std::minus<float>(), std::placeholders::_1, value); return apply(f, out); } int Tensor::subtract_i(Tensor const &m) { return add_i(m, -1); } Tensor Tensor::subtract(Tensor const &m) const { return add(m, -1); } Tensor &Tensor::subtract(Tensor const &m, Tensor &out) const { return add(m, out, -1); } int Tensor::pow_i(float exponent) { pow(exponent, *this); return ML_ERROR_NONE; } Tensor Tensor::pow(float exponent) const { Tensor t; return pow(exponent, t); } Tensor &Tensor::pow(float exponent, Tensor &out) const { auto f = [exponent](float in) { return powf(in, exponent); }; return apply(f, out); } Tensor Tensor::getBatchSlice(unsigned int offset, unsigned int size) const { TensorDim dim_ = dim; dim_.batch(size); return getSharedDataTensor(dim_, offset * this->dim.getFeatureLen()); } void Tensor::createSharedDataTensor(const Tensor &src, Tensor &dest, unsigned int offset) { /** * - If src already has data allocaed, then directly make dest tensor based on * the src tensor. * - If src.data does not exist (meaning tensor does not memory allocated), * and src.src_tensor does not exist (meaning the src tensor does not depened * on another tensor), then create a SrcSharedTensor around the src. * - If src.src_tensor exists, then use the src.src_tensor to create the * required SrcSharedTensor to avoid recursive dependency. * * @note src.data and src.src_tensor CAN co-exist. src.src_tensor is stored * if the batch size of src is updated and needs reallocation. */ if (src.data) dest.data = std::shared_ptr<float>(src.data, src.data.get() + offset); else if (!src.src_tensor) dest.src_tensor = std::make_shared<SrcSharedTensor>(&src, offset); else dest.src_tensor = std::make_shared<SrcSharedTensor>( src.src_tensor->tensor(), offset + src.src_tensor->offset()); } Tensor Tensor::getSharedDataTensor(const TensorDim dim_, unsigned int offset) const { Tensor ret = *this; if (dim_.getDataLen() + offset > dim.getDataLen()) throw std::invalid_argument( "Creating shared tensor of size bigger than tensor memory."); ret.dim = dim_; ret.strides = ret.dim.computeStrides(); /** * In this case, its the caller's responsibility to ensure that allocate() is * called for the output tensor before operating on the output tensor. */ createSharedDataTensor(*this, ret, offset); return ret; } void Tensor::makeSharedDataTensor(const Tensor &src, unsigned int offset) { if (strides != src.strides) throw std::invalid_argument( "Creating shared tensor of different stride than source tensor."); if (getDim().getDataLen() + offset > src.getDim().getDataLen()) throw std::invalid_argument( "Creating shared tensor of different size or stride than source tensor."); /** * In this case, its the caller's responsibility to ensure that allocate() is * called for the output tensor before operating on the output tensor. */ createSharedDataTensor(src, *this, offset); } void Tensor::apply_broadcast( Tensor const &m, std::function<void(const BroadcastInfo &e, const float *, const float *, float *)> v_func, Tensor &output) const { CREATE_IF_EMPTY_DIMS(output, dim); /// shortcut to cover when dimension matches /// note that buffer_size, the last stride is only used in v_func but it /// might be changed if (dim == m.dim) { BroadcastInfo e; e.buffer_size = length(); e.strides[3] = 1; v_func(e, getData(), m.getData(), output.getData()); return; } return apply_broadcast_util(m, v_func, output, this->computeBroadcastInfo(m)); } void Tensor::apply_broadcast_util( Tensor const &m, std::function<void(const BroadcastInfo &e, const float *, const float *, float *)> v_func, Tensor &output, const BroadcastInfo &e, int cur_axis, unsigned int offset, unsigned int m_offset) const { const float *buf = this->getData(); const float *m_buf = m.getData(); float *out_buf = output.getData(); if (e.buffer_axis == cur_axis) { v_func(e, buf + offset, m_buf + m_offset, out_buf + offset); return; } cur_axis++; for (unsigned int i = 0; i < dim.getTensorDim(cur_axis); ++i) { unsigned int next_offset = offset + i * strides[cur_axis]; unsigned int next_m_offset = m_offset + i * e.strides[cur_axis]; apply_broadcast_util(m, v_func, output, e, cur_axis, next_offset, next_m_offset); } } /** * This is to sum the Tensor data according to the dim.batch(). * Therefore the result has M(dim.batch(), 1, 1, 1) dimension. */ Tensor Tensor::sum_by_batch() { Tensor ret(dim.batch(), 1, 1, 1); unsigned int feat_len = dim.getFeatureLen(); unsigned int batch = dim.batch(); const float *data = getData(); float *rdata = ret.getData(); Tensor ones(1, 1, 1, feat_len); ones.setValue(1.0); sgemv(CblasRowMajor, CblasNoTrans, batch, feat_len, 1, data, feat_len, ones.getData(), 1, 0.0, rdata, 1); return ret; } /** * @brief Calculate sum according to the axis. */ Tensor Tensor::sum(unsigned int axis, float alpha) const { Tensor ret; return sum(ret, axis, alpha); } Tensor &Tensor::sum(Tensor &ret, unsigned int axis, float alpha) const { const float *data = getData(); if (axis >= 4) throw std::out_of_range("Error: axis is invalid"); if (dim.getDim()[axis] == 1 and alpha == 1.0) { CREATE_IF_EMPTY_DIMS(ret, dim); ret.copy(*this); return ret; } switch (axis) { case 0: { CREATE_IF_EMPTY_DIMS(ret, 1, dim.channel(), dim.height(), dim.width()); unsigned int feat_len = dim.getFeatureLen(); unsigned int batch = dim.batch(); Tensor ones(1, 1, 1, batch); ones.setValue(alpha); sgemv(CblasRowMajor, CblasTrans, batch, feat_len, 1, data, feat_len, ones.getData(), 1, 0.0, ret.getData(), 1); } break; case 1: { CREATE_IF_EMPTY_DIMS(ret, dim.batch(), 1, dim.height(), dim.width()); unsigned int feat_len = dim.height() * dim.width(); unsigned int channel = dim.channel(); Tensor ones(1, 1, 1, channel); ones.setValue(alpha); float *rdata = ret.getData(); for (unsigned int k = 0; k < dim.batch(); ++k) { sgemv(CblasRowMajor, CblasTrans, channel, feat_len, 1, &data[k * dim.getFeatureLen()], feat_len, ones.getData(), 1, 0.0, &rdata[k * feat_len], 1); } } break; case 2: { CREATE_IF_EMPTY_DIMS(ret, dim.batch(), dim.channel(), 1, dim.width()); unsigned int width = dim.width(); unsigned int height = dim.height(); Tensor ones(1, 1, 1, height); ones.setValue(alpha); float *rdata = ret.getData(); for (unsigned int k = 0; k < dim.batch(); ++k) { for (unsigned int c = 0; c < dim.channel(); ++c) { unsigned int idx = k * dim.getFeatureLen() + c * dim.width() * dim.height(); unsigned int ridx = k * ret.dim.getFeatureLen() + c * dim.width(); sgemv(CblasRowMajor, CblasTrans, height, width, 1, &data[idx], width, ones.getData(), 1, 0.0, &rdata[ridx], 1); } } } break; case 3: { CREATE_IF_EMPTY_DIMS(ret, dim.batch(), dim.channel(), dim.height(), 1); unsigned int m = ret.dim.getDataLen(); unsigned int n = dim.width(); Tensor ones(1, 1, 1, n); ones.setValue(alpha); sgemv(CblasRowMajor, CblasNoTrans, m, n, 1, data, n, ones.getData(), 1, 0.0, ret.getData(), 1); } break; default: throw std::out_of_range("Error: Dimension cannot exceed 3"); } return ret; } Tensor Tensor::sum(const std::vector<unsigned int> &axes, float alpha) const { if (axes.empty()) throw std::invalid_argument("empty axes given"); Tensor ret = this->sum(axes[0], alpha); for (unsigned int i = 1; i < axes.size(); ++i) ret = ret.sum(axes[i]); return ret; } Tensor Tensor::dot(Tensor const &m, bool trans, bool trans_m) const { Tensor output; dot(m, output, trans, trans_m); return output; } /** * @note: This dot product flattens the fist 3 axis for the purpose of * computation. So, while performing, these matrices are behaving as 2-D * matrices. The dimensions are restored while returning back the tensor * in case of trans is false. */ Tensor &Tensor::dot(Tensor const &m, Tensor &result, bool trans, bool trans_m, float beta) const { if (m.dim.rank() > 2) { throw exception::not_supported("Error: support only for rank of dot " "matrix <= 2"); } if (trans && dim.rank() > 2) { throw exception::not_supported("Error: support only for rank of dot " "matrix <= 2 with trans"); } unsigned int dim1 = batch() * channel() * height(); unsigned int dim2 = width(); unsigned int mdim1 = m.batch() * m.channel() * m.height(); unsigned int mdim2 = m.width(); unsigned int M, N, K, lda, ldb, ldc; if (!trans && !trans_m) { if (dim2 != mdim1) throw std::runtime_error( "Error: incompatible dimensions for dot product"); K = mdim1; /** == dim2 */ N = mdim2; M = dim1; CREATE_IF_EMPTY_DIMS(result, batch(), channel(), height(), N); // We are not set zero the result because of performnace reason. // However, result is not initialized properly. There might include // garbage like nan. When we have to use this value as in C = alpha*A*B + // beta*C, then have to check gargabe data of C is not effect or not. } else if (!trans && trans_m) { if (dim2 != mdim2) throw std::runtime_error( "Error: incompatible dimensions for dot product"); K = mdim2; /** == dim2 */ N = mdim1; M = dim1; CREATE_IF_EMPTY_DIMS(result, batch(), channel(), height(), N); } else if (trans && !trans_m) { if (dim1 != mdim1) throw std::runtime_error( "Error: incompatible dimensions for dot product"); K = mdim1; /** == dim1 */ N = mdim2; M = dim2; CREATE_IF_EMPTY_DIMS(result, 1, 1, M, N); } else { if (dim1 != mdim2) throw std::runtime_error( "Error: incompatible dimensions for dot product"); K = mdim2; /** == dim1 */ N = mdim1; M = dim2; CREATE_IF_EMPTY_DIMS(result, 1, 1, M, N); } lda = dim2; ldb = mdim2; ldc = result.width(); const float *data = getData(); const float *mdata = m.getData(); float *rdata = result.getData(); const float alpha = 1.0f; enum CBLAS_TRANSPOSE transA = trans ? CblasTrans : CblasNoTrans; enum CBLAS_TRANSPOSE transB = trans_m ? CblasTrans : CblasNoTrans; /// shortcut handling in case of vector /// for vector, (1 * K) == (K * 1) in current memory layout... /// and plaese note that N, K, M is a fixed place holder after considering /// transpose. /// For example, there is no case like (1 * K) X (1 * K) while /// (1 * K) X (1 * M) can be a case /// case1: (1 * K) X (K * 1) if (M == 1 && N == 1) { *rdata = sdot(K, data, 1, mdata, 1) + beta * (*rdata); } /// case2: (M * K) X (K * 1) else if (N == 1) { sgemv(CblasRowMajor, transA, dim1, dim2, alpha, data, lda, mdata, 1, beta, rdata, 1); } /// case3: (1 * K) X (K * N) = 1 * N = R /// = R^T = (K * N) ^T * (1 * K) ^T = (N * K) * (K * 1) = (N * K) * (1 * K) /// Effectively a translation of sgemv else if (M == 1) { transB = transB == CblasTrans ? CblasNoTrans : CblasTrans; sgemv(CblasRowMajor, transB, mdim1, mdim2, alpha, mdata, ldb, data, 1, beta, rdata, 1); } /// case others: use gemm else { sgemm(CblasRowMajor, transA, transB, M, N, K, alpha, data, lda, mdata, ldb, beta, rdata, ldc); } return result; } Tensor Tensor::transpose(std::string direction) const { unsigned int SL, SI, SJ, SK; int dir[MAXDIM - 1]; unsigned int fromDim[4]; const float *inptr; float *outptr; fromDim[0] = dim.batch(); fromDim[1] = dim.channel(); fromDim[2] = dim.height(); fromDim[3] = dim.width(); getValues(3, direction, dir); Tensor result(dim.batch(), fromDim[dir[0] + 1], fromDim[dir[1] + 1], fromDim[dir[2] + 1]); int indexI = dir[0]; int indexJ = dir[1]; SL = fromDim[0], SI = fromDim[1], SJ = fromDim[2], SK = fromDim[3]; inptr = getData(); outptr = result.getData(); switch (indexI) { case 0: if (indexJ == 1) { transposeloop(l, i, j, k, SL, SI, SJ, SK); } else { transposeloop(l, i, k, j, SL, SI, SK, SJ); } break; case 1: if (indexJ == 0) { transposeloop(l, j, i, k, SL, SJ, SI, SK); } else { transposeloop(l, j, k, i, SL, SJ, SK, SI); } break; case 2: if (indexJ == 0) { transposeloop(l, k, i, j, SL, SK, SI, SJ); } else { transposeloop(l, k, j, i, SL, SK, SJ, SI); } break; } return result; } int Tensor::apply_i(std::function<float(float)> f) { float *data = getData(); std::transform(data, data + length(), data, f); return ML_ERROR_NONE; } Tensor Tensor::apply(std::function<float(float)> f) const { Tensor result; return apply(f, result); } Tensor &Tensor::apply(std::function<float(float)> f, Tensor &output) const { CREATE_IF_EMPTY_DIMS(output, dim); const float *data = getData(); float *rdata = output.getData(); if (dim != output.dim) { /// @todo add unittest throw std::invalid_argument( "[Tensor::apply] output dimension does not match"); } std::transform(data, data + length(), rdata, f); return output; } Tensor Tensor::apply(std::function<Tensor(Tensor)> f) const { return f(*this); } Tensor &Tensor::apply(std::function<Tensor &(Tensor, Tensor &)> f, Tensor &output) const { return f(*this, output); } void Tensor::print(std::ostream &out) const { printInstance(out, this); const float *data = getData(); unsigned int len = length(); out << "data addr: " << data << '\n'; out << dim; if (len > 100) { out << '[' << data[0] << ' ' << data[1] << ' ' << data[2] << " ... " << data[len - 3] << ' ' << data[len - 2] << ' ' << data[len - 1] << ']' << std::endl; return; } std::ios init(NULL); init.copyfmt(out); for (unsigned int k = 0; k < dim.batch(); k++) { for (unsigned int l = 0; l < dim.channel(); l++) { for (unsigned int i = 0; i < dim.height(); i++) { for (unsigned int j = 0; j < dim.width(); j++) { out << std::setw(10) << std::setprecision(10) << this->getValue(k, l, i, j) << " "; } out << std::endl; } out << std::endl; } out << "-------" << std::endl; } out.copyfmt(init); } std::ostream &operator<<(std::ostream &out, Tensor const &m) { m.print(out); return out; } float *Tensor::getAddress(unsigned int i) { if (i > this->dim.getDataLen()) { ml_loge("Error: Index out of bounds"); return nullptr; } return &getData()[i]; } const float *Tensor::getAddress(unsigned int i) const { if (i > this->dim.getDataLen()) { ml_loge("Error: Index out of bounds"); return nullptr; } return &getData()[i]; } void Tensor::copy(const float *buf) noexcept { if (buf == getData()) { return; } scopy(length(), buf, 1, getData(), 1); } void Tensor::copy(const Tensor &from) { // todo: enable copy to non-contiguous tensor if (!is_contiguous) { throw std::runtime_error("Cannot copy non-contiguous tensor"); } if (from.length() != 0 && length() == from.length()) { reshape(from.getDim()); copy(from.getData()); } else { Tensor t = Tensor(from.getDim(), from.getData()); swap(t, *this); } } Tensor Tensor::clone() const { Tensor t; t.copy(*this); return t; } void Tensor::reshape(const TensorDim &d) { if (d.getDataLen() != dim.getDataLen()) { throw std::invalid_argument("Error: reshape cannot change the tensor size"); } dim = d; strides = d.computeStrides(); } void Tensor::fill(const Tensor &from, bool initialize) { if (initialize && this->uninitialized()) { this->copy(from); return; } if (!from.is_contiguous || !is_contiguous) { /// @todo enable this if needed throw nntrainer::exception::not_supported( "[Tensor::fill] non-contiguous tensors are not supported"); } if (dim != from.getDim()) { throw std::invalid_argument("[Tensor::fill] dimension must be the same"); } if (strides != from.getStrides()) { /// @todo length does not represent buffer size, there should be way to get /// the buffer size throw std::invalid_argument("[Tensor::fill] buffer size must be the same"); } this->copy(from.getData()); } void Tensor::save(std::ofstream &file) { checkedWrite(file, (char *)getData(), getSize(), "[Tensor::save] operation failed"); } void Tensor::read(std::ifstream &file) { checkedRead(file, (char *)getData(), getSize(), "[Tensor::read] operation failed"); } /** * @brief Calculate average value according to the axis. */ Tensor Tensor::average(unsigned int axis) const { if (axis >= MAXDIM) throw std::out_of_range( "negative axis or axis more then MAXDIM is invalid"); unsigned int axis_size = dim.getDim()[axis]; if (axis_size == 1) return this->clone(); return this->sum(axis, 1.0 / ((float)axis_size)); } Tensor Tensor::average(const std::vector<unsigned int> &axes) const { if (axes.empty()) return this->average(); TensorDim ret_shape; for (const auto &idx : axes) { if (idx >= MAXDIM) { throw std::out_of_range("axis more then MAXDIM is invalid"); } ret_shape.setTensorDim(idx, dim.getTensorDim(idx)); } return this->sum(axes, 1.0 / (float)ret_shape.getDataLen()); } /** * @brief Calculate average value according to the axis. */ Tensor Tensor::average() const { Tensor result = *this; result.reshape({1, 1, 1, dim.getDataLen()}); return result.average(3); } void Tensor::setValue(float val) { float *data = getData(); std::fill(data, data + length(), val); } void Tensor::setZero() { sscal(length(), 0, getData(), 1); } std::vector<unsigned int> Tensor::argmax() const { const float *data = getData(); std::vector<unsigned int> result; unsigned int batch_size = batch(); unsigned int feature_len = dim.getFeatureLen(); result.resize(batch_size); for (unsigned int b = 0; b < batch_size; b++) { auto max_iter = std::max_element(data + b * feature_len, data + (b + 1) * feature_len); result[b] = std::distance(data, max_iter) - (b * feature_len); } return result; } float Tensor::l2norm() const { unsigned int len = length(); const float *data = getData(); return snrm2(len, data, 1); } float Tensor::max_abs() const { unsigned int len = length(); const float *data = getData(); unsigned int idx = isamax(len, data, 1); return *(data + idx); } Tensor &Tensor::normalization(Tensor &output) const { if (output.uninitialized()) output = Tensor(dim); output.copy(*this); output.normalization_i(); return output; } void Tensor::normalization_i() { const float *data = getData(); auto bounds = std::minmax_element(data, data + length()); const float min = *bounds.first; const float max = *bounds.second; if (max == min) { Tensor tmp = *this; this->subtract_i(tmp); } else { this->subtract_i(min); this->divide_i(max - min); } } LazyTensor Tensor::chain() const { return LazyTensor(*this); } Tensor &Tensor::standardization(Tensor &output) const { if (output.uninitialized()) output = Tensor(dim); output.copy(*this); output.standardization_i(); return output; } void Tensor::standardization_i() { Tensor mean_by_batch = this->sum_by_batch(); mean_by_batch.divide_i(dim.getFeatureLen()); this->subtract_i(mean_by_batch); Tensor std_dev_by_batch(dim.batch(), 1, 1, 1); std_dev_by_batch.setZero(); float *std_dev = std_dev_by_batch.getData(); for (unsigned int k = 0; k < dim.batch(); ++k) { Tensor sub_this = this->getBatchSlice(k, 1); std_dev[k] = sub_this.l2norm(); } std_dev_by_batch.divide_i(dim.getFeatureLen()); this->divide_i(std_dev_by_batch); } Tensor::BroadcastInfo Tensor::computeBroadcastInfo(const Tensor &m) const { if (m.length() > this->length()) throw exception::not_supported("broadcasting *this is not supported"); const TensorDim m_dim = m.getDim(); BroadcastInfo e; /// checking if given Tensor's can be broadcasted for (unsigned int i = 0; i < MAXDIM; ++i) { if (dim.getTensorDim(i) == m_dim.getTensorDim(i)) { e.strides[i] = m.strides[i]; continue; } /// If given dimension is 1, it could be reused, the stride remaining 0 /// Need to check if dim[i] == 1 && m_dim[i] == 1 first though /// If so, strides should not change if (m_dim.getTensorDim(i) == 1) { continue; } std::stringstream ss; ss << "[computeBroadcastInfo] broadcasting only allowed for " "dimension value of 1 \n" << "this: " << dim << "target: " << m_dim; throw std::invalid_argument(ss.str().c_str()); } /// calculate inner loop size e.buffer_size = 1; e.buffer_axis = -1; e.strides[3] = m.strides[3]; /// initiate buffer info with matching dimension strategy for (int axis = 3; axis >= 0; --axis) { if (dim.getTensorDim(axis) != m_dim.getTensorDim(axis)) { e.buffer_axis = axis; break; } e.buffer_size *= dim.getTensorDim(axis); } /// check strategy that uses consecutive ones if (m_dim.getTensorDim(3) == 1) { unsigned int inner_loop_size = 1; int axis; for (axis = 3; axis >= 0; --axis) { if (m_dim.getTensorDim(axis) != 1) { break; } inner_loop_size *= dim.getTensorDim(axis); } /// if consecutive-one strategy has bigger chunk size, replace the /// information if (inner_loop_size > e.buffer_size) { e.buffer_axis = axis; e.buffer_size = inner_loop_size; e.strides[3] = 0; } } return e; } } /* namespace nntrainer */
27.932134
80
0.610082
[ "object", "vector", "transform" ]
ce6854efc0cc3c49947d03ef5e18e7abf1d43b78
1,108
cpp
C++
src/nvmesh/param/BoundaryMap.cpp
akien-mga/thekla_atlas
80a1430e16f10b9e79c153a6ac981601be2d64d4
[ "MIT" ]
null
null
null
src/nvmesh/param/BoundaryMap.cpp
akien-mga/thekla_atlas
80a1430e16f10b9e79c153a6ac981601be2d64d4
[ "MIT" ]
null
null
null
src/nvmesh/param/BoundaryMap.cpp
akien-mga/thekla_atlas
80a1430e16f10b9e79c153a6ac981601be2d64d4
[ "MIT" ]
1
2021-01-07T07:38:39.000Z
2021-01-07T07:38:39.000Z
// This code is in the public domain -- castano@gmail.com #include "BoundaryMap.h" #include "Util.h" #include <nvmath/Sparse.h> #include <nvmath/Solver.h> #include <nvmesh/halfedge/Edge.h> #include <nvmesh/halfedge/Mesh.h> #include <nvmesh/halfedge/Vertex.h> #include <nvmesh/halfedge/Face.h> using namespace nv; bool nv::computeCircularBoundaryMap(HalfEdge::Mesh * mesh) { HalfEdge::Vertex * vertex = findBoundaryVertex(mesh); if (vertex == NULL) { return false; } // Compute boundary length. float boundaryLength = 0.0f; HalfEdge::Edge * const firstEdge = vertex->edge(); HalfEdge::Edge * edge = firstEdge; do { boundaryLength += edge->length(); edge = edge->next(); } while (edge != firstEdge); float length = 0.0f; edge = firstEdge; do { float angle = length * 2.0f * PI / boundaryLength; edge->vertex()->tex.set(cos(angle), sin(angle)); length += edge->length(); edge = edge->next(); } while (edge != firstEdge); return true; }
21.72549
59
0.595668
[ "mesh" ]
ce6c14e4688b0b7d01610f955c80fcb453f393a0
281,399
cpp
C++
src/md/compiler/mdvalidator.cpp
mans0954/debian-dotnet-coreclr
5e42f510f19534800c8271bf83a9bf5e0c730b84
[ "MIT" ]
6
2017-09-22T06:55:45.000Z
2021-07-02T07:07:08.000Z
src/md/compiler/mdvalidator.cpp
mthalman/coreclr
102bea2e12753af9b723cf5370108b7eea3d74cb
[ "MIT" ]
2
2017-09-23T08:21:05.000Z
2017-09-27T03:31:06.000Z
src/md/compiler/mdvalidator.cpp
mthalman/coreclr
102bea2e12753af9b723cf5370108b7eea3d74cb
[ "MIT" ]
2
2017-06-04T15:47:12.000Z
2020-03-16T07:01:47.000Z
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. //***************************************************************************** // MDValidator.cpp // // // Implementation for the MetaData validator. // Only supported for full mscorwks version. // //***************************************************************************** #include "stdafx.h" #ifdef FEATURE_METADATA_VALIDATOR #include "regmeta.h" #include "importhelper.h" #include "pedecoder.h" #include "stgio.h" #include "corhost.h" #include "sstring.h" #include "nsutilpriv.h" #include "holder.h" #include "vererror.h" #include "mdsighelper.h" #ifdef DACCESS_COMPILE #error Dac should be using standalone version of metadata, not Wks version. #endif //----------------------------------------------------------------------------- // Application specific debug macro. #define IfBreakGo(EXPR) \ do {if ((EXPR) != S_OK) IfFailGo(VLDTR_E_INTERRUPTED); } while (0) //----------------------------------------------------------------------------- //#define CACHE_IMPLMAP_VALIDATION_RESULT #ifdef CACHE_IMPLMAP_VALIDATION_RESULT // To avoid multiple validation of the same thing: struct ValidationResult { mdToken tok; HRESULT hr; }; ValidationResult* g_rValidated=NULL; // allocated in ValidateMetaData unsigned g_nValidated=0; #endif //----------------------------------------------------------------------------- #define BASE_OBJECT_CLASSNAME "Object" #define BASE_NAMESPACE "System" #define BASE_VTYPE_CLASSNAME "ValueType" #define BASE_ENUM_CLASSNAME "Enum" #define BASE_VALUE_FIELDNAME "value__" #define BASE_CTOR_NAME ".ctor" #define BASE_CCTOR_NAME ".cctor" #define BASE_MCDELEGATE_CLASSNAME "MulticastDelegate" #define SYSTEM_OBJECT_TOSTRING_METHODNAME "ToString" #define SYSTEM_OBJECT_GETHASHCODE_METHODNAME "GetHashCode" #define SYSTEM_OBJECT_EQUALS_METHODNAME "Equals" // string ToString() static const BYTE g_sigSystemObject_ToString[] = { IMAGE_CEE_CS_CALLCONV_HASTHIS, // 0x20 0, // 0x00 ... Param Count ELEMENT_TYPE_STRING // 0x0e ... Return Type - string }; // int GetHashCode() static const BYTE g_sigSystemObject_GetHashCode[] = { IMAGE_CEE_CS_CALLCONV_HASTHIS, // 0x20 0, // 0x00 ... Param Count ELEMENT_TYPE_I4 // 0x08 ... Return Type - I4 }; // bool Equals(object) static const BYTE g_sigSystemObject_Equals[] = { IMAGE_CEE_CS_CALLCONV_HASTHIS, // 0x20 1, // 0x01 ... Param Count ELEMENT_TYPE_BOOLEAN, // 0x02 ... Return Type - bool ELEMENT_TYPE_OBJECT // 0x1c ... Param #1 - object }; // as defined in src\vm\vars.hpp #define MAX_CLASSNAME_LENGTH 1024 //----------------------------------------------------------------------------- // Class names used in long form signatures (namespace is always "System") unsigned g_NumSigLongForms = 19; static const LPCSTR g_SigLongFormName[] = { "String", "______", // "Object", <REVISIT_TODO>// uncomment when EE handles ELEMENT_TYPE_OBJECT</REVISIT_TODO> "Boolean", "Char", "Byte", "SByte", "UInt16", "Int16", "UInt32", "Int32", "UInt64", "Int64", "Single", "Double", "SysInt", // Review this. "SysUInt", // Review this. "SingleResult", "Void", "IntPtr" }; // <REVISIT_TODO>: Why are these global variables?</REVISIT_TODO> mdToken g_tkEntryPoint; bool g_fValidatingMscorlib; bool g_fIsDLL; //----------------------------------------------------------------------------- static HRESULT _FindClassLayout( CMiniMdRW *pMiniMd, // [IN] the minimd to lookup mdTypeDef tkParent, // [IN] the parent that ClassLayout is associated with RID *clRid, // [OUT] rid for the ClassLayout. RID rid); // [IN] rid to be ignored. static HRESULT _FindFieldLayout( CMiniMdRW *pMiniMd, // [IN] the minimd to lookup mdFieldDef tkParent, // [IN] the parent that FieldLayout is associated with RID *flRid, // [OUT] rid for the FieldLayout record. RID rid); // [IN] rid to be ignored. static BOOL _IsValidLocale(LPCUTF8 szLocale, BOOL fIsV2Assembly); #define REPORT_ERROR0(_VECode) \ IfFailGo(_ValidateErrorHelper(_VECode, veCtxt)) #define REPORT_ERROR1(_VECode, _Arg0) \ IfFailGo(_ValidateErrorHelper(_VECode, veCtxt, _Arg0)) #define REPORT_ERROR2(_VECode, _Arg0, _Arg1) \ IfFailGo(_ValidateErrorHelper(_VECode, veCtxt, _Arg0, _Arg1)) #define REPORT_ERROR3(_VECode, _Arg0, _Arg1, _Arg2) \ IfFailGo(_ValidateErrorHelper(_VECode, veCtxt, _Arg0, _Arg1, _Arg2)) //***************************************************************************** // Returns true if ixPtrTbl and ixParTbl are a valid parent-child combination // in the pointer table scheme. //***************************************************************************** static inline bool IsTblPtr(ULONG ixPtrTbl, ULONG ixParTbl) { if ((ixPtrTbl == TBL_Field && ixParTbl == TBL_TypeDef) || (ixPtrTbl == TBL_Method && ixParTbl == TBL_TypeDef) || (ixPtrTbl == TBL_Param && ixParTbl == TBL_Method) || (ixPtrTbl == TBL_Property && ixParTbl == TBL_PropertyMap) || (ixPtrTbl == TBL_Event && ixParTbl == TBL_EventMap)) { return true; } return false; } // IsTblPtr() //***************************************************************************** // This inline function is used to set the return hr value for the Validate // functions to one of VLDTR_S_WRN, VLDTR_S_ERR or VLDTR_S_WRNERR based on // the current hr value and the new success code. // The general algorithm for error codes from the validation functions is: // if (no warnings or errors found) // return S_OK or S_FALSE // else if (warnings found) // return VLDTR_S_WRN // else if (errors found) // return VLDTR_S_ERR // else if (warnings and errors found) // return VLDTR_S_WRNERR //***************************************************************************** static inline void SetVldtrCode(HRESULT *phr, HRESULT successcode) { _ASSERTE(successcode == S_OK || successcode == S_FALSE ||successcode == VLDTR_S_WRN || successcode == VLDTR_S_ERR || successcode == VLDTR_S_WRNERR); _ASSERTE(*phr == S_OK || *phr == VLDTR_S_WRN || *phr == VLDTR_S_ERR || *phr == VLDTR_S_WRNERR); if (successcode == S_OK || successcode == S_FALSE ||*phr == VLDTR_S_WRNERR) return; else if (*phr == S_OK || *phr == S_FALSE) *phr = successcode; else if (*phr != successcode) *phr = VLDTR_S_WRNERR; } // SetVldtrCode() //***************************************************************************** // Initialize the Validator related structures in RegMeta. //***************************************************************************** HRESULT RegMeta::ValidatorInit( // S_OK or error. DWORD dwModuleType, // [IN] Specifies whether the module is a PE file or an obj. IUnknown *pUnk) // [IN] Validation error handler. { HRESULT hr = S_OK; // Return value. BEGIN_ENTRYPOINT_NOTHROW; int i = 0; // Index into the function pointer table. // Initialize the array of function pointers to the validation function on // each table. #undef MiniMdTable #define MiniMdTable(x) m_ValidateRecordFunctionTable[i++] = &RegMeta::Validate##x; MiniMdTables() // Verify that the ModuleType passed in is a valid one. if (dwModuleType < ValidatorModuleTypeMin || dwModuleType > ValidatorModuleTypeMax) { IfFailGo(E_INVALIDARG); } // Verify that the interface passed in supports IID_IVEHandler. IfFailGo(pUnk->QueryInterface(IID_IVEHandler, (void **)&m_pVEHandler)); // Set the ModuleType class member. Do this last, this is used in // ValidateMetaData to see if the validator is correctly initialized. m_ModuleType = (CorValidatorModuleType)dwModuleType; ErrExit: END_ENTRYPOINT_NOTHROW; return hr; } // HRESULT RegMeta::ValidatorInit() //***************************************************************************** // Public implementation for code:IMetaDataValidate::ValidateMetaData // // Validate the entire MetaData. Here is the basic algorithm. // for each table // for each record // { // Do generic validation - validate that the offsets into the blob // pool are good, validate that all the rids are within range, // validate that token encodings are consistent. // } // if (problems found in generic validation) // return; // for each table // for each record // Do semantic validation. //****************************************************************************** HRESULT RegMeta::ValidateMetaData() { HRESULT hr = S_OK; BEGIN_ENTRYPOINT_NOTHROW; CMiniMdRW * pMiniMd = &(m_pStgdb->m_MiniMd); HRESULT hrSave = S_OK; // Saved hr from generic validation. ULONG ulCount; // Count of records in the current table. ULONG i; // Index to iterate over the tables. ULONG j; // Index to iterate over the records in a given table. IHostTaskManager * pHostTaskManager = NULL; #ifdef CACHE_IMPLMAP_VALIDATION_RESULT ULONG rValidatedSize=0; // Size of g_rValidated array #endif // Verify that the validator is initialized correctly if (m_ModuleType == ValidatorModuleTypeInvalid) { _ASSERTE(!"Validator not initialized, initialize with ValidatorInit()."); IfFailGo(VLDTR_E_NOTINIT); } // First do a validation pass to do some basic structural checks based on // the Meta-Meta data. This'll validate all the offsets into the pools, // rid value and coded token ranges. for (i = 0; i < pMiniMd->GetCountTables(); i++) { ulCount = pMiniMd->GetCountRecs(i); #ifdef CACHE_IMPLMAP_VALIDATION_RESULT switch(i) { case TBL_ImplMap: rValidatedSize += ulCount; default: ; } #endif for (j = 1; j <= ulCount; j++) { IfFailGo(ValidateRecord(i, j)); SetVldtrCode(&hrSave, hr); } } // Validate that the size of the Ptr tables matches with the corresponding // real tables. // Do not do semantic validation if structural validation failed. if (hrSave != S_OK) { hr = hrSave; goto ErrExit; } // Verify the entry point (if any) ::g_tkEntryPoint = 0; ::g_fIsDLL = false; if(m_pStgdb && m_pStgdb->m_pImage) { NewHolder<PEDecoder> pe; EX_TRY { // We need to use different PEDecoder constructors based on the type of data we give it. // We use the one with a 'bool' as the second argument when dealing with a mapped file, // and we use the one that takes a COUNT_T as the second argument when dealing with a // flat file. if (m_pStgdb->m_pStgIO->GetMemoryMappedType() == MTYPE_IMAGE) pe = new (nothrow) PEDecoder(m_pStgdb->m_pImage, false); else pe = new (nothrow) PEDecoder(m_pStgdb->m_pImage, (COUNT_T)(m_pStgdb->m_dwImageSize)); hr = S_OK; } EX_CATCH { hr = COR_E_BADIMAGEFORMAT; } EX_END_CATCH(SwallowAllExceptions) if (SUCCEEDED(hr) && pe == NULL) IfFailGo(E_OUTOFMEMORY); if(FAILED(hr) || !pe->CheckFormat()) { VEContext veCtxt; // Context structure. memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = 0; veCtxt.uOffset = 0; REPORT_ERROR0(COR_E_BADIMAGEFORMAT); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if(!pe->IsILOnly()) { VEContext veCtxt; // Context structure. memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = 0; veCtxt.uOffset = 0; REPORT_ERROR0(VER_E_BAD_PE); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if((pe->GetCorHeader()->Flags & COMIMAGE_FLAGS_NATIVE_ENTRYPOINT) == 0) g_tkEntryPoint = pe->GetEntryPointToken(); g_fIsDLL = pe->IsDll() ? true : false; if(g_tkEntryPoint) { RID rid = RidFromToken(g_tkEntryPoint); RID maxrid = 0; switch(TypeFromToken(g_tkEntryPoint)) { case mdtMethodDef: maxrid = pMiniMd->getCountMethods(); break; case mdtFile: maxrid = pMiniMd->getCountFiles(); break; default: break; } if((rid == 0)||(rid > maxrid)) { VEContext veCtxt; // Context structure. memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = g_tkEntryPoint; veCtxt.uOffset = 0; REPORT_ERROR0(VLDTR_E_EP_BADTOKEN); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } else if(!g_fIsDLL) // exe must have an entry point { VEContext veCtxt; // Context structure. memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = g_tkEntryPoint; veCtxt.uOffset = 0; REPORT_ERROR0(VLDTR_E_EP_BADTOKEN); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } g_fValidatingMscorlib = false; if(pMiniMd->GetCountRecs(TBL_Assembly)) { AssemblyRec *pRecord; IfFailGo(pMiniMd->GetAssemblyRecord(1, &pRecord)); LPCSTR szName; IfFailGo(pMiniMd->getNameOfAssembly(pRecord, &szName)); g_fValidatingMscorlib = (0 == SString::_stricmp(szName,"mscorlib")); } // Verify there are no circular class hierarchies. // Do per record semantic validation on the MetaData. The function // pointers to the per record validation are stored in the table by the // ValidatorInit() function. #ifdef CACHE_IMPLMAP_VALIDATION_RESULT g_rValidated = NULL; ::g_nValidated = 0; if (rValidatedSize) { g_rValidated = new(nothrow) ValidationResult[rValidatedSize]; IfNullGo(g_rValidated); } #endif pHostTaskManager = CorHost2::GetHostTaskManager(); #ifdef Sleep #undef Sleep #endif //DWORD cBegin=0,cEnd=0; for (i = 0; i < pMiniMd->GetCountTables(); i++) { ulCount = pMiniMd->GetCountRecs(i); //cBegin = GetTickCount(); for (j = 1; j <= ulCount; j++) { IfFailGo((this->*m_ValidateRecordFunctionTable[i])(j)); SetVldtrCode(&hrSave, hr); if(pHostTaskManager) { // SwitchToTask forces the current thread to give up quantum, while a host can decide what // to do with Sleep if the current thread has not run out of quantum yet. ClrSleepEx(0, FALSE); } } //cEnd = GetTickCount(); //printf("Table %d, recs: %d, time: %d\n",i,ulCount,(cEnd-cBegin)); } hr = hrSave; ErrExit: #ifdef CACHE_IMPLMAP_VALIDATION_RESULT if(g_rValidated) delete [] g_rValidated; #endif END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateMetaData() //***************************************************************************** // Validate the Module record. //***************************************************************************** HRESULT RegMeta::ValidateModule(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd for the scope. ModuleRec *pRecord; // Module record. VEContext veCtxt; // Context structure. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. LPCSTR szName; GUID GuidOfModule; BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Get the Module record. veCtxt.Token = TokenFromRid(rid, mdtModule); veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetModuleRecord(rid, &pRecord)); // There can only be one Module record. if (rid > 1) { REPORT_ERROR0(VLDTR_E_MOD_MULTI); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Verify the name IfFailGo(pMiniMd->getNameOfModule(pRecord, &szName)); if(szName && *szName) { ULONG L = (ULONG)strlen(szName); if(L >= MAX_CLASSNAME_LENGTH) { // Name too long REPORT_ERROR2(VLDTR_E_TD_NAMETOOLONG, L, (ULONG)(MAX_CLASSNAME_LENGTH-1)); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if(strchr(szName,':') || strchr(szName,'\\')) { REPORT_ERROR0(VLDTR_E_MOD_NAMEFULLQLFD); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } else { REPORT_ERROR0(VLDTR_E_MOD_NONAME); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Verify that the MVID is valid. IfFailGo(pMiniMd->getMvidOfModule(pRecord, &GuidOfModule)); if (GuidOfModule == GUID_NULL) { REPORT_ERROR0(VLDTR_E_MOD_NULLMVID); SetVldtrCode(&hrSave, VLDTR_S_ERR); } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateModule() //***************************************************************************** // Validate the given TypeRef. //***************************************************************************** HRESULT RegMeta::ValidateTypeRef(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. TypeRefRec *pRecord; // TypeRef record. mdToken tkRes; // Resolution scope. LPCSTR szNamespace; // TypeRef Namespace. LPCSTR szName; // TypeRef Name. mdTypeRef tkTypeRef; // Duplicate TypeRef. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Get the TypeRef record. veCtxt.Token = TokenFromRid(rid, mdtTypeRef); veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetTypeRefRecord(rid, &pRecord)); // Check name is not NULL. IfFailGo(pMiniMd->getNamespaceOfTypeRef(pRecord, &szNamespace)); IfFailGo(pMiniMd->getNameOfTypeRef(pRecord, &szName)); if (!*szName) { REPORT_ERROR0(VLDTR_E_TR_NAMENULL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { RID ridScope; // Look for a Duplicate, this function reports only one duplicate. tkRes = pMiniMd->getResolutionScopeOfTypeRef(pRecord); hr = ImportHelper::FindTypeRefByName(pMiniMd, tkRes, szNamespace, szName, &tkTypeRef, rid); if (hr == S_OK) { REPORT_ERROR1(VLDTR_E_TR_DUP, tkTypeRef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (hr == CLDB_E_RECORD_NOTFOUND) hr = S_OK; else IfFailGo(hr); ULONG L = (ULONG)(strlen(szName)+strlen(szNamespace)); if(L >= MAX_CLASSNAME_LENGTH) { REPORT_ERROR2(VLDTR_E_TD_NAMETOOLONG, L, (ULONG)(MAX_CLASSNAME_LENGTH-1)); SetVldtrCode(&hrSave, VLDTR_S_ERR); } ridScope = RidFromToken(tkRes); if(ridScope) { bool badscope = true; //check if valid scope switch(TypeFromToken(tkRes)) { case mdtAssemblyRef: case mdtModuleRef: case mdtModule: case mdtTypeRef: badscope = !IsValidToken(tkRes); break; default: break; } if(badscope) { REPORT_ERROR1(VLDTR_E_TR_BADSCOPE, tkTypeRef); SetVldtrCode(&hrSave, VLDTR_S_WRN); } } else { // check if there is a ExportedType //hr = ImportHelper::FindExportedType(pMiniMd, szNamespace, szName, tkImpl, &tkExportedType, rid); } // Check if there is TypeDef with the same name if(!ridScope) { if((TypeFromToken(tkRes) != mdtTypeRef) && (S_OK == ImportHelper::FindTypeDefByName(pMiniMd, szNamespace, szName, mdTokenNil,&tkTypeRef, 0))) { REPORT_ERROR1(VLDTR_E_TR_HASTYPEDEF, tkTypeRef); SetVldtrCode(&hrSave, VLDTR_S_WRN); } } } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateTypeRef() //***************************************************************************** // Validate the given TypeDef. //***************************************************************************** #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:21000) // Suppress PREFast warning about overly large function #endif HRESULT RegMeta::ValidateTypeDef(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. TypeDefRec *pRecord; // TypeDef record. TypeDefRec *pExtendsRec = 0; // TypeDef record for the parent class. mdTypeDef tkTypeDef; // Duplicate TypeDef token. DWORD dwFlags; // TypeDef flags. DWORD dwExtendsFlags; // TypeDef flags of the parent class. LPCSTR szName; // TypeDef Name. LPCSTR szNameSpace; // TypeDef NameSpace. LPCSTR szExtName = NULL; // Parent Name. LPCSTR szExtNameSpace = NULL; // Parent NameSpace. CQuickBytes qb; // QuickBytes for flexible allocation. mdToken tkExtends; // TypeDef of the parent class. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. mdToken tkEncloser=mdTokenNil; // Encloser, if any BOOL bIsEnum,bExtendsEnum,bExtendsVType,bIsVType,bExtendsObject,bIsObject,bExtendsMCDelegate; BOOL bHasMethods=FALSE, bHasFields=FALSE; BEGIN_ENTRYPOINT_NOTHROW; // Skip validating m_tdModule class. if (rid == RidFromToken(m_tdModule)) goto ErrExit; memset(&veCtxt, 0, sizeof(VEContext)); // Get the TypeDef record. veCtxt.Token = TokenFromRid(rid, mdtTypeDef); veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetTypeDefRecord(rid, &pRecord)); // Do checks for name validity.. IfFailGo(pMiniMd->getNameOfTypeDef(pRecord, &szName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pRecord, &szNameSpace)); if (!*szName) { // TypeDef Name is null. REPORT_ERROR0(VLDTR_E_TD_NAMENULL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (!IsDeletedName(szName)) { RID iRecord; IfFailGo(pMiniMd->FindNestedClassHelper(TokenFromRid(rid, mdtTypeDef), &iRecord)); if (InvalidRid(iRecord)) { tkEncloser = mdTokenNil; } else { NestedClassRec *pNestedClassRec; IfFailGo(pMiniMd->GetNestedClassRecord(iRecord, &pNestedClassRec)); tkEncloser = pMiniMd->getEnclosingClassOfNestedClass(pNestedClassRec); } // Check for duplicates based on Name/NameSpace. Do not do Dup checks // on deleted records. hr = ImportHelper::FindTypeDefByName(pMiniMd, szNameSpace, szName, tkEncloser, &tkTypeDef, rid); if (hr == S_OK) { REPORT_ERROR1(VLDTR_E_TD_DUPNAME, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (hr == CLDB_E_RECORD_NOTFOUND) hr = S_OK; else IfFailGo(hr); ULONG L = (ULONG)(strlen(szName)+strlen(szNameSpace)); if(L >= MAX_CLASSNAME_LENGTH) { REPORT_ERROR2(VLDTR_E_TD_NAMETOOLONG, L, (ULONG)(MAX_CLASSNAME_LENGTH-1)); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // Get the flag value for the TypeDef. dwFlags = pMiniMd->getFlagsOfTypeDef(pRecord); // Do semantic checks on the flags. // RTSpecialName bit must be set on Deleted records. if (IsDeletedName(szName)) { if(!IsTdRTSpecialName(dwFlags)) { REPORT_ERROR0(VLDTR_E_TD_DLTNORTSPCL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } hr = hrSave; goto ErrExit; } // If RTSpecialName bit is set, the record must be a Deleted record. if (IsTdRTSpecialName(dwFlags)) { REPORT_ERROR0(VLDTR_E_TD_RTSPCLNOTDLT); SetVldtrCode(&hrSave, VLDTR_S_ERR); if(!IsTdSpecialName(dwFlags)) { REPORT_ERROR0(VLDTR_E_TD_RTSPCLNOTSPCL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // Check if flag value is valid { DWORD dwInvalidMask, dwExtraBits; dwInvalidMask = (DWORD)~(tdVisibilityMask | tdLayoutMask | tdClassSemanticsMask | tdAbstract | tdSealed | tdSpecialName | tdImport | tdSerializable | tdWindowsRuntime | tdStringFormatMask | tdBeforeFieldInit | tdReservedMask); // check for extra bits dwExtraBits = dwFlags & dwInvalidMask; if (dwExtraBits == 0) { // if no extra bits, check layout dwExtraBits = dwFlags & tdLayoutMask; if (dwExtraBits != tdLayoutMask) { // layout OK, check string format dwExtraBits = dwFlags & tdStringFormatMask; if (dwExtraBits != tdStringFormatMask) dwExtraBits = 0; } } if (dwExtraBits != 0) { REPORT_ERROR1(VLDTR_E_TD_EXTRAFLAGS, dwExtraBits); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Generic types may be specified to have only AutoLayout or SequentialLayout (never ExplicitLayout). if (IsTdExplicitLayout(dwFlags)) { HENUMInternal hEnumTyPars; ULONG ulTypeDefArity; hr = pMiniMd->FindGenericParamHelper(TokenFromRid(rid, mdtTypeDef), &hEnumTyPars); if (SUCCEEDED(hr)) { IfFailGo(HENUMInternal::GetCount(&hEnumTyPars,&ulTypeDefArity)); HENUMInternal::ClearEnum(&hEnumTyPars); if (ulTypeDefArity != 0) { REPORT_ERROR0(VLDTR_E_TD_GENERICHASEXPLAYOUT); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } } // Get the parent of the TypeDef. tkExtends = pMiniMd->getExtendsOfTypeDef(pRecord); // Check if TypeDef extends itself if (tkExtends == veCtxt.Token) { REPORT_ERROR0(VLDTR_E_TD_EXTENDSITSELF); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Check if TypeDef extends one of its children if (RidFromToken(tkExtends)&&(TypeFromToken(tkExtends)==mdtTypeDef)) { TypeDefRec *pRec; IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkExtends), &pRec)); mdToken tkExtends2 = pMiniMd->getExtendsOfTypeDef(pRec); if( tkExtends2 == veCtxt.Token) { REPORT_ERROR0(VLDTR_E_TD_EXTENDSCHILD); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } if (IsNilToken(tkEncloser) == IsTdNested(dwFlags)) { REPORT_ERROR0(IsNilToken(tkEncloser) ? VLDTR_E_TD_NESTEDNOENCL : VLDTR_E_TD_ENCLNOTNESTED); SetVldtrCode(&hrSave, VLDTR_S_ERR); } bIsObject = bIsEnum = bIsVType = FALSE; if(0 == strcmp(szNameSpace,BASE_NAMESPACE)) { bIsObject = (0 == strcmp(szName,BASE_OBJECT_CLASSNAME)); if(!bIsObject) { bIsEnum = (0 == strcmp(szName,BASE_ENUM_CLASSNAME)); if(!bIsEnum) { bIsVType = (0 == strcmp(szName,BASE_VTYPE_CLASSNAME)); } } } if (IsNilToken(tkExtends)) { // If the parent token is nil, the class must be marked Interface, // unless it's the System.Object class. if ( !(bIsObject || IsTdInterface(dwFlags))) { REPORT_ERROR0(VLDTR_E_TD_NOTIFACEOBJEXTNULL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } szExtName = ""; szExtNameSpace = ""; } else { // If tkExtends is a TypeSpec, extract the generic type and continue if (TypeFromToken(tkExtends) == mdtTypeSpec) { //@GENERICSVER: TODO first validate the spec TypeSpecRec *pRec; IfFailGo(pMiniMd->GetTypeSpecRecord(RidFromToken(tkExtends), &pRec)); PCCOR_SIGNATURE pSig; ULONG cSig; IfFailGo(pMiniMd->getSignatureOfTypeSpec(pRec, &pSig, &cSig)); switch(CorSigUncompressElementType(pSig)) { default: { REPORT_ERROR1(VLDTR_E_TD_EXTBADTYPESPEC, tkExtends); SetVldtrCode(&hrSave, VLDTR_S_ERR); szExtName = ""; szExtNameSpace = ""; break; } case ELEMENT_TYPE_GENERICINST: { switch(CorSigUncompressElementType(pSig)) { default: { REPORT_ERROR1(VLDTR_E_TD_EXTBADTYPESPEC, tkExtends); SetVldtrCode(&hrSave, VLDTR_S_ERR); szExtName = ""; szExtNameSpace = ""; break; } case ELEMENT_TYPE_VALUETYPE: case ELEMENT_TYPE_CLASS: { tkExtends = CorSigUncompressToken(pSig); break; } } } } } // If tkExtends is a TypeRef try to resolve it to a corresponding // TypeDef. If it resolves successfully, issue a warning. It means // that the Ref to Def optimization didn't happen successfully. if (TypeFromToken(tkExtends) == mdtTypeRef) { TypeRefRec *pTypeRefRec; IfFailGo(pMiniMd->GetTypeRefRecord(RidFromToken(tkExtends), &pTypeRefRec)); IfFailGo(pMiniMd->getNameOfTypeRef(pTypeRefRec, &szExtName)); IfFailGo(pMiniMd->getNamespaceOfTypeRef(pTypeRefRec, &szExtNameSpace)); BOOL fLookForDef = TRUE; mdToken tkResScope = pMiniMd->getResolutionScopeOfTypeRef(pTypeRefRec); if (TypeFromToken(tkResScope) == mdtAssemblyRef) { // We will look for the TypeDef of the same name, only if the AssemblyRef has the same name as AssemblyDef fLookForDef = FALSE; RID ridResScope = RidFromToken(tkResScope); if ((ridResScope > 0) && (ridResScope <= pMiniMd->GetCountRecs(TBL_AssemblyRef))) { if (pMiniMd->GetCountRecs(TBL_Assembly) > 0) { AssemblyRefRec * pAsmRefRec; IfFailGo(pMiniMd->GetAssemblyRefRecord(ridResScope, &pAsmRefRec)); AssemblyRec *pAsmRec; IfFailGo(pMiniMd->GetAssemblyRecord(1, &pAsmRec)); if ((pAsmRec != NULL) && (pAsmRefRec != NULL)) { LPCUTF8 szAsmName; IfFailGo(pMiniMd->getNameOfAssembly(pAsmRec, &szAsmName)); LPCUTF8 szAsmRefName; IfFailGo(pMiniMd->getNameOfAssemblyRef(pAsmRefRec, &szAsmRefName)); if ((szAsmName != NULL) && (szAsmRefName != NULL)) fLookForDef = (strcmp(szAsmName,szAsmRefName) == 0); } } } } if (fLookForDef) { mdTypeDef tkResTd; if (ImportHelper::FindTypeDefByName(pMiniMd, szExtNameSpace, szExtName, tkResScope, &tkResTd) == S_OK) { // Ref to Def optimization is not expected to happen for Obj files. /* if (m_ModuleType != ValidatorModuleTypeObj) { REPORT_ERROR2(VLDTR_E_TD_EXTTRRES, tkExtends, tkResTd); SetVldtrCode(&hrSave, VLDTR_S_WRN); } */ // Set tkExtends to the new TypeDef, so we can continue // with the validation. tkExtends = tkResTd; } } } // Continue validation, even for the case where TypeRef got resolved // to a corresponding TypeDef in the same Module. if (TypeFromToken(tkExtends) == mdtTypeDef) { // Extends must not be sealed. IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkExtends), &pExtendsRec)); dwExtendsFlags = pMiniMd->getFlagsOfTypeDef(pExtendsRec); IfFailGo(pMiniMd->getNameOfTypeDef(pExtendsRec, &szExtName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pExtendsRec, &szExtNameSpace)); if (IsTdSealed(dwExtendsFlags)) { REPORT_ERROR1(VLDTR_E_TD_EXTENDSSEALED, tkExtends); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if (IsTdInterface(dwExtendsFlags)) { REPORT_ERROR1(VLDTR_E_TD_EXTENDSIFACE, tkExtends); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } else if(TypeFromToken(tkExtends) == mdtTypeSpec) { //If we got here, the instantiated generic type is itself a type spec, which is illegal REPORT_ERROR1(VLDTR_E_TD_EXTBADTYPESPEC, tkExtends); SetVldtrCode(&hrSave, VLDTR_S_ERR); szExtName = ""; szExtNameSpace = ""; } // If the parent token is non-null, the class must not be System.Object. if (bIsObject) { REPORT_ERROR1(VLDTR_E_TD_OBJEXTENDSNONNULL, tkExtends); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } bExtendsObject = bExtendsEnum = bExtendsVType = bExtendsMCDelegate = FALSE; if(0 == strcmp(szExtNameSpace,BASE_NAMESPACE)) { bExtendsObject = (0 == strcmp(szExtName,BASE_OBJECT_CLASSNAME)); if(!bExtendsObject) { bExtendsEnum = (0 == strcmp(szExtName,BASE_ENUM_CLASSNAME)); if(!bExtendsEnum) { bExtendsVType = (0 == strcmp(szExtName,BASE_VTYPE_CLASSNAME)); if(!bExtendsVType) { bExtendsMCDelegate = (0 == strcmp(szExtName,BASE_MCDELEGATE_CLASSNAME)); } } } } // System.ValueType must extend System.Object if(bIsVType && !bExtendsObject) { REPORT_ERROR0(VLDTR_E_TD_SYSVTNOTEXTOBJ); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Validate rules for interface. Some of the VOS rules are verified as // part of the validation for the corresponding Methods, fields etc. if (IsTdInterface(dwFlags)) { // Interface type must be marked abstract. if (!IsTdAbstract(dwFlags)) { REPORT_ERROR0(VLDTR_E_TD_IFACENOTABS); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Interface must not be sealed if(IsTdSealed(dwFlags)) { REPORT_ERROR0(VLDTR_E_TD_IFACESEALED); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Interface must have parent Nil token. if (!IsNilToken(tkExtends)) { REPORT_ERROR1(VLDTR_E_TD_IFACEPARNOTNIL, tkExtends); SetVldtrCode(&hrSave, VLDTR_S_ERR); } //Interface must have only static fields -- checked in ValidateField //Interface must have only public fields -- checked in ValidateField //Interface must have only abstract or static methods -- checked in ValidateMethod //Interface must have only public methods -- checked in ValidateMethod // Interface must have GUID /* if (*pGuid == GUID_NULL) { REPORT_ERROR0(VLDTR_E_TD_IFACEGUIDNULL); SetVldtrCode(&hrSave, VLDTR_S_WRN); } */ } // Class must have valid method and field lists { ULONG ridStart,ridEnd; ridStart = pMiniMd->getMethodListOfTypeDef(pRecord); ridEnd = pMiniMd->getCountMethods() + 1; if(ridStart > ridEnd) { REPORT_ERROR0(VLDTR_E_TD_BADMETHODLST); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { IfFailGo(pMiniMd->getEndMethodListOfTypeDef(rid, &ridEnd)); bHasMethods = (ridStart && (ridStart < ridEnd)); } ridStart = pMiniMd->getFieldListOfTypeDef(pRecord); ridEnd = pMiniMd->getCountFields() + 1; if(ridStart > ridEnd) { REPORT_ERROR0(VLDTR_E_TD_BADFIELDLST); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { IfFailGo(pMiniMd->getEndFieldListOfTypeDef(rid, &ridEnd)); bHasFields = (ridStart && (ridStart < ridEnd)); } } // Validate rules for System.Enum if(bIsEnum) { if(!IsTdClass(dwFlags)) { REPORT_ERROR0(VLDTR_E_TD_SYSENUMNOTCLASS); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if(!bExtendsVType) { REPORT_ERROR0(VLDTR_E_TD_SYSENUMNOTEXTVTYPE); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } else { if(bExtendsVType || bExtendsEnum) { // ValueTypes and Enums must be sealed if(!IsTdSealed(dwFlags)) { REPORT_ERROR0(VLDTR_E_TD_VTNOTSEAL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Value class must have fields or size if(!bHasFields) { ULONG ulClassSize = 0; ClassLayoutRec *pRec; RID ridClassLayout; IfFailGo(pMiniMd->FindClassLayoutHelper(TokenFromRid(rid, mdtTypeDef), &ridClassLayout)); if (!InvalidRid(ridClassLayout)) { IfFailGo(pMiniMd->GetClassLayoutRecord(RidFromToken(ridClassLayout), &pRec)); ulClassSize = pMiniMd->getClassSizeOfClassLayout(pRec); } if(ulClassSize == 0) { REPORT_ERROR0(VLDTR_E_TD_VTNOSIZE); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } else if(bExtendsMCDelegate) { // Delegates must be sealed if(!IsTdSealed(dwFlags)) { REPORT_ERROR0(VLDTR_E_TD_VTNOTSEAL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } // Enum-related checks if (bExtendsEnum) { { PCCOR_SIGNATURE pValueSig = NULL; ULONG cbValueSig = 0; mdFieldDef tkValueField=0, tkField, tkValue__Field = 0; ULONG ridStart,ridEnd,index; FieldRec *pFieldRecord; // Field record. DWORD dwRecordFlags, dwTally, dwValueFlags, dwValue__Flags = 0; RID ridField,ridValue=0,ridValue__ = 0; ridStart = pMiniMd->getFieldListOfTypeDef(pRecord); IfFailGo(pMiniMd->getEndFieldListOfTypeDef(rid, &ridEnd)); // check the instance (value__) field(s) dwTally = 0; for (index = ridStart; index < ridEnd; index++ ) { IfFailGo(pMiniMd->GetFieldRid(index, &ridField)); IfFailGo(pMiniMd->GetFieldRecord(ridField, &pFieldRecord)); dwRecordFlags = pFieldRecord->GetFlags(); if(!IsFdStatic(dwRecordFlags)) { dwTally++; if(ridValue == 0) { ridValue = ridField; tkValueField = TokenFromRid(ridField, mdtFieldDef); IfFailGo(pMiniMd->getSignatureOfField(pFieldRecord, &pValueSig, &cbValueSig)); dwValueFlags = dwRecordFlags; } } LPCSTR szFieldName; IfFailGo(pMiniMd->getNameOfField(pFieldRecord, &szFieldName)); if(!strcmp(szFieldName, BASE_VALUE_FIELDNAME)) { ridValue__ = ridField; dwValue__Flags = dwRecordFlags; tkValue__Field = TokenFromRid(ridField, mdtFieldDef); } } // Enum must have one (and only one) inst.field if(dwTally == 0) { REPORT_ERROR0(VLDTR_E_TD_ENUMNOINSTFLD); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if(dwTally > 1) { REPORT_ERROR0(VLDTR_E_TD_ENUMMULINSTFLD); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // inst.field name must be "value__" (CLS) if(ridValue__ == 0) { REPORT_ERROR0(VLDTR_E_TD_ENUMNOVALUE); SetVldtrCode(&hrSave, VLDTR_S_WRN); } else { // if "value__" field is present ... // ... it must be 1st instance field if(ridValue__ != ridValue) { REPORT_ERROR1(VLDTR_E_TD_ENUMVALNOT1ST, tkValue__Field); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // ... it must not be static if(IsFdStatic(dwValue__Flags)) { REPORT_ERROR1(VLDTR_E_TD_ENUMVALSTATIC, tkValue__Field); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // ... it must be fdRTSpecialName if(!IsFdRTSpecialName(dwValue__Flags)) { REPORT_ERROR1(VLDTR_E_TD_ENUMVALNOTSN, tkValueField); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // ... its type must be integral if(cbValueSig && pValueSig) { //ULONG ulCurByte = CorSigUncompressedDataSize(pValueSig); //CorSigUncompressData(pValueSig); //ULONG ulElemSize,ulElementType; //ulCurByte += (ulElemSize = CorSigUncompressedDataSize(pValueSig)); //ulElementType = CorSigUncompressData(pValueSig); //switch (ulElementType) BYTE* pB = (BYTE*)pValueSig; pB++; // skip the calling convention while((*pB == ELEMENT_TYPE_CMOD_OPT)|| (*pB == ELEMENT_TYPE_CMOD_REQD)) { mdToken tok; pB++; // move from E_T_... to compressed token pB += CorSigUncompressToken((PCOR_SIGNATURE)pB,&tok); } switch(*pB) { case ELEMENT_TYPE_BOOLEAN: case ELEMENT_TYPE_CHAR: case ELEMENT_TYPE_I1: case ELEMENT_TYPE_U1: case ELEMENT_TYPE_I2: case ELEMENT_TYPE_U2: case ELEMENT_TYPE_I4: case ELEMENT_TYPE_U4: case ELEMENT_TYPE_I8: case ELEMENT_TYPE_U8: case ELEMENT_TYPE_U: case ELEMENT_TYPE_I: case ELEMENT_TYPE_R4: case ELEMENT_TYPE_R8: break; default: REPORT_ERROR1(VLDTR_E_TD_ENUMFLDBADTYPE, tkValue__Field); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } // check all the fields dwTally = 0; for (index = ridStart; index < ridEnd; index++ ) { IfFailGo(pMiniMd->GetFieldRid(index, &ridField)); if(ridField == ridValue) continue; IfFailGo(pMiniMd->GetFieldRecord(ridField, &pFieldRecord)); LPCSTR szFieldName; IfFailGo(pMiniMd->getNameOfField(pFieldRecord, &szFieldName)); if(IsFdRTSpecialName(pFieldRecord->GetFlags()) && IsDeletedName(szFieldName)) continue; dwTally++; tkField = TokenFromRid(ridField, mdtFieldDef); if(!IsFdStatic(pFieldRecord->GetFlags())) { REPORT_ERROR1(VLDTR_E_TD_ENUMFLDNOTST, tkField); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if(!IsFdLiteral(pFieldRecord->GetFlags())) { REPORT_ERROR1(VLDTR_E_TD_ENUMFLDNOTLIT, tkField); SetVldtrCode(&hrSave, VLDTR_S_ERR); } /* IfFailGo(pMiniMd->getSignatureOfField(pFieldRecord, &pvSigTmp, &cbSig)); if(!(pvSigTmp && (cbSig==cbValueSig) &&(memcmp(pvSigTmp,pValueSig,cbSig)==0))) { REPORT_ERROR1(VLDTR_E_TD_ENUMFLDSIGMISMATCH, tkField); SetVldtrCode(&hrSave, VLDTR_S_ERR); } */ } if(dwTally == 0) { REPORT_ERROR0(VLDTR_E_TD_ENUMNOLITFLDS); SetVldtrCode(&hrSave, VLDTR_S_WRN); } } // Enum must have no methods if (bHasMethods) { REPORT_ERROR0(VLDTR_E_TD_ENUMHASMETHODS); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Enum must implement no interfaces { ULONG ridStart = 1; ULONG ridEnd = pMiniMd->getCountInterfaceImpls() + 1; ULONG index; for (index = ridStart; index < ridEnd; index ++ ) { InterfaceImplRec *pInterfaceImplRecord; IfFailGo(pMiniMd->GetInterfaceImplRecord(index, &pInterfaceImplRecord)); if (veCtxt.Token == pMiniMd->getClassOfInterfaceImpl(pInterfaceImplRecord)) { REPORT_ERROR0(VLDTR_E_TD_ENUMIMPLIFACE); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } } } // Enum must have no properties { ULONG ridStart = 1; ULONG ridEnd = pMiniMd->getCountPropertys() + 1; ULONG index; mdToken tkClass; for (index = ridStart; index < ridEnd; index ++ ) { IfFailGo(pMiniMd->FindParentOfPropertyHelper(index | mdtProperty, &tkClass)); if (veCtxt.Token == tkClass) { REPORT_ERROR0(VLDTR_E_TD_ENUMHASPROP); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } } } // Enum must have no events { ULONG ridStart = 1; ULONG ridEnd = pMiniMd->getCountEvents() + 1; ULONG index; mdToken tkClass; for (index = ridStart; index < ridEnd; index ++ ) { IfFailGo(pMiniMd->FindParentOfEventHelper(index | mdtEvent, &tkClass)); if (veCtxt.Token == tkClass) { REPORT_ERROR0(VLDTR_E_TD_ENUMHASEVENT); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } } } } // end if(bExtendsEnum) // Class having security must be marked tdHasSecurity and vice versa { ULONG ridStart = 1; ULONG ridEnd = pMiniMd->getCountDeclSecuritys() + 1; ULONG index; BOOL bHasSecurity = FALSE; for (index = ridStart; index < ridEnd; index ++ ) { DeclSecurityRec *pDeclSecurityRecord; IfFailGo(pMiniMd->GetDeclSecurityRecord(index, &pDeclSecurityRecord)); if (veCtxt.Token == pMiniMd->getParentOfDeclSecurity(pDeclSecurityRecord)) { bHasSecurity = TRUE; break; } } if (!bHasSecurity) // No records, check for CA "SuppressUnmanagedCodeSecurityAttribute" { bHasSecurity = (S_OK == ImportHelper::GetCustomAttributeByName(pMiniMd, veCtxt.Token, "System.Security.SuppressUnmanagedCodeSecurityAttribute", NULL, NULL)); } if(bHasSecurity != (IsTdHasSecurity(pRecord->GetFlags())!=0)) { REPORT_ERROR0(bHasSecurity ? VLDTR_E_TD_SECURNOTMARKED : VLDTR_E_TD_MARKEDNOSECUR); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateTypeDef() #ifdef _PREFAST_ #pragma warning(pop) #endif //***************************************************************************** // Validate the given FieldPtr. //***************************************************************************** HRESULT RegMeta::ValidateFieldPtr(RID rid) { return S_OK; } // RegMeta::ValidateFieldPtr() //***************************************************************************** // Validate the given Field. //***************************************************************************** HRESULT RegMeta::ValidateField(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. FieldRec *pRecord; // Field record. mdTypeDef tkTypeDef; // Parent TypeDef token. mdFieldDef tkFieldDef; // Duplicate FieldDef token. LPCSTR szName; // FieldDef name. PCCOR_SIGNATURE pbSig; // FieldDef signature. ULONG cbSig; // Signature size in bytes. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BOOL bIsValueField; BOOL bIsGlobalField = FALSE; BOOL bHasValidRVA = FALSE; DWORD dwInvalidFlags; DWORD dwFlags; RID tempRid; BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Get the FieldDef record. veCtxt.Token = TokenFromRid(rid, mdtFieldDef); veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetFieldRecord(rid, &pRecord)); // Do checks for name validity. IfFailGo(pMiniMd->getNameOfField(pRecord, &szName)); if (!*szName) { // Field name is NULL. REPORT_ERROR0(VLDTR_E_FD_NAMENULL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { if(!strcmp(szName,COR_DELETED_NAME_A)) goto ErrExit; ULONG L = (ULONG)strlen(szName); if(L >= MAX_CLASSNAME_LENGTH) { REPORT_ERROR2(VLDTR_E_TD_NAMETOOLONG, L, (ULONG)(MAX_CLASSNAME_LENGTH-1)); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } bIsValueField = (strcmp(szName,BASE_VALUE_FIELDNAME)==0); // If field is RTSpecialName, its name must be 'value__' and vice versa if((IsFdRTSpecialName(pRecord->GetFlags())!=0) != bIsValueField) { REPORT_ERROR1(bIsValueField ? VLDTR_E_TD_ENUMVALNOTSN : VLDTR_E_FD_NOTVALUERTSN, veCtxt.Token); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Validate flags dwFlags = pRecord->GetFlags(); dwInvalidFlags = ~(fdFieldAccessMask | fdStatic | fdInitOnly | fdLiteral | fdNotSerialized | fdSpecialName | fdPinvokeImpl | fdReservedMask); if(dwFlags & dwInvalidFlags) { REPORT_ERROR1(VLDTR_E_TD_EXTRAFLAGS, dwFlags & dwInvalidFlags); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Validate access if((dwFlags & fdFieldAccessMask) == fdFieldAccessMask) { REPORT_ERROR0(VLDTR_E_FMD_BADACCESSFLAG); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Literal : Static, !InitOnly if(IsFdLiteral(dwFlags)) { if(IsFdInitOnly(dwFlags)) { REPORT_ERROR0(VLDTR_E_FD_INITONLYANDLITERAL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if(!IsFdStatic(dwFlags)) { REPORT_ERROR0(VLDTR_E_FD_LITERALNOTSTATIC); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if(!IsFdHasDefault(dwFlags)) { REPORT_ERROR0(VLDTR_E_FD_LITERALNODEFAULT); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // RTSpecialName => SpecialName if(IsFdRTSpecialName(dwFlags) && !IsFdSpecialName(dwFlags)) { REPORT_ERROR0(VLDTR_E_FMD_RTSNNOTSN); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Validate Field signature. IfFailGo(pMiniMd->getSignatureOfField(pRecord, &pbSig, &cbSig)); IfFailGo(ValidateFieldSig(TokenFromRid(rid, mdtFieldDef), pbSig, cbSig)); if (hr != S_OK) SetVldtrCode(&hrSave, hr); // Validate Field RVA if(IsFdHasFieldRVA(dwFlags)) { ULONG iFieldRVARid; IfFailGo(pMiniMd->FindFieldRVAHelper(TokenFromRid(rid, mdtFieldDef), &iFieldRVARid)); if((iFieldRVARid==0) || (iFieldRVARid > pMiniMd->getCountFieldRVAs())) { REPORT_ERROR0(VLDTR_E_FD_RVAHASNORVA); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { /* FieldRVARec *pRVARec; IfFailGo(pMiniMd->GetFieldRVARecord(iFieldRVARid, &pRVARec)); if(pRVARec->GetRVA() == 0) { REPORT_ERROR0(VLDTR_E_FD_RVAHASZERORVA); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else */ bHasValidRVA = TRUE; } } // Get the parent of the Field. IfFailGo(pMiniMd->FindParentOfFieldHelper(TokenFromRid(rid, mdtFieldDef), &tkTypeDef)); // Validate that the parent is not nil. if (IsNilToken(tkTypeDef)) { REPORT_ERROR0(VLDTR_E_FD_PARNIL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (RidFromToken(tkTypeDef) != RidFromToken(m_tdModule)) { if(IsValidToken(tkTypeDef) && (TypeFromToken(tkTypeDef) == mdtTypeDef)) { TypeDefRec *pParentRec; IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkTypeDef), &pParentRec)); // If the name is "value__" ... if(bIsValueField) { // parent must be Enum mdToken tkExtends = pMiniMd->getExtendsOfTypeDef(pParentRec); RID ridExtends = RidFromToken(tkExtends); LPCSTR szExtName="",szExtNameSpace=""; if(ridExtends) { if(TypeFromToken(tkExtends) == mdtTypeRef) { TypeRefRec *pExtRec; IfFailGo(pMiniMd->GetTypeRefRecord(ridExtends, &pExtRec)); IfFailGo(pMiniMd->getNameOfTypeRef(pExtRec, &szExtName)); IfFailGo(pMiniMd->getNamespaceOfTypeRef(pExtRec, &szExtNameSpace)); } else if(TypeFromToken(tkExtends) == mdtTypeDef) { TypeDefRec *pExtRec; IfFailGo(pMiniMd->GetTypeDefRecord(ridExtends, &pExtRec)); IfFailGo(pMiniMd->getNameOfTypeDef(pExtRec, &szExtName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pExtRec, &szExtNameSpace)); } } if(strcmp(szExtName,BASE_ENUM_CLASSNAME) || strcmp(szExtNameSpace,BASE_NAMESPACE)) { REPORT_ERROR0(VLDTR_E_FD_VALUEPARNOTENUM); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // field must be instance - checked in ValidateTypeDef // must be no other instance fields - checked in ValidateTypeDef // must be first field - checked in ValidateTypeDef // must be RTSpecialName -- checked in ValidateTypeDef } if(IsTdInterface(pMiniMd->getFlagsOfTypeDef(pParentRec))) { // Fields in interface are not CLS compliant REPORT_ERROR0(VLDTR_E_FD_FLDINIFACE); SetVldtrCode(&hrSave, VLDTR_S_WRN); // If field is not static, verify parent is not interface. if(!IsFdStatic(dwFlags)) { REPORT_ERROR0(VLDTR_E_FD_INSTINIFACE); SetVldtrCode(&hrSave, VLDTR_S_ERR); // If field is not public, verify parent is not interface. if(!IsFdPublic(dwFlags)) { REPORT_ERROR0(VLDTR_E_FD_NOTPUBINIFACE); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } } // end if Valid and TypeDef else { REPORT_ERROR1(VLDTR_E_FD_BADPARENT, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } else // i.e. if (RidFromToken(tkTypeDef) == RidFromToken(m_tdModule)) { bIsGlobalField = TRUE; // Globals are not CLS-compliant REPORT_ERROR0(VLDTR_E_FMD_GLOBALITEM); SetVldtrCode(&hrSave, VLDTR_S_WRN); // Validate global field: // Must be static if(!IsFdStatic(dwFlags)) { REPORT_ERROR0(VLDTR_E_FMD_GLOBALNOTSTATIC); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Must have a non-zero RVA /* if(!bHasValidRVA) { REPORT_ERROR0(VLDTR_E_FD_GLOBALNORVA); SetVldtrCode(&hrSave, VLDTR_S_ERR); } */ } // Check for duplicates, except global fields with PrivateScope. if (*szName && cbSig && !IsFdPrivateScope(dwFlags)) { hr = ImportHelper::FindField(pMiniMd, tkTypeDef, szName, pbSig, cbSig, &tkFieldDef, rid); if (hr == S_OK) { if(!IsFdPrivateScope(dwFlags)) { REPORT_ERROR1(VLDTR_E_FD_DUP, tkFieldDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else hr = S_OK; } else if (hr == CLDB_E_RECORD_NOTFOUND) { hr = S_OK; } else { IfFailGo(hr); } } // Field having security must be marked fdHasSecurity and vice versa { ULONG ridStart = 1; ULONG ridEnd = pMiniMd->getCountDeclSecuritys() + 1; ULONG index; BOOL bHasSecurity = FALSE; for (index = ridStart; index < ridEnd; index ++ ) { DeclSecurityRec *pDeclSecurityRecord; IfFailGo(pMiniMd->GetDeclSecurityRecord(index, &pDeclSecurityRecord)); if ( veCtxt.Token == pMiniMd->getParentOfDeclSecurity(pDeclSecurityRecord)) { bHasSecurity = TRUE; break; } } if(!bHasSecurity) // No records, check for CA "SuppressUnmanagedCodeSecurityAttribute" { bHasSecurity = (S_OK == ImportHelper::GetCustomAttributeByName(pMiniMd, veCtxt.Token, "System.Security.SuppressUnmanagedCodeSecurityAttribute", NULL, NULL)); } if(bHasSecurity) { REPORT_ERROR0(VLDTR_E_FMD_SECURNOTMARKED); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // Field having marshaling must be marked fdHasFieldMarshal and vice versa IfFailGo(pMiniMd->FindFieldMarshalHelper(veCtxt.Token, &tempRid)); if (InvalidRid(tempRid) == (IsFdHasFieldMarshal(dwFlags) != 0)) { REPORT_ERROR0(IsFdHasFieldMarshal(dwFlags)? VLDTR_E_FD_MARKEDNOMARSHAL : VLDTR_E_FD_MARSHALNOTMARKED); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Field having const value must be marked fdHasDefault and vice versa IfFailGo(pMiniMd->FindConstantHelper(veCtxt.Token, &tempRid)); if(InvalidRid(tempRid) == (IsFdHasDefault(dwFlags) != 0)) { REPORT_ERROR0(IsFdHasDefault(dwFlags)? VLDTR_E_FD_MARKEDNODEFLT : VLDTR_E_FD_DEFLTNOTMARKED); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Check the field's impl.map { ULONG iRecord; IfFailGo(pMiniMd->FindImplMapHelper(veCtxt.Token, &iRecord)); if(IsFdPinvokeImpl(dwFlags)) { // must be static if(!IsFdStatic(dwFlags)) { REPORT_ERROR0(VLDTR_E_FMD_PINVOKENOTSTATIC); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // must have ImplMap if (InvalidRid(iRecord)) { REPORT_ERROR0(VLDTR_E_FMD_MARKEDNOPINVOKE); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } else { // must have no ImplMap if (!InvalidRid(iRecord)) { REPORT_ERROR0(VLDTR_E_FMD_PINVOKENOTMARKED); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } if (!InvalidRid(iRecord)) { hr = ValidateImplMap(iRecord); if(hr != S_OK) { REPORT_ERROR0(VLDTR_E_FMD_BADIMPLMAP); SetVldtrCode(&hrSave, VLDTR_S_WRN); } } } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateField() //***************************************************************************** // Validate the given MethodPtr. //***************************************************************************** HRESULT RegMeta::ValidateMethodPtr(RID rid) { return S_OK; } // RegMeta::ValidateMethodPtr() //***************************************************************************** // Validate the given Method. //***************************************************************************** #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:21000) // Suppress PREFast warning about overly large function #endif HRESULT RegMeta::ValidateMethod(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. MethodRec *pRecord = NULL; // Method record. mdTypeDef tkTypeDef; // Parent TypeDef token. mdMethodDef tkMethodDef; // Duplicate MethodDef token. LPCSTR szName; // MethodDef name. DWORD dwFlags = 0; // Method flags. DWORD dwImplFlags = 0; // Method impl.flags. PCCOR_SIGNATURE pbSig; // MethodDef signature. ULONG cbSig; // Signature size in bytes. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BOOL bIsCtor=FALSE; BOOL bIsCctor=FALSE; BOOL bIsGlobal=FALSE; BOOL bIsParentImport = FALSE; BOOL bIsGeneric = FALSE; unsigned retType; BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Get the MethodDef record. veCtxt.Token = TokenFromRid(rid, mdtMethodDef); veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetMethodRecord(rid, &pRecord)); // Do checks for name validity. IfFailGo(pMiniMd->getNameOfMethod(pRecord, &szName)); if (!*szName) { // Method name is NULL. REPORT_ERROR0(VLDTR_E_MD_NAMENULL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { if(!strcmp(szName,COR_DELETED_NAME_A)) goto ErrExit; bIsCtor = (0 == strcmp(szName,BASE_CTOR_NAME)); bIsCctor = (0 == strcmp(szName,BASE_CCTOR_NAME)); ULONG L = (ULONG)strlen(szName); if(L >= MAX_CLASSNAME_LENGTH) { REPORT_ERROR2(VLDTR_E_TD_NAMETOOLONG, L, (ULONG)(MAX_CLASSNAME_LENGTH-1)); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // Get the parent, flags and signature of the Method. IfFailGo(pMiniMd->FindParentOfMethodHelper(TokenFromRid(rid, mdtMethodDef), &tkTypeDef)); dwFlags = pMiniMd->getFlagsOfMethod(pRecord); dwImplFlags = pMiniMd->getImplFlagsOfMethod(pRecord); IfFailGo(pMiniMd->getSignatureOfMethod(pRecord, &pbSig, &cbSig)); // Check for duplicates. if (*szName && cbSig && !IsNilToken(tkTypeDef) && !IsMdPrivateScope(dwFlags)) { hr = ImportHelper::FindMethod(pMiniMd, tkTypeDef, szName, pbSig, cbSig, &tkMethodDef, rid); if (hr == S_OK) { REPORT_ERROR1(VLDTR_E_MD_DUP, tkMethodDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (hr == CLDB_E_RECORD_NOTFOUND) hr = S_OK; else IfFailGo(hr); } // No further error checking for VtblGap methods. if (IsVtblGapName(szName)) { hr = hrSave; goto ErrExit; } // Validate Method signature. IfFailGo(ValidateMethodSig(TokenFromRid(rid, mdtMethodDef), pbSig, cbSig, dwFlags)); if (hr != S_OK) SetVldtrCode(&hrSave, hr); // Validate that the parent is not nil. if (IsNilToken(tkTypeDef)) { REPORT_ERROR0(VLDTR_E_MD_PARNIL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (RidFromToken(tkTypeDef) != RidFromToken(m_tdModule)) { if(TypeFromToken(tkTypeDef) == mdtTypeDef) { TypeDefRec *pTDRec; IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkTypeDef), &pTDRec)); DWORD dwTDFlags = pTDRec->GetFlags(); LPCSTR szTDName; IfFailGo(pMiniMd->getNameOfTypeDef(pTDRec, &szTDName)); LPCSTR szTDNameSpace; IfFailGo(pMiniMd->getNamespaceOfTypeDef(pTDRec, &szTDNameSpace)); BOOL fIsTdValue=FALSE, fIsTdEnum=FALSE; mdToken tkExtends = pMiniMd->getExtendsOfTypeDef(pTDRec); if(0 == strcmp(szTDNameSpace,BASE_NAMESPACE)) { fIsTdEnum = (0 == strcmp(szTDName,BASE_ENUM_CLASSNAME)); if(!fIsTdEnum) { fIsTdValue = (0 == strcmp(szTDName,BASE_VTYPE_CLASSNAME)); } } if(fIsTdEnum || fIsTdValue) { fIsTdEnum = fIsTdValue = FALSE; // System.Enum and System.ValueType themselves are classes } else if(RidFromToken(tkExtends)) { if(TypeFromToken(tkExtends) == mdtTypeDef) { IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkExtends), &pTDRec)); IfFailGo(pMiniMd->getNameOfTypeDef(pTDRec, &szTDName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pTDRec, &szTDNameSpace)); } else if(TypeFromToken(tkExtends) == mdtTypeSpec) { fIsTdEnum = fIsTdValue = FALSE; // a type extending a spec cannot be an enum or value type // the assignments are redundant, but clear. } else { TypeRefRec *pTRRec; IfFailGo(pMiniMd->GetTypeRefRecord(RidFromToken(tkExtends), &pTRRec)); IfFailGo(pMiniMd->getNameOfTypeRef(pTRRec, &szTDName)); IfFailGo(pMiniMd->getNamespaceOfTypeRef(pTRRec, &szTDNameSpace)); } if(0 == strcmp(szTDNameSpace,BASE_NAMESPACE)) { fIsTdEnum = (0 == strcmp(szTDName,BASE_ENUM_CLASSNAME)); if(!fIsTdEnum) { fIsTdValue = (0 == strcmp(szTDName,BASE_VTYPE_CLASSNAME)); } else fIsTdValue = FALSE; } } // If Method is abstract, verify parent is abstract. if(IsMdAbstract(dwFlags) && !IsTdAbstract(dwTDFlags)) { REPORT_ERROR1(VLDTR_E_MD_ABSTPARNOTABST, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // If parent is import, method must have zero RVA, otherwise it depends... if(IsTdImport(dwTDFlags)) bIsParentImport = TRUE; if(IsTdInterface(dwTDFlags)) { if(!IsMdStatic(dwFlags)) { // No non-abstract instance methods in interface. if(!IsMdAbstract(dwFlags)) { REPORT_ERROR1(VLDTR_E_MD_NOTSTATABSTININTF, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // No non-public instance methods in interface. if(!IsMdPublic(dwFlags)) { REPORT_ERROR1(VLDTR_E_MD_NOTPUBININTF, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // If Method is constructor, verify parent is not interface. if(bIsCtor) { REPORT_ERROR1(VLDTR_E_MD_CTORININTF, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } }//end if(interface) if((fIsTdValue || fIsTdEnum) && IsMiSynchronized(dwImplFlags)) { REPORT_ERROR1(VLDTR_E_MD_SYNCMETHODINVTYPE, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if(bIsCtor) { // .ctor must be instance if(IsMdStatic(dwFlags)) { REPORT_ERROR1(VLDTR_E_MD_CTORSTATIC, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } }//end if .ctor else if(bIsCctor) { // .cctor must be static if(!IsMdStatic(dwFlags)) { REPORT_ERROR1(VLDTR_E_MD_CCTORNOTSTATIC, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // ..cctor must have default callconv IfFailGo(pMiniMd->getSignatureOfMethod(pRecord, &pbSig, &cbSig)); if(IMAGE_CEE_CS_CALLCONV_DEFAULT != CorSigUncompressData(pbSig)) { REPORT_ERROR0(VLDTR_E_MD_CCTORCALLCONV); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // .cctor must have no arguments if(0 != CorSigUncompressData(pbSig)) { REPORT_ERROR0(VLDTR_E_MD_CCTORHASARGS); SetVldtrCode(&hrSave, VLDTR_S_ERR); } }//end if .cctor if(bIsCtor || bIsCctor) { // .ctor, .cctor must be SpecialName and RTSpecialName if(!(IsMdSpecialName(dwFlags) && IsMdRTSpecialName(dwFlags))) { REPORT_ERROR1(VLDTR_E_MD_CTORNOTSNRTSN, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } #ifdef NO_SUCH_CHECKS_NEEDED_SPEC_TO_BE_UODATED // .ctor, .cctor must not be virtual if(IsMdVirtual(dwFlags)) { REPORT_ERROR1(VLDTR_E_MD_CTORVIRT, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // .ctor, .cctor must not be abstract if(IsMdAbstract(dwFlags)) { REPORT_ERROR1(VLDTR_E_MD_CTORABST, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // .ctor, .cctor must not be PInvoke if(IsMdPinvokeImpl(dwFlags)) { REPORT_ERROR1(VLDTR_E_MD_CTORPINVOKE, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // .ctor,.cctor must have RVA!=0 if(pRecord->GetRVA()==0) { REPORT_ERROR0(VLDTR_E_MD_CTORZERORVA); SetVldtrCode(&hrSave, VLDTR_S_ERR); } #endif }//end if .ctor or .cctor }// end if(parent == TypeDef) }// end if not Module else // i.e. if (RidFromToken(tkTypeDef) == RidFromToken(m_tdModule)) { bIsGlobal = TRUE; // Globals are not CLS-compliant REPORT_ERROR0(VLDTR_E_FMD_GLOBALITEM); SetVldtrCode(&hrSave, VLDTR_S_WRN); // Validate global method: // Must be static if(!IsMdStatic(dwFlags)) { REPORT_ERROR0(VLDTR_E_FMD_GLOBALNOTSTATIC); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Must not be abstract or virtual if(IsMdAbstract(dwFlags) || IsMdVirtual(dwFlags)) { REPORT_ERROR0(VLDTR_E_MD_GLOBALABSTORVIRT); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Must be not .ctor or .cctor if(bIsCtor) { REPORT_ERROR0(VLDTR_E_MD_GLOBALCTORCCTOR); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } //end if Module // Signature specifics: .ctor, .cctor, entrypoint if(bIsCtor || bIsCctor) { // .ctor, .cctor must return void IfFailGo(pMiniMd->getSignatureOfMethod(pRecord, &pbSig, &cbSig)); CorSigUncompressData(pbSig); // get call conv out of the way CorSigUncompressData(pbSig); // get num args out of the way while (((retType=CorSigUncompressData(pbSig)) == ELEMENT_TYPE_CMOD_OPT) || (retType == ELEMENT_TYPE_CMOD_REQD)) CorSigUncompressToken(pbSig); if(retType != ELEMENT_TYPE_VOID) { REPORT_ERROR0(VLDTR_E_MD_CTORNOTVOID); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } if(g_tkEntryPoint == veCtxt.Token) { ULONG ulCallConv; // EP must be static if(!IsMdStatic(dwFlags)) { REPORT_ERROR0(VLDTR_E_EP_INSTANCE); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // EP can't belong to generic class or nested in generic class mdToken tkTypeDefCur; for(tkTypeDefCur = tkTypeDef; tkTypeDefCur != mdTokenNil;) { HENUMInternal hEnumTyPars; ULONG ulTypeDefArity = 0; hr = pMiniMd->FindGenericParamHelper(tkTypeDefCur, &hEnumTyPars); if (SUCCEEDED(hr)) { IfFailGo(HENUMInternal::GetCount(&hEnumTyPars,&ulTypeDefArity)); HENUMInternal::ClearEnum(&hEnumTyPars); if (ulTypeDefArity != 0) { REPORT_ERROR0(VLDTR_E_EP_GENERIC_TYPE); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } if(ulTypeDefArity == 0) { // This class is not generic, how about the encloser? RID iRecord; IfFailGo(pMiniMd->FindNestedClassHelper(tkTypeDefCur, &iRecord)); if (InvalidRid(iRecord)) { tkTypeDefCur = mdTokenNil; } else { NestedClassRec *pNestedClassRec; IfFailGo(pMiniMd->GetNestedClassRecord(iRecord, &pNestedClassRec)); tkTypeDefCur = pMiniMd->getEnclosingClassOfNestedClass(pNestedClassRec); } } else tkTypeDefCur = mdTokenNil; } // EP must have a predetermined signature (different for DLL and EXE IfFailGo(pMiniMd->getSignatureOfMethod(pRecord, &pbSig, &cbSig)); ulCallConv = CorSigUncompressData(pbSig); // get call conv out of the way // EP can't be generic if (ulCallConv & IMAGE_CEE_CS_CALLCONV_GENERIC) { // Skip the arity CorSigUncompressData(pbSig); REPORT_ERROR0(VLDTR_E_EP_GENERIC_METHOD); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // EP must have 0 or 1 argument unsigned nArgs = CorSigUncompressData(pbSig); if(g_fIsDLL) { if(nArgs != 3) { REPORT_ERROR1(VLDTR_E_EP_TOOMANYARGS, 3); SetVldtrCode(&hrSave, VLDTR_S_ERR); } //EP must return I4 while (((retType=CorSigUncompressData(pbSig)) == ELEMENT_TYPE_CMOD_OPT) || (retType == ELEMENT_TYPE_CMOD_REQD)) CorSigUncompressToken(pbSig); if(retType != ELEMENT_TYPE_I4) { REPORT_ERROR0(VLDTR_E_EP_BADRET); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Arguments must be VOID*, U4, VOID* if(nArgs) { unsigned jj; bool badarg; for(jj=0; jj<nArgs;jj++) { while (((retType=CorSigUncompressData(pbSig)) == ELEMENT_TYPE_CMOD_OPT) || (retType == ELEMENT_TYPE_CMOD_REQD)) CorSigUncompressToken(pbSig); switch(jj) { case 0: case 2: badarg = (retType != ELEMENT_TYPE_PTR) ||(CorSigUncompressData(pbSig) != ELEMENT_TYPE_VOID); break; case 1: badarg = (retType != ELEMENT_TYPE_U4); break; default: badarg = true; } if(badarg) { REPORT_ERROR1(VLDTR_E_EP_BADARG, jj+1); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } } else { if(nArgs > 1) { REPORT_ERROR1(VLDTR_E_EP_TOOMANYARGS, 1); SetVldtrCode(&hrSave, VLDTR_S_ERR); } //EP must return VOID, I4 or U4 while (((retType=CorSigUncompressData(pbSig)) == ELEMENT_TYPE_CMOD_OPT) || (retType == ELEMENT_TYPE_CMOD_REQD)) CorSigUncompressToken(pbSig); if((retType != ELEMENT_TYPE_VOID)&&(retType != ELEMENT_TYPE_I4)&&(retType != ELEMENT_TYPE_U4)) { REPORT_ERROR0(VLDTR_E_EP_BADRET); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Argument (if any) must be vector of strings if(nArgs) { while (((retType=CorSigUncompressData(pbSig)) == ELEMENT_TYPE_CMOD_OPT) || (retType == ELEMENT_TYPE_CMOD_REQD)) CorSigUncompressToken(pbSig); if((retType != ELEMENT_TYPE_SZARRAY)||(CorSigUncompressData(pbSig) != ELEMENT_TYPE_STRING)) { REPORT_ERROR1(VLDTR_E_EP_BADARG, 1); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } // end if(IsDll)--else } // end if (IsEntryPoint) // Check method RVA if(pRecord->GetRVA()==0) { if(!(IsMdPinvokeImpl(dwFlags) || IsMdAbstract(dwFlags) || IsMiRuntime(dwImplFlags) || IsMiInternalCall(dwImplFlags) || bIsParentImport)) { REPORT_ERROR0(VLDTR_E_MD_ZERORVA); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } else { if(m_pStgdb && m_pStgdb->m_pImage) { NewHolder<PEDecoder> pe; EX_TRY { // We need to use different PEDecoder constructors based on the type of data we give it. // We use the one with a 'bool' as the second argument when dealing with a mapped file, // and we use the one that takes a COUNT_T as the second argument when dealing with a // flat file. if (m_pStgdb->m_pStgIO->GetMemoryMappedType() == MTYPE_IMAGE) pe = new (nothrow) PEDecoder(m_pStgdb->m_pImage, false); else pe = new (nothrow) PEDecoder(m_pStgdb->m_pImage, (COUNT_T)(m_pStgdb->m_dwImageSize)); } EX_CATCH { hr = COR_E_BADIMAGEFORMAT; } EX_END_CATCH(SwallowAllExceptions) IfFailGo(hr); IfNullGo(pe); if (!pe->CheckRva(pRecord->GetRVA())) { REPORT_ERROR1(VLDTR_E_MD_BADRVA, pRecord->GetRVA()); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { if(IsMiManaged(dwImplFlags) && (IsMiIL(dwImplFlags) || IsMiOPTIL(dwImplFlags))) { HRESULT hrTemp = S_OK; // validate locals signature token EX_TRY { COR_ILMETHOD_DECODER method((COR_ILMETHOD*) pe->GetRvaData(pRecord->GetRVA())); if (method.LocalVarSigTok) { if((TypeFromToken(method.GetLocalVarSigTok()) != mdtSignature) || (!IsValidToken(method.GetLocalVarSigTok())) || (RidFromToken(method.GetLocalVarSigTok())==0)) { hrTemp = _ValidateErrorHelper(VLDTR_E_MD_BADLOCALSIGTOK, veCtxt, method.GetLocalVarSigTok()); if (SUCCEEDED(hrTemp)) SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } EX_CATCH { hrTemp = _ValidateErrorHelper(VLDTR_E_MD_BADHEADER, veCtxt); if (SUCCEEDED(hrTemp)) SetVldtrCode(&hrSave, VLDTR_S_ERR); } EX_END_CATCH(SwallowAllExceptions) IfFailGo(hrTemp); } } } if(IsMdAbstract(dwFlags) || bIsParentImport || IsMiRuntime(dwImplFlags) || IsMiInternalCall(dwImplFlags)) { REPORT_ERROR0(VLDTR_E_MD_ZERORVA); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // Check the method flags // Validate access if((dwFlags & mdMemberAccessMask) == mdMemberAccessMask) { REPORT_ERROR0(VLDTR_E_FMD_BADACCESSFLAG); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Final/NewSlot must be virtual if((IsMdFinal(dwFlags)||IsMdNewSlot(dwFlags)||IsMdCheckAccessOnOverride(dwFlags)) && !IsMdVirtual(dwFlags)) { REPORT_ERROR0(VLDTR_E_MD_FINNOTVIRT); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Static can't be final or virtual if(IsMdStatic(dwFlags)) { if(IsMdFinal(dwFlags) || IsMdVirtual(dwFlags) || IsMdNewSlot(dwFlags)) { REPORT_ERROR0(VLDTR_E_MD_STATANDFINORVIRT); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } else // non-static can't be an entry point { if(g_tkEntryPoint == veCtxt.Token) { REPORT_ERROR0(VLDTR_E_EP_INSTANCE); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } if(IsMdAbstract(dwFlags)) { // Can't be both abstract and final if(IsMdFinal(dwFlags)) { REPORT_ERROR0(VLDTR_E_MD_ABSTANDFINAL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // If abstract, must be not miForwardRef, not Pinvoke, and must be virtual if(IsMiForwardRef(dwImplFlags)) { REPORT_ERROR0(VLDTR_E_MD_ABSTANDIMPL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if(IsMdPinvokeImpl(dwFlags)) { REPORT_ERROR0(VLDTR_E_MD_ABSTANDPINVOKE); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if(!IsMdVirtual(dwFlags)) { REPORT_ERROR0(VLDTR_E_MD_ABSTNOTVIRT); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // If PrivateScope, must have RVA!=0 if(IsMdPrivateScope(dwFlags) && (pRecord->GetRVA() ==0)) { REPORT_ERROR0(VLDTR_E_MD_PRIVSCOPENORVA); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // RTSpecialName => SpecialName if(IsMdRTSpecialName(dwFlags) && !IsMdSpecialName(dwFlags)) { REPORT_ERROR0(VLDTR_E_FMD_RTSNNOTSN); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Method having security must be marked mdHasSecurity and vice versa { ULONG ridStart = 1; ULONG ridEnd = pMiniMd->getCountDeclSecuritys() + 1; ULONG index; BOOL bHasSecurity = FALSE; for (index = ridStart; index < ridEnd; index ++ ) { DeclSecurityRec *pDeclSecurityRecord; IfFailGo(pMiniMd->GetDeclSecurityRecord(index, &pDeclSecurityRecord)); if ( veCtxt.Token == pMiniMd->getParentOfDeclSecurity(pDeclSecurityRecord)) { bHasSecurity = TRUE; break; } } if(!bHasSecurity) // No records, check for CA "SuppressUnmanagedCodeSecurityAttribute" { bHasSecurity = (S_OK == ImportHelper::GetCustomAttributeByName(pMiniMd, veCtxt.Token, "System.Security.SuppressUnmanagedCodeSecurityAttribute", NULL, NULL)); } if(bHasSecurity != (IsMdHasSecurity(dwFlags)!=0)) { REPORT_ERROR0(bHasSecurity ? VLDTR_E_FMD_SECURNOTMARKED : VLDTR_E_FMD_MARKEDNOSECUR); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // Validate method semantics { MethodSemanticsRec *pRec; ULONG ridEnd; ULONG index; unsigned uTally = 0; mdToken tkEventProp; ULONG iCount; DWORD dwSemantic; // get the range of method rids given a typedef ridEnd = pMiniMd->getCountMethodSemantics(); for (index = 1; index <= ridEnd; index++ ) { IfFailGo(pMiniMd->GetMethodSemanticsRecord(index, &pRec)); if ( pMiniMd->getMethodOfMethodSemantics(pRec) == veCtxt.Token ) { uTally++; if(uTally > 1) { REPORT_ERROR0(VLDTR_E_MD_MULTIPLESEMANTICS); SetVldtrCode(&hrSave, VLDTR_S_WRN); } tkEventProp = pMiniMd->getAssociationOfMethodSemantics(pRec); if((TypeFromToken(tkEventProp) == mdtEvent)||(TypeFromToken(tkEventProp) == mdtProperty)) { iCount = (TypeFromToken(tkEventProp) == mdtEvent) ? pMiniMd->getCountEvents() : pMiniMd->getCountPropertys(); if(RidFromToken(tkEventProp) > iCount) { REPORT_ERROR1(VLDTR_E_MD_SEMANTICSNOTEXIST, tkEventProp); SetVldtrCode(&hrSave, VLDTR_S_WRN); } } else { REPORT_ERROR1(VLDTR_E_MD_INVALIDSEMANTICS, tkEventProp); SetVldtrCode(&hrSave, VLDTR_S_WRN); } // One and only one semantics flag must be set iCount = 0; dwSemantic = pRec->GetSemantic(); if(IsMsSetter(dwSemantic)) iCount++; if(IsMsGetter(dwSemantic)) iCount++; if(IsMsOther(dwSemantic)) iCount++; if(IsMsAddOn(dwSemantic)) iCount++; if(IsMsRemoveOn(dwSemantic)) iCount++; if(IsMsFire(dwSemantic)) iCount++; if(iCount != 1) { REPORT_ERROR1(iCount ? VLDTR_E_MD_MULTSEMANTICFLAGS : VLDTR_E_MD_NOSEMANTICFLAGS, tkEventProp); SetVldtrCode(&hrSave, VLDTR_S_WRN); } } }// end for(index) } // Check the method's impl.map { RID iRecord; IfFailGo(pMiniMd->FindImplMapHelper(veCtxt.Token, &iRecord)); if(IsMdPinvokeImpl(dwFlags)) { // must be static if(!IsMdStatic(dwFlags)) { REPORT_ERROR0(VLDTR_E_FMD_PINVOKENOTSTATIC); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // must have either ImplMap or RVA == 0 if (InvalidRid(iRecord)) { if(pRecord->GetRVA()==0) { REPORT_ERROR0(VLDTR_E_FMD_MARKEDNOPINVOKE); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } else { if(pRecord->GetRVA()!=0) { // C++ emits ImplMaps for IJW methods, // with resolution=ModuleRef with name "" ImplMapRec *pIMRecord; mdToken tkModuleRef; IfFailGo(pMiniMd->GetImplMapRecord(iRecord, &pIMRecord)); tkModuleRef = pMiniMd->getImportScopeOfImplMap(pIMRecord); if((TypeFromToken(tkModuleRef) == mdtModuleRef) && (!IsNilToken(tkModuleRef))) { ModuleRefRec *pMRRecord; // ModuleRef record. LPCUTF8 szMRName; // ModuleRef name. // Get the ModuleRef record. IfFailGo(pMiniMd->GetModuleRefRecord(RidFromToken(tkModuleRef), &pMRRecord)); // Check ModuleRef name is "". IfFailGo(pMiniMd->getNameOfModuleRef(pMRRecord, &szMRName)); if (*szMRName) { REPORT_ERROR0(VLDTR_E_MD_RVAANDIMPLMAP); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } else { hr = ValidateImplMap(iRecord); if(hr != S_OK) { REPORT_ERROR0(VLDTR_E_FMD_BADIMPLMAP); SetVldtrCode(&hrSave, VLDTR_S_WRN); } } } } else { // must have no ImplMap if (!InvalidRid(iRecord)) { REPORT_ERROR0(VLDTR_E_FMD_PINVOKENOTMARKED); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } // Validate params { ULONG ridStart = pMiniMd->getParamListOfMethod(pRecord); ULONG ridEnd; IfFailGo(pMiniMd->getEndParamListOfMethod(rid, &ridEnd)); ParamRec* pRec; ULONG cbSigT; PCCOR_SIGNATURE typePtr; IfFailGo(pMiniMd->getSignatureOfMethod(pRecord, &typePtr, &cbSigT)); unsigned callConv = CorSigUncompressData(typePtr); // get the calling convention out of the way unsigned numTyArgs = 0; if (callConv & IMAGE_CEE_CS_CALLCONV_GENERIC) { bIsGeneric = TRUE; numTyArgs = CorSigUncompressData(typePtr); } unsigned numArgs = CorSigUncompressData(typePtr); USHORT usPrevSeq = 0; for(ULONG ridP = ridStart; ridP < ridEnd; ridP++) { RID tempRid; IfFailGo(pMiniMd->GetParamRecord(ridP, &pRec)); // Sequence order must be ascending if(ridP > ridStart) { if(pRec->GetSequence() <= usPrevSeq) { REPORT_ERROR2(VLDTR_E_MD_PARAMOUTOFSEQ, ridP-ridStart,pRec->GetSequence()); SetVldtrCode(&hrSave, VLDTR_S_WRN); } } usPrevSeq = pRec->GetSequence(); // Sequence value must not exceed num of arguments if(usPrevSeq > numArgs) { REPORT_ERROR2(VLDTR_E_MD_PARASEQTOOBIG, ridP-ridStart,usPrevSeq); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Param having marshaling must be marked pdHasFieldMarshal and vice versa IfFailGo(pMiniMd->FindFieldMarshalHelper(TokenFromRid(ridP,mdtParamDef), &tempRid)); if (InvalidRid(tempRid) == (IsPdHasFieldMarshal(pRec->GetFlags()) != 0)) { REPORT_ERROR1(IsPdHasFieldMarshal(pRec->GetFlags()) ? VLDTR_E_MD_PARMMARKEDNOMARSHAL : VLDTR_E_MD_PARMMARSHALNOTMARKED, ridP-ridStart); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Param having const value must be marked pdHasDefault and vice versa IfFailGo(pMiniMd->FindConstantHelper(TokenFromRid(ridP,mdtParamDef), &tempRid)); if (InvalidRid(tempRid) == (IsPdHasDefault(pRec->GetFlags()) != 0)) { REPORT_ERROR1(IsPdHasDefault(pRec->GetFlags()) ? VLDTR_E_MD_PARMMARKEDNODEFLT : VLDTR_E_MD_PARMDEFLTNOTMARKED, ridP-ridStart); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } // Generic Method related checks if (bIsGeneric) { if (bIsCctor) { REPORT_ERROR0(VLDTR_E_MD_GENERIC_CCTOR); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if (bIsCtor) { REPORT_ERROR0(VLDTR_E_MD_GENERIC_CTOR); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if (bIsParentImport) { REPORT_ERROR0(VLDTR_E_MD_GENERIC_IMPORT); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateMethod() #ifdef _PREFAST_ #pragma warning(pop) #endif //***************************************************************************** // Validate the given ParamPtr. //***************************************************************************** HRESULT RegMeta::ValidateParamPtr(RID rid) { return S_OK; } // RegMeta::ValidateParamPtr() //***************************************************************************** // Validate the given Param. //***************************************************************************** HRESULT RegMeta::ValidateParam(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. ParamRec *pRecord; // Param record VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. LPCSTR szName; // Param name. BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Get the InterfaceImpl record. veCtxt.Token = TokenFromRid(rid, mdtParamDef); veCtxt.uOffset = 0; DWORD dwBadFlags = 0; DWORD dwFlags = 0; IfFailGo(pMiniMd->GetParamRecord(rid, &pRecord)); // Name, if any, must not exceed MAX_CLASSNAME_LENGTH IfFailGo(pMiniMd->getNameOfParam(pRecord, &szName)); ULONG L = (ULONG)strlen(szName); if(L >= MAX_CLASSNAME_LENGTH) { REPORT_ERROR2(VLDTR_E_TD_NAMETOOLONG, L, (ULONG)(MAX_CLASSNAME_LENGTH-1)); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Flags must be as defined in CorHdr.h dwBadFlags = ~(pdIn | pdOut | pdOptional | pdHasDefault | pdHasFieldMarshal); dwFlags = pRecord->GetFlags(); if(dwFlags & dwBadFlags) { REPORT_ERROR1(VLDTR_E_PD_BADFLAGS, dwFlags); SetVldtrCode(&hrSave, VLDTR_S_ERR); } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateParam() //***************************************************************************** // Helper function for ValidateInterfaceImpl //***************************************************************************** int IsMethodImplementedByClass(CMiniMdRW *pMiniMd, mdToken tkMethod, LPCUTF8 szName, PCCOR_SIGNATURE pSig, ULONG cbSig, mdToken tkClass) { HRESULT hr; int numImpl = 0; if(TypeFromToken(tkMethod) == mdtMethodDef) { if(TypeFromToken(tkClass) == mdtTypeSpec) { // We are trying to find out if an interface method is implemented in the generic class tkClass. // Simple signature comparison doesn't work here, because "int Method()" in the interface might // be implemented by "T Type.Method()" in the generic type. // Therefore we assume it is implemented. Atlernatively we could implement better signature // comparison which would match T with any other type, etc. numImpl = 1; } else if(TypeFromToken(tkClass) == mdtTypeDef) { TypeDefRec *pClass; IfFailRet(pMiniMd->GetTypeDefRecord(RidFromToken(tkClass), &pClass)); RID ridClsStart = pMiniMd->getMethodListOfTypeDef(pClass); RID ridClsEnd; IfFailRet(pMiniMd->getEndMethodListOfTypeDef(RidFromToken(tkClass), &ridClsEnd)); mdMethodDef tkFoundMethod = 0; DWORD dwFoundMethodFlags = 0; // Check among methods hr = ImportHelper::FindMethod(pMiniMd, tkClass, szName, pSig, cbSig, &tkFoundMethod, 0); if(SUCCEEDED(hr)) { MethodRec * pMethod; IfFailRet(pMiniMd->GetMethodRecord(RidFromToken(tkFoundMethod), &pMethod)); if(pMethod) { dwFoundMethodFlags = pMiniMd->getFlagsOfMethod(pMethod); if(IsMdVirtual(dwFoundMethodFlags)) //&&!IsMdNewSlot(dwFoundMethodFlags)) numImpl = 1; } } if (numImpl==0) //if(hr == CLDB_E_RECORD_NOTFOUND) { // Check among MethodImpls RID ridImpl; for(RID idxCls = ridClsStart; idxCls < ridClsEnd; idxCls++) { RID ridCls; IfFailRet(pMiniMd->GetMethodRid(idxCls, &ridCls)); hr = ImportHelper::FindMethodImpl(pMiniMd,tkClass,TokenFromRid(ridCls,mdtMethodDef), tkMethod,&ridImpl); if(hr != CLDB_E_RECORD_NOTFOUND) { if(SUCCEEDED(hr)) numImpl++; break; } } if(numImpl == 0) { // Check if parent class implements this method mdToken tkParent = pMiniMd->getExtendsOfTypeDef(pClass); if(RidFromToken(tkParent)) numImpl = IsMethodImplementedByClass(pMiniMd,tkMethod,szName,pSig,cbSig,tkParent); } } } else if (TypeFromToken(tkClass) == mdtTypeRef) { TypeRefRec *pRecord; // TypeRef record. LPCSTR szTRNamespace; // TypeRef Namespace. LPCSTR szTRName; // TypeRef Name. // Get the TypeRef record. IfFailRet(pMiniMd->GetTypeRefRecord(RidFromToken(tkClass), &pRecord)); // Check name is not NULL. IfFailRet(pMiniMd->getNamespaceOfTypeRef(pRecord, &szTRNamespace)); IfFailRet(pMiniMd->getNameOfTypeRef(pRecord, &szTRName)); mdToken tkRefScope = pMiniMd->getResolutionScopeOfTypeRef(pRecord); if (tkRefScope == TokenFromRid(1, mdtModule)) { // if the typeref is referring to a type in this module then // we should check the type definition it is referring to mdTypeDef tkTypeDef; hr = ImportHelper::FindTypeDefByName(pMiniMd, szTRNamespace, szTRName, tkRefScope, &tkTypeDef); if (SUCCEEDED(hr)) numImpl = IsMethodImplementedByClass(pMiniMd, tkMethod, szName, pSig, cbSig, tkTypeDef); } else if ((strcmp(szTRNamespace, BASE_NAMESPACE) == 0) && ((strcmp(szTRName, BASE_OBJECT_CLASSNAME) == 0) || (strcmp(szTRName, BASE_VTYPE_CLASSNAME) == 0) || (strcmp(szTRName, BASE_ENUM_CLASSNAME) == 0))) { if (((strcmp(szName, SYSTEM_OBJECT_TOSTRING_METHODNAME) == 0) && (cbSig == _countof(g_sigSystemObject_ToString)) && (memcmp(pSig, g_sigSystemObject_ToString, cbSig) == 0)) || ((strcmp(szName, SYSTEM_OBJECT_GETHASHCODE_METHODNAME) == 0) && (cbSig == _countof(g_sigSystemObject_GetHashCode)) && (memcmp(pSig, g_sigSystemObject_GetHashCode, cbSig) == 0)) || ((strcmp(szName, SYSTEM_OBJECT_EQUALS_METHODNAME) == 0) && (cbSig == _countof(g_sigSystemObject_Equals)) && (memcmp(pSig, g_sigSystemObject_Equals, cbSig) == 0))) { numImpl = 1; // Method signature matches one of System.Object's virtual methods } else { numImpl = 0; // These classes (System.Object, System.ValueType and System.Enum) don't implement any other virtual methods } } else { numImpl = -1; // The method is defined in another module, we cannot verify it (no external modules are loaded) } } } return numImpl; } //***************************************************************************** // Validate the given InterfaceImpl. //***************************************************************************** //@todo GENERICS: complete logic for type specs // - for now, we just allow them, but we should be checking more properties HRESULT RegMeta::ValidateInterfaceImpl(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. InterfaceImplRec *pRecord; // InterfaceImpl record. mdTypeDef tkClass; // Class implementing the interface. mdToken tkInterface; // TypeDef for the interface. mdInterfaceImpl tkInterfaceImpl; // Duplicate InterfaceImpl. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BOOL fCheckTheMethods=TRUE; BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Get the InterfaceImpl record. veCtxt.Token = TokenFromRid(rid, mdtInterfaceImpl); veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetInterfaceImplRecord(rid, &pRecord)); // Get implementing Class and the TypeDef for the interface. tkClass = pMiniMd->getClassOfInterfaceImpl(pRecord); // No validation needs to be done on deleted records. if (IsNilToken(tkClass)) goto ErrExit; tkInterface = pMiniMd->getInterfaceOfInterfaceImpl(pRecord); // Validate that the Class is TypeDef. if((!IsValidToken(tkClass))||(TypeFromToken(tkClass) != mdtTypeDef)/*&&(TypeFromToken(tkClass) != mdtTypeRef)*/) { REPORT_ERROR1(VLDTR_E_IFACE_BADIMPL, tkClass); SetVldtrCode(&hrSave, VLDTR_S_ERR); fCheckTheMethods = FALSE; } // Validate that the Interface is TypeDef or TypeRef or TypeSpec if((!IsValidToken(tkInterface))||(TypeFromToken(tkInterface) != mdtTypeDef)&&(TypeFromToken(tkInterface) != mdtTypeRef) &&(TypeFromToken(tkInterface) != mdtTypeSpec)) { REPORT_ERROR1(VLDTR_E_IFACE_BADIFACE, tkInterface); SetVldtrCode(&hrSave, VLDTR_S_ERR); fCheckTheMethods = FALSE; } // Validate that Interface is marked tdInterface. else if(TypeFromToken(tkInterface) == mdtTypeDef) { TypeDefRec *pTDRec; IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkInterface), &pTDRec)); if(!IsTdInterface(pTDRec->GetFlags())) { REPORT_ERROR1(VLDTR_E_IFACE_NOTIFACE, tkInterface); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // Look for duplicates. hr = ImportHelper::FindInterfaceImpl(pMiniMd, tkClass, tkInterface, &tkInterfaceImpl, rid); if (hr == S_OK) { REPORT_ERROR1(VLDTR_E_IFACE_DUP, tkInterfaceImpl); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (hr == CLDB_E_RECORD_NOTFOUND) hr = S_OK; else IfFailGo(hr); // Validate that the Class (if not interface or abstract) implements all the methods of Interface if((TypeFromToken(tkInterface) == mdtTypeDef) && fCheckTheMethods && (tkInterface != tkClass)) { TypeDefRec *pClass; IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkClass), &pClass)); if(!(IsTdAbstract(pClass->GetFlags()) ||IsTdImport(pClass->GetFlags()) ||IsTdInterface(pClass->GetFlags()))) { TypeDefRec *pInterface; IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkInterface), &pInterface)); RID ridIntStart = pMiniMd->getMethodListOfTypeDef(pInterface); RID ridIntEnd; IfFailGo(pMiniMd->getEndMethodListOfTypeDef(RidFromToken(tkInterface), &ridIntEnd)); MethodRec* pIntMethod; for(RID idxInt = ridIntStart; idxInt < ridIntEnd; idxInt++) { RID ridInt; IfFailGo(pMiniMd->GetMethodRid(idxInt, &ridInt)); IfFailGo(pMiniMd->GetMethodRecord(ridInt, &pIntMethod)); const char* szName; IfFailGo(pMiniMd->getNameOfMethod(pIntMethod, &szName)); if(!IsMdStatic(pIntMethod->GetFlags()) && !IsDeletedName(szName) && !IsVtblGapName(szName)) { ULONG cbSig; PCCOR_SIGNATURE pSig; IfFailGo(pMiniMd->getSignatureOfMethod(pIntMethod, &pSig, &cbSig)); if(cbSig) { int num = IsMethodImplementedByClass(pMiniMd,TokenFromRid(ridInt,mdtMethodDef),szName,pSig,cbSig,tkClass); if(num == 0) { // Error: method not implemented REPORT_ERROR3(VLDTR_E_IFACE_METHNOTIMPL, tkClass, tkInterface, TokenFromRid(ridInt,mdtMethodDef)); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if(num == -1) { // Traced to a TypeRef, which might implement the method, give warning REPORT_ERROR3(VLDTR_E_IFACE_METHNOTIMPLTHISMOD, tkClass, tkInterface, TokenFromRid(ridInt,mdtMethodDef)); SetVldtrCode(&hrSave, VLDTR_S_WRN); } if(num > 1) { // Error: multiple method implementation REPORT_ERROR3(VLDTR_E_IFACE_METHMULTIMPL, tkClass, tkInterface, TokenFromRid(ridInt,mdtMethodDef)); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } } } } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateInterfaceImpl() //***************************************************************************** // Validate the given GenericParam. //***************************************************************************** HRESULT RegMeta::ValidateGenericParam(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. GenericParamRec *pRecord; // GenericParam record. LPCSTR szName; // GenericParam name field. mdToken tkOwner; // GenericParam owner field. ULONG ulNumber; // GenericParam number field. DWORD dwFlags; // GenericParam flags field VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Get the GenericParam record. veCtxt.Token = TokenFromRid(rid, mdtGenericParam); veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetGenericParamRecord(rid, &pRecord)); // 1. GenericParam may contain zero or more rows. // (Nothing to check.) tkOwner = pMiniMd->getOwnerOfGenericParam(pRecord); // 2. Owner must be a valid token and a type def or method def // (Already checked by ValidateRecord) // CLR tolerates Nil owners, ECMA does not if(IsNilToken(tkOwner)) { REPORT_ERROR0(VLDTR_E_GP_OWNERNIL); SetVldtrCode(&hrSave, VLDTR_S_WRN); } //3. Every generic type shall own one row in the Generic Param table for each of its type parameters. [ERROR] // (Nothing to check, as the arity of a generic type is, by definition, the number of generic param entries). //4. Every generic method shall own one row in the Generic Param table for each of its type parameters. [ERROR] // (This is checked in ValidateMethodSig, error VLDTR_E_MD_GPMISMATCH). ulNumber = pMiniMd->getNumberOfGenericParam(pRecord); // 5. Flags must be valid { DWORD dwInvalidMask, dwExtraBits; dwFlags = pMiniMd->getFlagsOfGenericParam(pRecord); // check for extra bits dwInvalidMask = (DWORD)~(gpVarianceMask|gpSpecialConstraintMask); dwExtraBits = dwFlags & dwInvalidMask; if(dwExtraBits) { //@GENERICS: we could use a custom error, // but this is one is already used in more than one context. REPORT_ERROR1(VLDTR_E_TD_EXTRAFLAGS, dwExtraBits); SetVldtrCode(&hrSave, VLDTR_S_ERR); } //Check Variance { DWORD dwVariance = dwFlags & gpVarianceMask; switch (dwVariance) { case gpNonVariant: // always ok break; case gpCovariant: case gpContravariant: if (TypeFromToken(tkOwner)==mdtTypeDef) { if (IsNilToken(tkOwner)) break; TypeDefRec *pTypeDefRec; IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkOwner), &pTypeDefRec)); // co-contra variance only legal on interfaces and delegates // If owner is not an interface and does not extend MultiCastDelegate, report an error if(!IsTdInterface(pTypeDefRec->GetFlags())) { // Get the parent of the TypeDef. mdToken tkExtends = pMiniMd->getExtendsOfTypeDef(pTypeDefRec); LPCSTR szExtName = NULL; // Parent Name. LPCSTR szExtNameSpace = NULL; // Parent NameSpace. BOOL bExtendsMCDelegate = FALSE; // Determine if the parent is MCDelegate if (TypeFromToken(tkExtends) != mdtTypeSpec) { if (TypeFromToken(tkExtends) == mdtTypeRef) { TypeRefRec *pExtTypeRefRec; IfFailGo(pMiniMd->GetTypeRefRecord(RidFromToken(tkExtends), &pExtTypeRefRec)); mdToken tkResScope = pMiniMd->getResolutionScopeOfTypeRef(pExtTypeRefRec); if (RidFromToken(tkResScope) && (TypeFromToken(tkResScope) == mdtAssemblyRef)) { AssemblyRefRec * pARRec; IfFailGo(pMiniMd->GetAssemblyRefRecord(RidFromToken(tkResScope), &pARRec)); LPCSTR szAssemblyRefName; IfFailGo(pMiniMd->getNameOfAssemblyRef(pARRec, &szAssemblyRefName)); if ((0 == SString::_stricmp("mscorlib", szAssemblyRefName)) || (0 == SString::_stricmp("System.Runtime", szAssemblyRefName))) // otherwise don't even bother extracting the name { IfFailGo(pMiniMd->getNameOfTypeRef(pExtTypeRefRec, &szExtName)); IfFailGo(pMiniMd->getNamespaceOfTypeRef(pExtTypeRefRec, &szExtNameSpace)); } } } else if (TypeFromToken(tkExtends) == mdtTypeDef) { if (g_fValidatingMscorlib) // otherwise don't even bother extracting the name { TypeDefRec * pExtTypeRefRec; IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkExtends), &pExtTypeRefRec)); IfFailGo(pMiniMd->getNameOfTypeDef(pExtTypeRefRec, &szExtName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pExtTypeRefRec, &szExtNameSpace)); } } bExtendsMCDelegate = szExtNameSpace && szExtName && (0 == strcmp(szExtNameSpace,BASE_NAMESPACE)) && (0 == strcmp(szExtName,BASE_MCDELEGATE_CLASSNAME)); } // Report any error if (!bExtendsMCDelegate) { REPORT_ERROR1(VLDTR_E_GP_UNEXPECTED_OWNER_FOR_VARIANT_VAR,tkOwner); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } else { // co-contra variance never legal on MVARs REPORT_ERROR0(VLDTR_E_GP_ILLEGAL_VARIANT_MVAR); SetVldtrCode(&hrSave, VLDTR_S_ERR); } break; default: REPORT_ERROR1(VLDTR_E_GP_ILLEGAL_VARIANCE_FLAGS,dwFlags); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } } // Check special constraints { DWORD dwSpecialConstraints = dwFlags & gpSpecialConstraintMask; // It is illegal go declare both gpNotNullableValueTypeConstraint // and gpReferenceTypeConstraint, but gpDefaultConstructorConstraint // is legal with either (or neither). if ((dwSpecialConstraints & (gpReferenceTypeConstraint | gpNotNullableValueTypeConstraint)) == (gpReferenceTypeConstraint | gpNotNullableValueTypeConstraint)) { REPORT_ERROR1(VLDTR_E_GP_REFANDVALUETYPE,dwFlags); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } // 6. Number shall have a value >=0 and < number of type parameters in owner type or method. // 7. Successive rows of the GenericParam table that are owned by the same method (sic) (owner?) shall // be ordered by increasing Number value; there can be no gaps in the Number sequence. { if(ulNumber>0) { if(rid==1) { REPORT_ERROR0(VLDTR_E_GP_NONSEQ_BY_NUMBER); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { GenericParamRec *pPredRecord; IfFailGo(pMiniMd->GetGenericParamRecord(rid-1, &pPredRecord)); mdToken tkPredOwner = pMiniMd->getOwnerOfGenericParam(pPredRecord); ULONG ulPredNumber = pMiniMd->getNumberOfGenericParam(pPredRecord); if (tkPredOwner != tkOwner) { REPORT_ERROR0(VLDTR_E_GP_NONSEQ_BY_OWNER); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if (ulPredNumber != ulNumber-1) { REPORT_ERROR0(VLDTR_E_GP_NONSEQ_BY_NUMBER); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } } // 8. Name must be non-null and not too long IfFailGo(pMiniMd->getNameOfGenericParam(pRecord, &szName)); if (!*szName) { // name is NULL. REPORT_ERROR0(VLDTR_E_GP_NAMENULL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { if(!strcmp(szName,COR_DELETED_NAME_A)) goto ErrExit; //@GENERICS: do we allow parameters to be deleted? ULONG L = (ULONG)strlen(szName); if(L >= MAX_CLASSNAME_LENGTH) { REPORT_ERROR2(VLDTR_E_TD_NAMETOOLONG, L, (ULONG)(MAX_CLASSNAME_LENGTH-1)); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } #ifdef THIS_RULE_IS_DISABLED_BECAUSE_CSHARP_EMITS_DUP_NAMES_AND_DOESNT_WANT_TO_STOP // 9. There shall be no duplicates based upon Owner and Name if (szName) { mdGenericParam tkDupGenericParam; hr = ImportHelper::FindGenericParamByOwner(pMiniMd, tkOwner, szName, NULL, &tkDupGenericParam, rid); if (hr == S_OK) { REPORT_ERROR1(VLDTR_E_GP_DUPNAME, tkDupGenericParam); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (hr == CLDB_E_RECORD_NOTFOUND) hr = S_OK; else IfFailGo(hr); } #endif // 10. There shall be no duplicates based upon Owner and Number { mdGenericParam tkDupGenericParam; hr = ImportHelper::FindGenericParamByOwner(pMiniMd, tkOwner, NULL, &ulNumber, &tkDupGenericParam, rid); if (hr == S_OK) { REPORT_ERROR1(VLDTR_E_GP_DUPNUMBER, tkDupGenericParam); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (hr == CLDB_E_RECORD_NOTFOUND) hr = S_OK; else IfFailGo(hr); } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateGenericParam() //***************************************************************************** // Validate the given MemberRef. //***************************************************************************** HRESULT RegMeta::ValidateMemberRef(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. MemberRefRec *pRecord; // MemberRef record. mdMemberRef tkMemberRef; // Duplicate MemberRef. mdToken tkClass; // MemberRef parent. LPCSTR szName; // MemberRef name. PCCOR_SIGNATURE pbSig; // MemberRef signature. PCCOR_SIGNATURE pbSigTmp; // Temp copy of pbSig, so that can be changed. ULONG cbSig; // Size of sig in bytes. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Get the MemberRef record. veCtxt.Token = TokenFromRid(rid, mdtMemberRef); veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetMemberRefRecord(rid, &pRecord)); // Do checks for name validity. IfFailGo(pMiniMd->getNameOfMemberRef(pRecord, &szName)); if (!*szName) { REPORT_ERROR0(VLDTR_E_MR_NAMENULL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { if (IsVtblGapName(szName)) { REPORT_ERROR0(VLDTR_E_MR_VTBLNAME); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (IsDeletedName(szName)) { REPORT_ERROR0(VLDTR_E_MR_DELNAME); SetVldtrCode(&hrSave, VLDTR_S_ERR); } ULONG L = (ULONG)strlen(szName); if(L >= MAX_CLASSNAME_LENGTH) { // Name too long REPORT_ERROR2(VLDTR_E_TD_NAMETOOLONG, L, (ULONG)(MAX_CLASSNAME_LENGTH-1)); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // MemberRef parent should never be nil in a PE file. tkClass = pMiniMd->getClassOfMemberRef(pRecord); if (m_ModuleType == ValidatorModuleTypePE && IsNilToken(tkClass)) { REPORT_ERROR0(VLDTR_E_MR_PARNIL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Verify that the signature is a valid signature as per signature spec. IfFailGo(pMiniMd->getSignatureOfMemberRef(pRecord, &pbSig, &cbSig)); // Do some semantic checks based on the signature. if (hr == S_OK) { ULONG ulCallingConv; ULONG ulArgCount; ULONG ulTyArgCount = 0; ULONG ulCurByte = 0; // Extract calling convention. pbSigTmp = pbSig; ulCurByte += CorSigUncompressedDataSize(pbSigTmp); ulCallingConv = CorSigUncompressData(pbSigTmp); // Get the type argument count if (ulCallingConv & IMAGE_CEE_CS_CALLCONV_GENERIC) { ulCurByte += CorSigUncompressedDataSize(pbSigTmp); ulTyArgCount = CorSigUncompressData(pbSigTmp); } // Get the argument count. ulCurByte += CorSigUncompressedDataSize(pbSigTmp); ulArgCount = CorSigUncompressData(pbSigTmp); // Calling convention must be one of IMAGE_CEE_CS_CALLCONV_DEFAULT, // IMAGE_CEE_CS_CALLCONV_VARARG or IMAGE_CEE_CS_CALLCONV_FIELD. if (!isCallConv(ulCallingConv, IMAGE_CEE_CS_CALLCONV_DEFAULT) && !isCallConv(ulCallingConv, IMAGE_CEE_CS_CALLCONV_VARARG) && !isCallConv(ulCallingConv, IMAGE_CEE_CS_CALLCONV_FIELD)) { REPORT_ERROR1(VLDTR_E_MR_BADCALLINGCONV, ulCallingConv); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // [CLS] Calling convention must not be VARARG if(isCallConv(ulCallingConv, IMAGE_CEE_CS_CALLCONV_VARARG)) { REPORT_ERROR0(VLDTR_E_MR_VARARGCALLINGCONV); SetVldtrCode(&hrSave, VLDTR_S_WRN); } // If the parent is a MethodDef... if (TypeFromToken(tkClass) == mdtMethodDef) { if (RidFromToken(tkClass) != 0) { // The MethodDef must be the same name and the fixed part of the // vararg signature must be the same. MethodRec *pMethodRecord; // Method Record. LPCSTR szMethodName; // Method name. PCCOR_SIGNATURE pbMethodSig; // Method signature. ULONG cbMethodSig; // Size in bytes of signature. // Get Method record, name and signature. IfFailGo(pMiniMd->GetMethodRecord(RidFromToken(tkClass), &pMethodRecord)); IfFailGo(pMiniMd->getNameOfMethod(pMethodRecord, &szMethodName)); IfFailGo(pMiniMd->getSignatureOfMethod(pMethodRecord, &pbMethodSig, &cbMethodSig)); // Verify that the name of the Method is the same as the MemberRef. if (strcmp(szName, szMethodName)) { REPORT_ERROR1(VLDTR_E_MR_NAMEDIFF, tkClass); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if (isCallConv(ulCallingConv, IMAGE_CEE_CS_CALLCONV_VARARG)) { // It's VARARG calling convention CQuickBytes qbFixedSig; // Quick bytes to hold the fixed part of the variable signature. ULONG cbFixedSig; // Size in bytes of the fixed part. // Get the fixed part of the vararg signature of the MemberRef. hr = _GetFixedSigOfVarArg(pbSig, cbSig, &qbFixedSig, &cbFixedSig); if (FAILED(hr) || cbFixedSig != cbMethodSig || memcmp(pbMethodSig, qbFixedSig.Ptr(), cbFixedSig)) { UnifiedAssemblySigComparer uasc(*this); MDSigComparer sc(MDSigParser(pbMethodSig, cbMethodSig), MDSigParser((PCCOR_SIGNATURE)qbFixedSig.Ptr(), cbFixedSig), uasc); hr = sc.CompareMethodSignature(); if (FAILED(hr)) { hr = S_OK; REPORT_ERROR1(VLDTR_E_MR_SIGDIFF, tkClass); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } else { // It's not VARARG calling convention - a MemberRef is referencing MethodDef (part of // NoPIA) UnifiedAssemblySigComparer uasc(*this); MDSigComparer sc(MDSigParser(pbMethodSig, cbMethodSig), MDSigParser(pbSig, cbSig), uasc); // Compare signatures hr = sc.CompareMethodSignature(); if (FAILED(hr)) { hr = S_OK; REPORT_ERROR1(VLDTR_E_MR_SIGDIFF, tkClass); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } } // There should be no duplicate MemberRefs. if (*szName && pbSig && cbSig) { hr = ImportHelper::FindMemberRef(pMiniMd, tkClass, szName, pbSig, cbSig, &tkMemberRef, rid, ImportHelper::CreateHash); // Optimize for multiple calls if (hr == S_OK) { REPORT_ERROR1(VLDTR_E_MR_DUP, tkMemberRef); SetVldtrCode(&hrSave, VLDTR_S_WRN); } else if (hr == CLDB_E_RECORD_NOTFOUND) { hr = S_OK; } else { IfFailGo(hr); } } if (!isCallConv(ulCallingConv, IMAGE_CEE_CS_CALLCONV_FIELD)) { hr = ValidateMethodSig(veCtxt.Token,pbSig, cbSig,0); SetVldtrCode(&hrSave,hr); } } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateMemberRef() //***************************************************************************** // Validate the given Constant. //***************************************************************************** HRESULT RegMeta::ValidateConstant(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. ConstantRec *pRecord; // Constant record. mdToken tkParent; // Constant parent. const VOID* pbBlob; // Constant value blob ptr DWORD cbBlob; // Constant value blob size VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Get the MemberRef record. veCtxt.Token = rid; veCtxt.uOffset = 0; ULONG maxrid = 0; ULONG typ = 0; IfFailGo(pMiniMd->GetConstantRecord(rid, &pRecord)); IfFailGo(pMiniMd->getValueOfConstant(pRecord, (const BYTE **)&pbBlob, &cbBlob)); switch(pRecord->GetType()) { case ELEMENT_TYPE_BOOLEAN: case ELEMENT_TYPE_CHAR: case ELEMENT_TYPE_I1: case ELEMENT_TYPE_U1: case ELEMENT_TYPE_I2: case ELEMENT_TYPE_U2: case ELEMENT_TYPE_I4: case ELEMENT_TYPE_U4: case ELEMENT_TYPE_R4: case ELEMENT_TYPE_I8: case ELEMENT_TYPE_U8: case ELEMENT_TYPE_R8: if(pbBlob == NULL) { REPORT_ERROR1(VLDTR_E_CN_BLOBNULL, pRecord->GetType()); SetVldtrCode(&hrSave, VLDTR_S_ERR); } case ELEMENT_TYPE_STRING: break; case ELEMENT_TYPE_CLASS: if(GET_UNALIGNED_32(pbBlob) != 0) { REPORT_ERROR1(VLDTR_E_CN_BLOBNOTNULL, pRecord->GetType()); SetVldtrCode(&hrSave, VLDTR_S_ERR); } break; default: REPORT_ERROR1(VLDTR_E_CN_BADTYPE, pRecord->GetType()); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } tkParent = pMiniMd->getParentOfConstant(pRecord); typ = TypeFromToken(tkParent); switch(typ) { case mdtFieldDef: maxrid = pMiniMd->getCountFields(); break; case mdtParamDef: maxrid = pMiniMd->getCountParams(); break; case mdtProperty: maxrid = pMiniMd->getCountPropertys(); break; } switch(typ) { case mdtFieldDef: case mdtParamDef: case mdtProperty: { ULONG rid_p = RidFromToken(tkParent); if((0==rid_p)||(rid_p > maxrid)) { REPORT_ERROR1(VLDTR_E_CN_PARENTRANGE, tkParent); SetVldtrCode(&hrSave, VLDTR_S_WRN); } break; } default: REPORT_ERROR1(VLDTR_E_CN_PARENTTYPE, tkParent); SetVldtrCode(&hrSave, VLDTR_S_WRN); break; } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateConstant() //***************************************************************************** // Validate the given CustomAttribute. //***************************************************************************** HRESULT RegMeta::ValidateCustomAttribute(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BEGIN_ENTRYPOINT_NOTHROW; CustomAttributeRec *pRecord; IfFailGo(pMiniMd->GetCustomAttributeRecord(rid, &pRecord)); memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = TokenFromRid(rid,mdtCustomAttribute); veCtxt.uOffset = 0; if (pRecord != NULL) { mdToken tkOwner = pMiniMd->getParentOfCustomAttribute(pRecord); if(RidFromToken(tkOwner)) { // if 0, it's deleted CA, don't pay attention mdToken tkCAType = pMiniMd->getTypeOfCustomAttribute(pRecord); DWORD cbValue=0; const BYTE *pbValue; IfFailGo(pMiniMd->getValueOfCustomAttribute(pRecord, &pbValue, &cbValue)); if((TypeFromToken(tkOwner)==mdtCustomAttribute)||(!IsValidToken(tkOwner))) { REPORT_ERROR1(VLDTR_E_CA_BADPARENT, tkOwner); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if(((TypeFromToken(tkCAType)!=mdtMethodDef)&&(TypeFromToken(tkCAType)!=mdtMemberRef)) ||(!IsValidToken(tkCAType))||(RidFromToken(tkCAType)==0)) { REPORT_ERROR1(VLDTR_E_CA_BADTYPE, tkCAType); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { //i.e. Type is valid MethodDef or MemberRef LPCUTF8 szName; PCCOR_SIGNATURE pSig=NULL; DWORD cbSig=0; DWORD dwFlags=0; if (TypeFromToken(tkCAType) == mdtMethodDef) { MethodRec *pTypeRec; IfFailGo(pMiniMd->GetMethodRecord(RidFromToken(tkCAType), &pTypeRec)); IfFailGo(pMiniMd->getNameOfMethod(pTypeRec, &szName)); IfFailGo(pMiniMd->getSignatureOfMethod(pTypeRec, &pSig, &cbSig)); dwFlags = pTypeRec->GetFlags(); } else // it can be only MemberRef, otherwise we wouldn't be here { MemberRefRec *pTypeRec; IfFailGo(pMiniMd->GetMemberRefRecord(RidFromToken(tkCAType), &pTypeRec)); IfFailGo(pMiniMd->getNameOfMemberRef(pTypeRec, &szName)); IfFailGo(pMiniMd->getSignatureOfMemberRef(pTypeRec, &pSig, &cbSig)); } if (strcmp(szName, ".ctor") != 0) { REPORT_ERROR1(VLDTR_E_CA_NOTCTOR, tkCAType); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if ((cbSig > 0) && (pSig != NULL)) { if(FAILED(ValidateMethodSig(tkCAType, pSig,cbSig,dwFlags)) || (!((*pSig) & IMAGE_CEE_CS_CALLCONV_HASTHIS))) { REPORT_ERROR1(VLDTR_E_CA_BADSIG, tkCAType); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { // sig seems to be OK if ((pbValue != NULL) && (cbValue > 0)) { // Check if prolog is OK WORD pW = *((UNALIGNED WORD*)pbValue); if(pW != 0x0001) { REPORT_ERROR1(VLDTR_E_CA_BADPROLOG, pW); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Check if blob corresponds to the signature } } } else { REPORT_ERROR1(VLDTR_E_CA_NOSIG, tkCAType); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // end if bad Type - else } // end if RidFromToken(tkOwner) } // end if pRecord hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateCustomAttribute() //***************************************************************************** // Validate the given FieldMarshal. //***************************************************************************** HRESULT RegMeta::ValidateFieldMarshal(RID rid) { return S_OK; } // RegMeta::ValidateFieldMarshal() //***************************************************************************** // Validate the given DeclSecurity. //***************************************************************************** HRESULT RegMeta::ValidateDeclSecurity(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. DeclSecurityRec *pRecord; mdToken tkOwner; // Owner of the decl security DWORD dwAction; // action flags BOOL bIsValidOwner = FALSE; BEGIN_ENTRYPOINT_NOTHROW; IfFailGo(pMiniMd->GetDeclSecurityRecord(rid, &pRecord)); memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = TokenFromRid(rid,mdtPermission); veCtxt.uOffset = 0; // Must have a valid owner tkOwner = pMiniMd->getParentOfDeclSecurity(pRecord); if(RidFromToken(tkOwner)==0) goto ErrExit; // deleted record, no need to validate switch(TypeFromToken(tkOwner)) { case mdtModule: case mdtAssembly: case mdtTypeDef: case mdtMethodDef: case mdtFieldDef: case mdtInterfaceImpl: bIsValidOwner = IsValidToken(tkOwner); break; default: break; } if(!bIsValidOwner) { REPORT_ERROR1(VLDTR_E_DS_BADOWNER, tkOwner); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Must have one and only one flag set dwAction = pRecord->GetAction() & dclActionMask; if(dwAction > dclMaximumValue) // the flags are 0,1,2,3,...,dclMaximumValue { REPORT_ERROR1(VLDTR_E_DS_BADFLAGS, dwAction); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // If field has DeclSecurity, verify its parent is not an interface.-- checked in ValidateField // If method has DeclSecurity, verify its parent is not an interface.-- checked in ValidateMethod hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateDeclSecurity() //***************************************************************************** // Validate the given ClassLayout. //***************************************************************************** HRESULT RegMeta::ValidateClassLayout(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. ClassLayoutRec *pRecord; // ClassLayout record. TypeDefRec *pTypeDefRec; // Parent TypeDef record. DWORD dwPackingSize; // Packing size. mdTypeDef tkParent; // Parent TypeDef token. DWORD dwTypeDefFlags; // Parent TypeDef flags. RID clRid; // Duplicate ClassLayout rid. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. memset(&veCtxt, 0, sizeof(VEContext)); BEGIN_ENTRYPOINT_NOTHROW; // Extract the record. veCtxt.Token = rid; veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetClassLayoutRecord(rid, &pRecord)); // Get the parent, if parent is nil its a deleted record. Skip validation. tkParent = pMiniMd->getParentOfClassLayout(pRecord); if (IsNilToken(tkParent)) goto ErrExit; // Parent should not have AutoLayout set on it. IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkParent), &pTypeDefRec)); dwTypeDefFlags = pMiniMd->getFlagsOfTypeDef(pTypeDefRec); if (IsTdAutoLayout(dwTypeDefFlags)) { REPORT_ERROR1(VLDTR_E_CL_TDAUTO, tkParent); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Parent must not be an Interface if(IsTdInterface(dwTypeDefFlags)) { REPORT_ERROR1(VLDTR_E_CL_TDINTF, tkParent); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Validate the PackingSize. dwPackingSize = pMiniMd->getPackingSizeOfClassLayout(pRecord); if((dwPackingSize > 128)||((dwPackingSize & (dwPackingSize-1)) !=0 )) { REPORT_ERROR2(VLDTR_E_CL_BADPCKSZ, tkParent, dwPackingSize); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Validate that there are no duplicates. hr = _FindClassLayout(pMiniMd, tkParent, &clRid, rid); if (hr == S_OK) { REPORT_ERROR2(VLDTR_E_CL_DUP, tkParent, clRid); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (hr == CLDB_E_RECORD_NOTFOUND) hr = S_OK; else IfFailGo(hr); hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateClassLayout() //***************************************************************************** // Validate the given FieldLayout. //***************************************************************************** HRESULT RegMeta::ValidateFieldLayout(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. FieldLayoutRec *pRecord; // FieldLayout record. mdFieldDef tkField; // Field token. ULONG ulOffset; // Field offset. FieldRec *pFieldRec; // Field record. TypeDefRec *pTypeDefRec; // Parent TypeDef record. mdTypeDef tkTypeDef; // Parent TypeDef token. RID clRid; // Corresponding ClassLayout token. RID flRid = 0; // Duplicate FieldLayout rid. DWORD dwTypeDefFlags; // Parent TypeDef flags. DWORD dwFieldFlags; // Field flags. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Extract the record. veCtxt.Token = rid; veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetFieldLayoutRecord(rid, &pRecord)); // Get the field, if it's nil it's a deleted record, so just skip it. tkField = pMiniMd->getFieldOfFieldLayout(pRecord); if (IsNilToken(tkField)) goto ErrExit; // Validate the Offset value. ulOffset = pMiniMd->getOffSetOfFieldLayout(pRecord); if (ulOffset == ULONG_MAX) { REPORT_ERROR2(VLDTR_E_FL_BADOFFSET, tkField, ulOffset); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Get the parent of the Field. IfFailGo(pMiniMd->FindParentOfFieldHelper(tkField, &tkTypeDef)); // Validate that the parent is not nil. if (IsNilToken(tkTypeDef)) { REPORT_ERROR1(VLDTR_E_FL_TDNIL, tkField); SetVldtrCode(&hr, hrSave); goto ErrExit; } // Validate that there exists a ClassLayout record associated with // this TypeDef. IfFailGo(pMiniMd->FindClassLayoutHelper(tkTypeDef, &clRid)); if (InvalidRid(rid)) { REPORT_ERROR2(VLDTR_E_FL_NOCL, tkField, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Validate that ExplicitLayout is set on the TypeDef flags. IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkTypeDef), &pTypeDefRec)); dwTypeDefFlags = pMiniMd->getFlagsOfTypeDef(pTypeDefRec); if (IsTdAutoLayout(dwTypeDefFlags)) { REPORT_ERROR2(VLDTR_E_FL_TDNOTEXPLCT, tkField, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Extract Field record. IfFailGo(pMiniMd->GetFieldRecord(RidFromToken(tkField), &pFieldRec)); // Validate that the field is non-static. dwFieldFlags = pMiniMd->getFlagsOfField(pFieldRec); if (IsFdStatic(dwFieldFlags)) { REPORT_ERROR1(VLDTR_E_FL_FLDSTATIC, tkField); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Look for duplicates. hr = _FindFieldLayout(pMiniMd, tkField, &flRid, rid); if (hr == S_OK) { REPORT_ERROR1(VLDTR_E_FL_DUP, flRid); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (hr == CLDB_E_RECORD_NOTFOUND) hr = S_OK; else IfFailGo(hr); hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateFieldLayout() //***************************************************************************** // Validate the given StandAloneSig. //***************************************************************************** HRESULT RegMeta::ValidateStandAloneSig(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. StandAloneSigRec *pRecord; // FieldLayout record. PCCOR_SIGNATURE pbSig; // Signature. ULONG cbSig; // Size in bytes of the signature. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. ULONG ulCurByte = 0; // Current index into the signature. ULONG ulCallConv; // Calling convention. ULONG ulArgCount; // Count of arguments. ULONG ulTyArgCount = 0; // Count of type arguments. ULONG i; // Looping index. ULONG ulNSentinels = 0; // Number of sentinels in the signature BOOL bNoVoidAllowed=TRUE; BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Extract the record. veCtxt.Token = TokenFromRid(rid,mdtSignature); veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetStandAloneSigRecord(rid, &pRecord)); IfFailGo(pMiniMd->getSignatureOfStandAloneSig(pRecord, &pbSig, &cbSig)); // Validate the signature is well-formed with respect to the compression // scheme. If this fails, no further validation needs to be done. if ( (hr = ValidateSigCompression(veCtxt.Token, pbSig, cbSig)) != S_OK) goto ErrExit; //_ASSERTE((rid != 0x2c2)&&(rid!=0x2c8)&&(rid!=0x2c9)&&(rid!=0x2d6)&&(rid!=0x38b)); // Validate the calling convention. ulCurByte += CorSigUncompressedDataSize(pbSig); ulCallConv = CorSigUncompressData(pbSig); i = ulCallConv & IMAGE_CEE_CS_CALLCONV_MASK; if(i == IMAGE_CEE_CS_CALLCONV_FIELD) // <REVISIT_TODO>it's a temporary bypass (VB bug)</REVISIT_TODO> ulArgCount = 1; else { if(i != IMAGE_CEE_CS_CALLCONV_LOCAL_SIG) // then it is function sig for calli { if((i >= IMAGE_CEE_CS_CALLCONV_FIELD) ||((ulCallConv & IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS) &&(!(ulCallConv & IMAGE_CEE_CS_CALLCONV_HASTHIS)))) { REPORT_ERROR1(VLDTR_E_MD_BADCALLINGCONV, ulCallConv); SetVldtrCode(&hrSave, VLDTR_S_ERR); } bNoVoidAllowed = FALSE; } // Is there any sig left for arguments? _ASSERTE(ulCurByte <= cbSig); if (cbSig == ulCurByte) { REPORT_ERROR1(VLDTR_E_MD_NOARGCNT, ulCurByte+1); SetVldtrCode(&hr, hrSave); goto ErrExit; } // Get the type argument count. if (ulCallConv & IMAGE_CEE_CS_CALLCONV_GENERIC) { ulCurByte += CorSigUncompressedDataSize(pbSig); ulTyArgCount = CorSigUncompressData(pbSig); } // Get the argument count. ulCurByte += CorSigUncompressedDataSize(pbSig); ulArgCount = CorSigUncompressData(pbSig); } // Validate the the arguments. if(ulArgCount) { for(i=1; ulCurByte < cbSig; i++) { hr = ValidateOneArg(veCtxt.Token, pbSig, cbSig, &ulCurByte,&ulNSentinels,bNoVoidAllowed); if (hr != S_OK) { if(hr == VLDTR_E_SIG_MISSARG) { REPORT_ERROR1(VLDTR_E_SIG_MISSARG, i); } SetVldtrCode(&hr, hrSave); hrSave = hr; break; } bNoVoidAllowed = TRUE; // whatever it was for the 1st arg, it must be TRUE for the rest } if((ulNSentinels != 0) && (!isCallConv(ulCallConv, IMAGE_CEE_CS_CALLCONV_VARARG ))) { REPORT_ERROR0(VLDTR_E_SIG_SENTMUSTVARARG); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if(ulNSentinels > 1) { REPORT_ERROR0(VLDTR_E_SIG_MULTSENTINELS); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateStandAloneSig() //***************************************************************************** // Validate the given EventMap. //***************************************************************************** HRESULT RegMeta::ValidateEventMap(RID rid) { return S_OK; } // RegMeta::ValidateEventMap() //***************************************************************************** // Validate the given EventPtr. //***************************************************************************** HRESULT RegMeta::ValidateEventPtr(RID rid) { return S_OK; } // RegMeta::ValidateEventPtr() //***************************************************************************** // Validate the given Event. //***************************************************************************** HRESULT RegMeta::ValidateEvent(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. mdToken tkClass; // Declaring TypeDef mdToken tkEventType; // Event Type (TypeDef/TypeRef) EventRec *pRecord; HENUMInternal hEnum; BEGIN_ENTRYPOINT_NOTHROW; IfFailGo(pMiniMd->GetEventRecord(rid, &pRecord)); memset(&veCtxt, 0, sizeof(VEContext)); memset(&hEnum, 0, sizeof(HENUMInternal)); veCtxt.Token = TokenFromRid(rid,mdtEvent); veCtxt.uOffset = 0; // The scope must be a valid TypeDef if (FAILED(pMiniMd->FindParentOfEventHelper(veCtxt.Token, &tkClass)) || (TypeFromToken(tkClass) != mdtTypeDef) || !IsValidToken(tkClass)) { REPORT_ERROR1(VLDTR_E_EV_BADSCOPE, tkClass); SetVldtrCode(&hrSave, VLDTR_S_ERR); tkClass = 0; } // Must have name { LPCUTF8 szName; IfFailGo(pMiniMd->getNameOfEvent(pRecord, &szName)); if (*szName == 0) { REPORT_ERROR0(VLDTR_E_EV_NONAME); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { if (strcmp(szName, COR_DELETED_NAME_A) == 0) goto ErrExit; if (tkClass != 0) // Must be no duplicates { RID ridEventMap; EventMapRec *pEventMapRec; EventRec *pRec; ULONG ridStart; ULONG ridEnd; ULONG i; IfFailGo(pMiniMd->FindEventMapFor(RidFromToken(tkClass), &ridEventMap)); if (!InvalidRid(ridEventMap)) { IfFailGo(pMiniMd->GetEventMapRecord(ridEventMap, &pEventMapRec)); ridStart = pMiniMd->getEventListOfEventMap(pEventMapRec); IfFailGo(pMiniMd->getEndEventListOfEventMap(ridEventMap, &ridEnd)); for (i = ridStart; i < ridEnd; i++) { if (i == rid) continue; IfFailGo(pMiniMd->GetEventRecord(i, &pRec)); LPCSTR szEventName; IfFailGo(pMiniMd->getNameOfEvent(pRec, &szEventName)); if (strcmp(szName, szEventName) != 0) continue; REPORT_ERROR1(VLDTR_E_EV_DUP, TokenFromRid(i, mdtEvent)); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } } }// end of name block // EventType must be Nil or valid TypeDef, TypeRef or TypeSpec representing an instantiated generic type tkEventType = pMiniMd->getEventTypeOfEvent(pRecord); if (!IsNilToken(tkEventType)) { if(IsValidToken(tkEventType) && ((TypeFromToken(tkEventType)==mdtTypeDef)|| (TypeFromToken(tkEventType)==mdtTypeRef)|| (TypeFromToken(tkEventType)==mdtTypeSpec))) { // TypeSpecs can be many things, we only handle instantiated generic types currently. if (TypeFromToken(tkEventType)==mdtTypeSpec) { TypeSpecRec *pRec; IfFailGo(pMiniMd->GetTypeSpecRecord(RidFromToken(tkEventType), &pRec)); PCCOR_SIGNATURE pSig; ULONG cSig; IfFailGo(pMiniMd->getSignatureOfTypeSpec(pRec, &pSig, &cSig)); if (CorSigUncompressElementType(pSig) == ELEMENT_TYPE_GENERICINST && CorSigUncompressElementType(pSig) == ELEMENT_TYPE_CLASS) { // Just update the event type token variable and fall through to the validation code below (it doesn't care // whether the type is generic or not). tkEventType = CorSigUncompressToken(pSig); } else { REPORT_ERROR1(VLDTR_E_EV_BADEVTYPE, tkEventType); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // EventType must not be Interface or ValueType if(TypeFromToken(tkEventType)==mdtTypeDef) // can't say anything about TypeRef: no flags available! { TypeDefRec *pTypeDefRecord; IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkEventType), &pTypeDefRecord)); DWORD dwFlags = pTypeDefRecord->GetFlags(); if(!IsTdClass(dwFlags)) { REPORT_ERROR2(VLDTR_E_EV_EVTYPENOTCLASS, tkEventType, dwFlags); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } else { REPORT_ERROR1(VLDTR_E_EV_BADEVTYPE, tkEventType); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // Validate related methods { MethodSemanticsRec *pSemantics; RID ridCur; ULONG ulSemantics; mdMethodDef tkMethod; bool bHasAddOn = false; bool bHasRemoveOn = false; IfFailGo( pMiniMd->FindMethodSemanticsHelper(veCtxt.Token, &hEnum) ); while (HENUMInternal::EnumNext(&hEnum, (mdToken *)&ridCur)) { IfFailGo(pMiniMd->GetMethodSemanticsRecord(ridCur, &pSemantics)); ulSemantics = pMiniMd->getSemanticOfMethodSemantics(pSemantics); tkMethod = TokenFromRid( pMiniMd->getMethodOfMethodSemantics(pSemantics), mdtMethodDef ); // Semantics must be Setter, Getter or Other switch (ulSemantics) { case msAddOn: bHasAddOn = true; break; case msRemoveOn: bHasRemoveOn = true; break; case msFire: case msOther: break; default: REPORT_ERROR2(VLDTR_E_EV_BADSEMANTICS, tkMethod,ulSemantics); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Method must be valid if(!IsValidToken(tkMethod)) { REPORT_ERROR1(VLDTR_E_EV_BADMETHOD, tkMethod); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { // Method's parent must be the same mdToken tkTypeDef; IfFailGo(pMiniMd->FindParentOfMethodHelper(tkMethod, &tkTypeDef)); if(tkTypeDef != tkClass) { REPORT_ERROR2(VLDTR_E_EV_ALIENMETHOD, tkMethod,tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } // end loop over methods // AddOn and RemoveOn are a must if(!bHasAddOn) { REPORT_ERROR0(VLDTR_E_EV_NOADDON); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if(!bHasRemoveOn) { REPORT_ERROR0(VLDTR_E_EV_NOREMOVEON); SetVldtrCode(&hrSave, VLDTR_S_ERR); } }// end of related method validation block hr = hrSave; ErrExit: HENUMInternal::ClearEnum(&hEnum); END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateEvent() //***************************************************************************** // Validate the given PropertyMap. //***************************************************************************** HRESULT RegMeta::ValidatePropertyMap(RID rid) { return S_OK; } // RegMeta::ValidatePropertyMap(0 //***************************************************************************** // Validate the given PropertyPtr. //***************************************************************************** HRESULT RegMeta::ValidatePropertyPtr(RID rid) { return S_OK; } // RegMeta::ValidatePropertyPtr() //***************************************************************************** // Validate the given Property. //***************************************************************************** HRESULT RegMeta::ValidateProperty(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd for the scope. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. mdToken tkClass = mdTokenNil; // Declaring TypeDef PropertyRec *pRecord; HENUMInternal hEnum; RID tempRid; BEGIN_ENTRYPOINT_NOTHROW; IfFailGo(pMiniMd->GetPropertyRecord(rid, &pRecord)); memset(&veCtxt, 0, sizeof(VEContext)); memset(&hEnum, 0, sizeof(HENUMInternal)); veCtxt.Token = TokenFromRid(rid,mdtProperty); veCtxt.uOffset = 0; // The scope must be a valid TypeDef IfFailGo(pMiniMd->FindParentOfPropertyHelper( veCtxt.Token, &tkClass)); if ((TypeFromToken(tkClass) != mdtTypeDef) || !IsValidToken(tkClass) || IsNilToken(tkClass)) { REPORT_ERROR1(VLDTR_E_PR_BADSCOPE, tkClass); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Must have name and signature { ULONG cbSig; PCCOR_SIGNATURE pvSig; IfFailGo(pMiniMd->getTypeOfProperty(pRecord, &pvSig, &cbSig)); LPCUTF8 szName; IfFailGo(pMiniMd->getNameOfProperty(pRecord, &szName)); ULONG ulNameLen = (szName != NULL) ? (ULONG)strlen(szName) : 0; if (ulNameLen == 0) { REPORT_ERROR0(VLDTR_E_PR_NONAME); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { if(strcmp(szName, COR_DELETED_NAME_A) == 0) goto ErrExit; } if (cbSig == 0) { REPORT_ERROR0(VLDTR_E_PR_NOSIG); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Must be no duplicates if ((ulNameLen != 0) && (cbSig != 0)) { RID ridPropertyMap; PropertyMapRec *pPropertyMapRec; PropertyRec *pRec; ULONG ridStart; ULONG ridEnd; ULONG i; ULONG cbSig1; PCCOR_SIGNATURE pvSig1; IfFailGo(pMiniMd->FindPropertyMapFor(RidFromToken(tkClass), &ridPropertyMap)); if (!InvalidRid(ridPropertyMap) ) { IfFailGo(pMiniMd->GetPropertyMapRecord(ridPropertyMap, &pPropertyMapRec)); ridStart = pMiniMd->getPropertyListOfPropertyMap(pPropertyMapRec); IfFailGo(pMiniMd->getEndPropertyListOfPropertyMap(ridPropertyMap, &ridEnd)); for (i = ridStart; i < ridEnd; i++) { if (i == rid) continue; IfFailGo(pMiniMd->GetPropertyRecord(i, &pRec)); IfFailGo(pMiniMd->getTypeOfProperty(pRec, &pvSig1, &cbSig1)); if (cbSig != cbSig1) continue; if (memcmp(pvSig,pvSig1,cbSig) != 0) continue; LPCSTR szPropertyName; IfFailGo(pMiniMd->getNameOfProperty(pRec, &szPropertyName)); if (strcmp(szName, szPropertyName) != 0) continue; REPORT_ERROR1(VLDTR_E_PR_DUP, TokenFromRid(i,mdtProperty)); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } // Validate the signature if ((pvSig != NULL) && (cbSig != 0)) { ULONG ulCurByte = 0; // Current index into the signature. ULONG ulCallConv; // Calling convention. ULONG ulArgCount; ULONG i; ULONG ulNSentinels = 0; // Validate the calling convention. ulCurByte += CorSigUncompressedDataSize(pvSig); ulCallConv = CorSigUncompressData(pvSig); if (!isCallConv(ulCallConv, IMAGE_CEE_CS_CALLCONV_PROPERTY )) { REPORT_ERROR1(VLDTR_E_PR_BADCALLINGCONV, ulCallConv); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Get the argument count. ulCurByte += CorSigUncompressedDataSize(pvSig); ulArgCount = CorSigUncompressData(pvSig); // Validate the arguments. for (i = 0; i < ulArgCount; i++) { hr = ValidateOneArg(veCtxt.Token, pvSig, cbSig, &ulCurByte,&ulNSentinels,(i>0)); if (hr != S_OK) { if (hr == VLDTR_E_SIG_MISSARG) { REPORT_ERROR1(VLDTR_E_SIG_MISSARG, i+1); } SetVldtrCode(&hr, hrSave); break; } } }//end if(pvSig && cbSig) }// end of name/signature block // Marked HasDefault <=> has default value IfFailGo(pMiniMd->FindConstantHelper(veCtxt.Token, &tempRid)); if (InvalidRid(tempRid) == IsPrHasDefault(pRecord->GetPropFlags())) { REPORT_ERROR0(IsPrHasDefault(pRecord->GetPropFlags())? VLDTR_E_PR_MARKEDNODEFLT : VLDTR_E_PR_DEFLTNOTMARKED); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Validate related methods { MethodSemanticsRec *pSemantics; RID ridCur; ULONG ulSemantics; mdMethodDef tkMethod; IfFailGo( pMiniMd->FindMethodSemanticsHelper(veCtxt.Token, &hEnum) ); while (HENUMInternal::EnumNext(&hEnum, (mdToken *) &ridCur)) { IfFailGo(pMiniMd->GetMethodSemanticsRecord(ridCur, &pSemantics)); ulSemantics = pMiniMd->getSemanticOfMethodSemantics(pSemantics); tkMethod = TokenFromRid( pMiniMd->getMethodOfMethodSemantics(pSemantics), mdtMethodDef ); // Semantics must be Setter, Getter or Other switch (ulSemantics) { case msSetter: case msGetter: case msOther: break; default: REPORT_ERROR2(VLDTR_E_PR_BADSEMANTICS, tkMethod, ulSemantics); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Method must be valid if(!IsValidToken(tkMethod)) { REPORT_ERROR1(VLDTR_E_PR_BADMETHOD, tkMethod); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { // Method's parent must be the same mdToken tkTypeDef; IfFailGo(pMiniMd->FindParentOfMethodHelper(tkMethod, &tkTypeDef)); if(tkTypeDef != tkClass) { REPORT_ERROR2(VLDTR_E_PR_ALIENMETHOD, tkMethod, tkTypeDef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } // end loop over methods }// end of related method validation block hr = hrSave; ErrExit: HENUMInternal::ClearEnum(&hEnum); END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateProperty() //***************************************************************************** // Validate the given MethodSemantics. //***************************************************************************** HRESULT RegMeta::ValidateMethodSemantics(RID rid) { return S_OK; } // RegMeta::ValidateMethodSemantics() //***************************************************************************** // Validate the given MethodImpl. //***************************************************************************** HRESULT RegMeta::ValidateMethodImpl(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd for the scope. MethodImplRec* pRecord; MethodImplRec* pRec; VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. mdToken tkClass; // Declaring TypeDef mdToken tkBody; // Implementing method (MethodDef or MemberRef) mdToken tkDecl; // Implemented method (MethodDef or MemberRef) unsigned iCount; unsigned index; BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = TokenFromRid(rid, mdtMethodImpl); veCtxt.uOffset = 0; PCCOR_SIGNATURE pbBodySig = NULL; PCCOR_SIGNATURE pbDeclSig = NULL; IfFailGo(pMiniMd->GetMethodImplRecord(rid, &pRecord)); tkClass = pMiniMd->getClassOfMethodImpl(pRecord); // Class must be valid if(!IsValidToken(tkClass) || (TypeFromToken(tkClass) != mdtTypeDef)) { REPORT_ERROR1(VLDTR_E_MI_BADCLASS, tkClass); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { // ... and not an Interface TypeDefRec *pTypeDefRecord; IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkClass), &pTypeDefRecord)); if(IsTdInterface(pTypeDefRecord->GetFlags())) { REPORT_ERROR1(VLDTR_E_MI_CLASSISINTF, tkClass); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // Decl must be valid MethodDef or MemberRef tkDecl = pMiniMd->getMethodDeclarationOfMethodImpl(pRecord); if(!(IsValidToken(tkDecl) && ((TypeFromToken(tkDecl) == mdtMethodDef) || (TypeFromToken(tkDecl) == mdtMemberRef)))) { REPORT_ERROR1(VLDTR_E_MI_BADDECL, tkDecl); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Body must be valid MethodDef or MemberRef tkBody = pMiniMd->getMethodBodyOfMethodImpl(pRecord); if(!(IsValidToken(tkBody) && ((TypeFromToken(tkBody) == mdtMethodDef) || (TypeFromToken(tkBody) == mdtMemberRef)))) { REPORT_ERROR1(VLDTR_E_MI_BADBODY, tkBody); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // No duplicates based on (tkClass,tkDecl) iCount = pMiniMd->getCountMethodImpls(); for(index = rid+1; index <= iCount; index++) { IfFailGo(pMiniMd->GetMethodImplRecord(index, &pRec)); if((tkClass == pMiniMd->getClassOfMethodImpl(pRec)) && (tkDecl == pMiniMd->getMethodDeclarationOfMethodImpl(pRec))) { REPORT_ERROR1(VLDTR_E_MI_DUP, index); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } mdToken tkBodyParent; ULONG cbBodySig; if(TypeFromToken(tkBody) == mdtMethodDef) { MethodRec *pBodyRec; IfFailGo(pMiniMd->GetMethodRecord(RidFromToken(tkBody), &pBodyRec)); IfFailGo(pMiniMd->getSignatureOfMethod(pBodyRec, &pbBodySig, &cbBodySig)); IfFailGo(pMiniMd->FindParentOfMethodHelper(tkBody, &tkBodyParent)); // Body must not be static if(IsMdStatic(pBodyRec->GetFlags())) { REPORT_ERROR1(VLDTR_E_MI_BODYSTATIC, tkBody); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } else if(TypeFromToken(tkBody) == mdtMemberRef) { MemberRefRec *pBodyRec; IfFailGo(pMiniMd->GetMemberRefRecord(RidFromToken(tkBody), &pBodyRec)); tkBodyParent = pMiniMd->getClassOfMemberRef(pBodyRec); IfFailGo(pMiniMd->getSignatureOfMemberRef(pBodyRec, &pbBodySig, &cbBodySig)); } // Body must belong to the same class if(tkBodyParent != tkClass) { REPORT_ERROR1(VLDTR_E_MI_ALIENBODY, tkBodyParent); SetVldtrCode(&hrSave, VLDTR_S_ERR); } mdToken tkDeclParent; ULONG cbDeclSig; if(TypeFromToken(tkDecl) == mdtMethodDef) { MethodRec *pDeclRec; IfFailGo(pMiniMd->GetMethodRecord(RidFromToken(tkDecl), &pDeclRec)); IfFailGo(pMiniMd->getSignatureOfMethod(pDeclRec, &pbDeclSig, &cbDeclSig)); IfFailGo(pMiniMd->FindParentOfMethodHelper(tkDecl, &tkDeclParent)); // Decl must be virtual if(!IsMdVirtual(pDeclRec->GetFlags())) { REPORT_ERROR1(VLDTR_E_MI_DECLNOTVIRT, tkDecl); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Decl must not be final if(IsMdFinal(pDeclRec->GetFlags())) { REPORT_ERROR1(VLDTR_E_MI_DECLFINAL, tkDecl); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Decl must not be private if(IsMdPrivate(pDeclRec->GetFlags()) && IsMdCheckAccessOnOverride(pDeclRec->GetFlags())) { REPORT_ERROR1(VLDTR_E_MI_DECLPRIV, tkDecl); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } else if(TypeFromToken(tkDecl) == mdtMemberRef) { MemberRefRec *pDeclRec; IfFailGo(pMiniMd->GetMemberRefRecord(RidFromToken(tkDecl), &pDeclRec)); tkDeclParent = pMiniMd->getClassOfMemberRef(pDeclRec); IfFailGo(pMiniMd->getSignatureOfMemberRef(pDeclRec, &pbDeclSig, &cbDeclSig)); } // Compare the signatures as best we can, delegating some comparisons to the loader. if (*pbBodySig & IMAGE_CEE_CS_CALLCONV_GENERIC) { // decl's callconv must be generic if (*pbDeclSig & IMAGE_CEE_CS_CALLCONV_GENERIC) { // and the arities must match ULONG ulBodyArity = CorSigUncompressData(++pbBodySig); ULONG ulDeclArity = CorSigUncompressData(++pbDeclSig); if(ulBodyArity != ulDeclArity) { REPORT_ERROR3(VLDTR_E_MI_ARITYMISMATCH,tkDecl,ulDeclArity,ulBodyArity); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } else { REPORT_ERROR1(VLDTR_E_MI_DECLNOTGENERIC,tkDecl); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // delegate precise signature checking to the loader, // as this requires signature comparison modulo substitution } else if (*pbDeclSig & IMAGE_CEE_CS_CALLCONV_GENERIC) { REPORT_ERROR1(VLDTR_E_MI_IMPLNOTGENERIC,tkDecl); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (TypeFromToken(tkDeclParent) == mdtTypeSpec) { // do nothing for now... // delegate precise signature checking to the loader, // as this requires signature comparison modulo substitution } // Signatures must match (except call conv) else if((cbDeclSig != cbBodySig)||(memcmp(pbDeclSig+1,pbBodySig+1,cbDeclSig-1))) { //@GENERICSVER: todo: /* //@TODO: Fix to have peverify resolve assemblies // through the runtime. At that point, use this method instead // of the current compare // @TODO: check for other bad memcmp sig comparisons in peverify // Can't use memcmp because there may be two AssemblyRefs // in this scope, pointing to the same assembly, etc.). if (!MetaSig::CompareMethodSigs(pbDeclSig, cbDeclSig, Module* pModule1, pbBodySig, cbDeclSig, Module* pModule2)) */ UnifiedAssemblySigComparer uasc(*this); MDSigComparer sc(MDSigParser(pbDeclSig, cbDeclSig), MDSigParser(pbBodySig, cbBodySig), uasc); hr = sc.CompareMethodSignature(); if (FAILED(hr)) { REPORT_ERROR2(VLDTR_E_MI_SIGMISMATCH,tkDecl,tkBody); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateMethodImpl() //***************************************************************************** // Validate the given ModuleRef. //***************************************************************************** HRESULT RegMeta::ValidateModuleRef(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd for the scope. ModuleRefRec *pRecord; // ModuleRef record. LPCUTF8 szName; // ModuleRef name. mdModuleRef tkModuleRef; // Duplicate ModuleRef. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Get the ModuleRef record. veCtxt.Token = TokenFromRid(rid, mdtModuleRef); veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetModuleRefRecord(rid, &pRecord)); // C++ emits IJW methods with ImplMaps // which have resolution=ModuleRef with empty name IfFailGo(pMiniMd->getNameOfModuleRef(pRecord, &szName)); if (*szName) { // Look for a Duplicate, this function reports only one duplicate. hr = ImportHelper::FindModuleRef(pMiniMd, szName, &tkModuleRef, rid); if (hr == S_OK) { REPORT_ERROR1(VLDTR_E_MODREF_DUP, tkModuleRef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (hr == CLDB_E_RECORD_NOTFOUND) hr = S_OK; else IfFailGo(hr); } else hrSave = S_FALSE; hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateModuleRef() //***************************************************************************** // Validate the given TypeSpec. //***************************************************************************** //@todo GENERICS: reject duplicate specs? HRESULT RegMeta::ValidateTypeSpec(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. TypeSpecRec *pRecord; // TypeSpec record. PCCOR_SIGNATURE pbSig; // Signature. ULONG cbSig; // Size in bytes of the signature. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. ULONG ulCurByte = 0; // Current index into the signature. ULONG ulNSentinels = 0; // Number of sentinels in the signature BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Extract the record. veCtxt.Token = TokenFromRid(rid,mdtTypeSpec); veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetTypeSpecRecord(rid, &pRecord)); IfFailGo(pMiniMd->getSignatureOfTypeSpec(pRecord, &pbSig, &cbSig)); // Validate the signature is well-formed with respect to the compression // scheme. If this fails, no further validation needs to be done. if ( (hr = ValidateSigCompression(veCtxt.Token, pbSig, cbSig)) != S_OK) goto ErrExit; hr = ValidateOneArg(veCtxt.Token, pbSig, cbSig, &ulCurByte,&ulNSentinels,FALSE); if (hr != S_OK) { if(hr == VLDTR_E_SIG_MISSARG) { REPORT_ERROR0(VLDTR_E_TS_EMPTY); } SetVldtrCode(&hr, hrSave); hrSave = hr; } if(ulNSentinels != 0) { REPORT_ERROR0(VLDTR_E_TS_HASSENTINALS); SetVldtrCode(&hrSave, VLDTR_S_ERR); } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateTypeSpec() //***************************************************************************** // This function validates the given Field signature. This function works // with Field signature for both the MemberRef and FieldDef. //***************************************************************************** HRESULT RegMeta::ValidateMethodSpecSig( mdMethodSpec tk, // [IN] Token whose signature needs to be validated. PCCOR_SIGNATURE pbSig, // [IN] Signature. ULONG cbSig, // [IN] Size in bytes of the signature. ULONG *pArity) // [Out] Arity of the instantiation { ULONG ulCurByte = 0; // Current index into the signature. ULONG ulCallConv; // Calling convention. ULONG ulArity; // Arity of instantiation. ULONG ulArgCnt; VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); _ASSERTE(TypeFromToken(tk) == mdtMethodSpec); veCtxt.Token = tk; veCtxt.uOffset = 0; // Validate the calling convention. ulCurByte += CorSigUncompressedDataSize(pbSig); ulCallConv = CorSigUncompressData(pbSig); if (!isCallConv(ulCallConv, IMAGE_CEE_CS_CALLCONV_GENERICINST)) { REPORT_ERROR1(VLDTR_E_MS_BADCALLINGCONV, ulCallConv); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if (cbSig == ulCurByte) { REPORT_ERROR1(VLDTR_E_MS_MISSARITY, ulCurByte + 1); SetVldtrCode(&hrSave, VLDTR_S_ERR); } ulCurByte += CorSigUncompressedDataSize(pbSig); ulArity = CorSigUncompressData(pbSig); if (ulArity == 0) { REPORT_ERROR1(VLDTR_E_MS_ARITYZERO, ulCurByte); SetVldtrCode(&hrSave, VLDTR_S_ERR); } ulArgCnt = ulArity; if(pArity != NULL) { *pArity = ulArity; } // Validate and consume the arguments. while(ulArgCnt--) { PCCOR_SIGNATURE pbTypeArg = pbSig; ULONG ulTypeArgByte = ulCurByte; IfFailGo(ValidateOneArg(tk, pbSig, cbSig, &ulCurByte, NULL, TRUE)); if (hr != S_OK) { if(hr == VLDTR_E_SIG_MISSARG) { REPORT_ERROR1(VLDTR_E_MS_MISSARG, ulArity-ulArgCnt); } SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } // reject byref-like args switch (CorSigUncompressData(pbTypeArg)) { case ELEMENT_TYPE_TYPEDBYREF: case ELEMENT_TYPE_BYREF: { REPORT_ERROR1(VLDTR_E_MS_BYREFINST, ulTypeArgByte); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } default: break; } } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateMethodSpecSig() //***************************************************************************** // Validate the given MethodSpec. //***************************************************************************** HRESULT RegMeta::ValidateMethodSpec(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. MethodSpecRec *pRecord; // MethodSpec record. mdToken tkMethod; // Method field (a MethodDefOrRef) PCCOR_SIGNATURE pInstantiation; // MethodSpec instantiation (a signature) ULONG cbInstantiation; // Size of instantiation. ULONG ulInstantiationArity; // Arity of the Instantiation VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Get the GenericParamConstraint record. veCtxt.Token = TokenFromRid(rid, mdtMethodSpec); veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetMethodSpecRecord(rid, &pRecord)); // 1. The MethodSpec table may contain zero or more rows. // (Nothing to check.) // Implicit (missing from spec): Method is not nil [ERROR] tkMethod = pMiniMd->getMethodOfMethodSpec(pRecord); if(IsNilToken(tkMethod)) { REPORT_ERROR0(VLDTR_E_MS_METHODNIL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Implicit in ValidateRecord: Method is a valid mdMethodDefOrRef. // 2. One or more rows may refer to the same row in the MethodDef or MethodRef table. // (There may be more multiple instantions of the same generic method) // (nothing to check!) // 3. "The signature stored at Instantiation shall be a valid instantiation of the signature of the generic method stored at Method. [ERROR] { IfFailGo(pMiniMd->getInstantiationOfMethodSpec(pRecord, &pInstantiation, &cbInstantiation)); IfFailGo(ValidateMethodSpecSig(TokenFromRid(rid, mdtMethodSpec), pInstantiation, cbInstantiation,&ulInstantiationArity)); if (hr != S_OK) SetVldtrCode(&hrSave, hr); } IfFailGo(pMiniMd->getInstantiationOfMethodSpec(pRecord, &pInstantiation, &cbInstantiation)); // 4. There shall be no duplicate rows based upon Method and Instantiation [ERROR] { mdMethodSpec tkDupMethodSpec; hr = ImportHelper::FindMethodSpecByMethodAndInstantiation(pMiniMd, tkMethod, pInstantiation, cbInstantiation, &tkDupMethodSpec, rid); if (hr == S_OK) { REPORT_ERROR1(VLDTR_E_MS_DUP, tkDupMethodSpec); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (hr == CLDB_E_RECORD_NOTFOUND) hr = S_OK; else IfFailGo(hr); } // check the method is generic and that the arity of the instantiation is correct { PCCOR_SIGNATURE pbGenericMethodSig; ULONG cbGenericMethodSig; if(TypeFromToken(tkMethod) == mdtMethodDef) { MethodRec *pMethodRec; IfFailGo(m_pStgdb->m_MiniMd.GetMethodRecord(RidFromToken(tkMethod), &pMethodRec)); IfFailGo(pMiniMd->getSignatureOfMethod(pMethodRec, &pbGenericMethodSig, &cbGenericMethodSig)); } else { _ASSERTE(TypeFromToken(tkMethod) == mdtMemberRef); MemberRefRec *pMethodRefRec; IfFailGo(pMiniMd->GetMemberRefRecord(RidFromToken(tkMethod), &pMethodRefRec)); IfFailGo(pMiniMd->getSignatureOfMemberRef(pMethodRefRec, &pbGenericMethodSig, &cbGenericMethodSig)); } if (*pbGenericMethodSig & IMAGE_CEE_CS_CALLCONV_GENERIC) { ULONG ulGenericArity = CorSigUncompressData(++pbGenericMethodSig); if(ulGenericArity != ulInstantiationArity) { REPORT_ERROR2(VLDTR_E_MS_ARITYMISMATCH,ulGenericArity,ulInstantiationArity); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } else { REPORT_ERROR1(VLDTR_E_MS_METHODNOTGENERIC, tkMethod); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateMethodSpec() //***************************************************************************** // Validate the given GenericParamConstraint. //***************************************************************************** HRESULT RegMeta::ValidateGenericParamConstraint(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd of the scope. GenericParamConstraintRec *pRecord; // GenericParamConstraint record. mdGenericParam tkOwner; // GenericParamConstraint owner field. mdToken tkConstraint; // GenericParamConstraint constraint field. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Get the GenericParamConstraint record. veCtxt.Token = TokenFromRid(rid, mdtGenericParamConstraint); veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetGenericParamConstraintRecord(rid, &pRecord)); // 1. GenericParamConstraint may contain zero or more rows. // (Nothing to check.) // 2. Each row shall have one, and only one, owner row in the GenericParamTable [ERROR] // (Nothing to check except owner not nil) tkOwner = pMiniMd->getOwnerOfGenericParamConstraint(pRecord); if(IsNilToken(tkOwner)) { REPORT_ERROR0(VLDTR_E_GPC_OWNERNIL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // 3. Each row in the GenericParam table shall own a separate row in the GenericParamConstraint table for each constraint that type parameter has [ERROR] // (Nothing to check) // 4.All of the rows in the GenericParamConstraint table that are owned by a given row in the GenericParamTable // shall form a contiguous range of rows [ERROR] //@NOTE: this check is (iterated over all rows) is quadratic in the (typically small) number of constraints { RID curRid = rid; GenericParamConstraintRec *pCurRecord; mdGenericParam tkCurOwner = tkOwner; // find the first preceding row with a distinct owner while (curRid > 1 && tkCurOwner == tkOwner) { curRid--; IfFailGo(pMiniMd->GetGenericParamConstraintRecord(curRid, &pCurRecord)); tkCurOwner = pMiniMd->getOwnerOfGenericParamConstraint(pCurRecord); }; // reject this row if there is some row preceding the current row with this owner while (curRid > 1) { curRid--; IfFailGo(pMiniMd->GetGenericParamConstraintRecord(curRid, &pCurRecord)); tkCurOwner = pMiniMd->getOwnerOfGenericParamConstraint(pCurRecord); if (tkCurOwner == tkOwner) { REPORT_ERROR1(VLDTR_E_GPC_NONCONTIGUOUS,tkOwner); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } }; } // 5. "At most one class constraint per GenericParam" --- no longer required. // 6. "Zero or more interface constraints per GenericParam" --- no longer required. tkConstraint = pMiniMd->getConstraintOfGenericParamConstraint(pRecord); // 7. There shall be no duplicates based upon Owner and Constraint { mdGenericParamConstraint tkDupGenericParamConstraint; hr = ImportHelper::FindGenericParamConstraintByOwnerAndConstraint(pMiniMd, tkOwner, tkConstraint, &tkDupGenericParamConstraint, rid); if (hr == S_OK) { REPORT_ERROR1(VLDTR_E_GPC_DUP, tkDupGenericParamConstraint); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (hr == CLDB_E_RECORD_NOTFOUND) hr = S_OK; else IfFailGo(hr); } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateGenericParamConstraint() //***************************************************************************** // Validate the given ImplMap. //***************************************************************************** HRESULT RegMeta::ValidateImplMap(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd for the scope. ImplMapRec *pRecord; VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. HRESULT hrModuleRef=S_OK; mdToken tkModuleRef; mdToken tkMember; USHORT usFlags; BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); #ifdef CACHE_IMPLMAP_VALIDATION_RESULT for(unsigned jjj=0; jjj<g_nValidated; jjj++) { if(g_rValidated[jjj].tok == (rid | 0x51000000)) return g_rValidated[jjj].hr; } #endif veCtxt.Token = rid; veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetImplMapRecord(rid, &pRecord)); if(pRecord == NULL) IfFailGo(E_FAIL); // ImplMap must have ModuleRef tkModuleRef = pMiniMd->getImportScopeOfImplMap(pRecord); if((TypeFromToken(tkModuleRef) != mdtModuleRef) || IsNilToken(tkModuleRef) || FAILED(hrModuleRef= ValidateModuleRef(RidFromToken(tkModuleRef)))) { REPORT_ERROR1(VLDTR_E_IMAP_BADMODREF, tkModuleRef); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // ImplMap must belong to FieldDef or MethodDef tkMember = pMiniMd->getMemberForwardedOfImplMap(pRecord); if((TypeFromToken(tkMember) != mdtFieldDef) && (TypeFromToken(tkMember) != mdtMethodDef)) { REPORT_ERROR1(VLDTR_E_IMAP_BADMEMBER, tkMember); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // ImplMap must have import name, unless ModuleRef has no name // (special case for C++ IJW methods) if(hrModuleRef != S_FALSE) { LPCSTR szName; // Import name. IfFailGo(pMiniMd->getImportNameOfImplMap(pRecord, &szName)); if((szName==NULL)||(*szName == 0)) { REPORT_ERROR0(VLDTR_E_IMAP_BADIMPORTNAME); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // ImplMap must have valid flags: // one value of pmCharSetMask - always so, no check needed (values: 0,2,4,6, mask=6) // one value of pmCallConvMask... // ...and it's not pmCallConvThiscall usFlags = pRecord->GetMappingFlags() & pmCallConvMask; if((usFlags < pmCallConvWinapi)||(usFlags > pmCallConvFastcall)) { REPORT_ERROR1(VLDTR_E_IMAP_BADCALLCONV, usFlags); SetVldtrCode(&hrSave, VLDTR_S_ERR); } ErrExit: #ifdef CACHE_IMPLMAP_VALIDATION_RESULT g_rValidated[g_nValidated].tok = rid | 0x51000000; g_rValidated[g_nValidated].hr = hrSave; g_nValidated++; #endif ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateImplMap() //***************************************************************************** // Validate the given FieldRVA. //***************************************************************************** HRESULT RegMeta::ValidateFieldRVA(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd for the scope. FieldRVARec *pRecord; VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. mdToken tkField; ULONG ulRVA; BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = rid; veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetFieldRVARecord(rid, &pRecord)); ulRVA = pRecord->GetRVA(); tkField = pMiniMd->getFieldOfFieldRVA(pRecord); /* if(ulRVA == 0) { REPORT_ERROR1(VLDTR_E_FRVA_ZERORVA, tkField); SetVldtrCode(&hrSave, VLDTR_S_ERR); } */ if((0==RidFromToken(tkField))||(TypeFromToken(tkField) != mdtFieldDef)||(!IsValidToken(tkField))) { REPORT_ERROR2(VLDTR_E_FRVA_BADFIELD, tkField, ulRVA); SetVldtrCode(&hrSave, VLDTR_S_ERR); } { RID N = pMiniMd->getCountFieldRVAs(); RID tmp; FieldRVARec* pRecTmp; for(tmp = rid+1; tmp <= N; tmp++) { IfFailGo(pMiniMd->GetFieldRVARecord(tmp, &pRecTmp)); if(tkField == pMiniMd->getFieldOfFieldRVA(pRecTmp)) { REPORT_ERROR2(VLDTR_E_FRVA_DUPFIELD, tkField, tmp); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateFieldRVA() //***************************************************************************** // Validate the given ENCLog. //***************************************************************************** HRESULT RegMeta::ValidateENCLog(RID rid) { return S_OK; } // RegMeta::ValidateENCLog() //***************************************************************************** // Validate the given ENCMap. //***************************************************************************** HRESULT RegMeta::ValidateENCMap(RID rid) { return S_OK; } // RegMeta::ValidateENCMap() //***************************************************************************** // Validate the given Assembly. //***************************************************************************** HRESULT RegMeta::ValidateAssembly(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd for the scope. AssemblyRec *pRecord; // Assembly record. CorAssemblyFlags dwFlags; // Assembly flags. LPCSTR szName; // Assembly Name. VEContext veCtxt; // Context structure. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BOOL invalidAssemblyFlags; // Whether the CorAssemblyFlags are valid. BOOL fIsV2Assembly = FALSE; BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); // Get the Assembly record. veCtxt.Token = TokenFromRid(rid, mdtAssembly); veCtxt.uOffset = 0; IfFailGo(pMiniMd->GetAssemblyRecord(rid, &pRecord)); // There can only be one Assembly record. if (rid > 1) { REPORT_ERROR0(VLDTR_E_AS_MULTI); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Do checks for name validity.. IfFailGo(pMiniMd->getNameOfAssembly(pRecord, &szName)); if (!*szName) { // Assembly Name is null. REPORT_ERROR0(VLDTR_E_AS_NAMENULL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { unsigned L = (unsigned)strlen(szName); if((*szName==' ')||strchr(szName,':') || strchr(szName,'\\') || strchr(szName, '/') || strchr(szName, ',') || strchr(szName, '\n') || strchr(szName, '\r') || ((L > 4)&&((!SString::_stricmp(&szName[L-4],".exe"))||(!SString::_stricmp(&szName[L-4],".dll"))))) { //Assembly name has path and/or extension REPORT_ERROR0(VLDTR_E_AS_BADNAME); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // Get the flags value for the Assembly. dwFlags = (CorAssemblyFlags) pMiniMd->getFlagsOfAssembly(pRecord); // Validate the flags invalidAssemblyFlags = dwFlags & (~(afPublicKey | afRetargetable | afPA_FullMask | afDebuggableAttributeMask | afContentType_Mask)); // Validate we only set a legal processor architecture flags // The processor architecture flags were introduced in CLR v2.0. // Note that METAMODEL_MINOR_VER_V2_0 is 0. GCC points out the comparison // is useless, so that part is commented out. fIsV2Assembly = (m_pStgdb->m_MiniMd.m_Schema.m_major >= METAMODEL_MAJOR_VER_V2_0 /* && m_pStgdb->m_MiniMd.m_Schema.m_minor >= METAMODEL_MINOR_VER_V2_0*/); if (fIsV2Assembly) { if ((dwFlags & afPA_Mask) > afPA_AMD64 && !IsAfPA_NoPlatform(dwFlags)) invalidAssemblyFlags = true; } else { if ((dwFlags & afPA_Mask) != 0) invalidAssemblyFlags = true; } if (!IsAfContentType_Default(dwFlags) && !IsAfContentType_WindowsRuntime(dwFlags)) { // Unknown ContentType value invalidAssemblyFlags = true; } if (invalidAssemblyFlags) { REPORT_ERROR1(VLDTR_E_AS_BADFLAGS, dwFlags); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Validate hash algorithm ID switch(pRecord->GetHashAlgId()) { case CALG_MD2: case CALG_MD4: case CALG_MD5: case CALG_SHA: //case CALG_SHA1: // same as CALG_SHA case CALG_MAC: case CALG_SSL3_SHAMD5: case CALG_HMAC: case 0: break; default: REPORT_ERROR1(VLDTR_E_AS_HASHALGID, pRecord->GetHashAlgId()); SetVldtrCode(&hrSave, VLDTR_S_WRN); } // Validate locale { LPCSTR szLocale; IfFailGo(pMiniMd->getLocaleOfAssembly(pRecord, &szLocale)); if(!_IsValidLocale(szLocale, fIsV2Assembly)) { REPORT_ERROR0(VLDTR_E_AS_BADLOCALE); SetVldtrCode(&hrSave, VLDTR_S_WRN); } } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateAssembly() //***************************************************************************** // Validate the given AssemblyProcessor. //***************************************************************************** HRESULT RegMeta::ValidateAssemblyProcessor(RID rid) { return S_OK; } // RegMeta::ValidateAssemblyProcessor() //***************************************************************************** // Validate the given AssemblyOS. //***************************************************************************** HRESULT RegMeta::ValidateAssemblyOS(RID rid) { return S_OK; } // RegMeta::ValidateAssemblyOS() //***************************************************************************** // Validate the given AssemblyRef. //***************************************************************************** HRESULT RegMeta::ValidateAssemblyRef(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd for the scope. AssemblyRefRec *pRecord; // Assembly record. LPCSTR szName; // AssemblyRef Name. VEContext veCtxt; // Context structure. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = TokenFromRid(rid, mdtAssemblyRef); veCtxt.uOffset = 0; // Get the AssemblyRef record. IfFailGo(pMiniMd->GetAssemblyRefRecord(rid, &pRecord)); // Do checks for name and alias validity. IfFailGo(pMiniMd->getNameOfAssemblyRef(pRecord, &szName)); if (!*szName) { // AssemblyRef Name is null. REPORT_ERROR0(VLDTR_E_AR_NAMENULL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { unsigned L = (unsigned)strlen(szName); if((*szName==' ')||strchr(szName,':') || strchr(szName,'\\') || strchr(szName, '/') || strchr(szName, ',') || strchr(szName, '\n') || strchr(szName, '\r') || ((L > 4)&&((!SString::_stricmp(&szName[L-4],".exe"))||(!SString::_stricmp(&szName[L-4],".dll"))))) { //Assembly name has path and/or extension REPORT_ERROR0(VLDTR_E_AS_BADNAME); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // Validate locale { LPCSTR szLocale; IfFailGo(pMiniMd->getLocaleOfAssemblyRef(pRecord, &szLocale)); BOOL fIsV2Assembly = (m_pStgdb->m_MiniMd.m_Schema.m_major >= METAMODEL_MAJOR_VER_V2_0 /* && m_pStgdb->m_MiniMd.m_Schema.m_minor >= METAMODEL_MINOR_VER_V2_0*/); if(!_IsValidLocale(szLocale, fIsV2Assembly)) { REPORT_ERROR0(VLDTR_E_AS_BADLOCALE); SetVldtrCode(&hrSave, VLDTR_S_WRN); } } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateAssemblyRef() //***************************************************************************** // Validate the given AssemblyRefProcessor. //***************************************************************************** HRESULT RegMeta::ValidateAssemblyRefProcessor(RID rid) { return S_OK; } // RegMeta::ValidateAssemblyRefProcessor() //***************************************************************************** // Validate the given AssemblyRefOS. //***************************************************************************** HRESULT RegMeta::ValidateAssemblyRefOS(RID rid) { return S_OK; } // RegMeta::ValidateAssemblyRefOS() //***************************************************************************** // Validate the given File. //***************************************************************************** HRESULT RegMeta::ValidateFile(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd for the scope. FileRec *pRecord; // File record. mdFile tkFile; // Duplicate File token. LPCSTR szName; // File Name. VEContext veCtxt; // Context structure. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = TokenFromRid(rid, mdtFile); veCtxt.uOffset = 0; // Get the File record. IfFailGo(pMiniMd->GetFileRecord(rid, &pRecord)); // Do checks for name validity. IfFailGo(pMiniMd->getNameOfFile(pRecord, &szName)); if (!*szName) { // File Name is null. REPORT_ERROR0(VLDTR_E_FILE_NAMENULL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { ULONG L = (ULONG)strlen(szName); if(L >= MAX_PATH_FNAME) { // Name too long REPORT_ERROR2(VLDTR_E_TD_NAMETOOLONG, L, (ULONG)(MAX_PATH_FNAME-1)); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Check for duplicates based on Name. hr = ImportHelper::FindFile(pMiniMd, szName, &tkFile, rid); if (hr == S_OK) { REPORT_ERROR1(VLDTR_E_FILE_DUP, tkFile); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (hr == CLDB_E_RECORD_NOTFOUND) hr = S_OK; else IfFailGo(hr); // File name must not be fully qualified. if(strchr(szName,':') || strchr(szName,'\\') || strchr(szName,'/')) { REPORT_ERROR0(VLDTR_E_FILE_NAMEFULLQLFD); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // File name must not be one of system names. char *sysname[6]={"con","aux","lpt","prn","null","com"}; char *syssymbol = "0123456789$:"; for(unsigned i=0; i<6; i++) { L = (ULONG)strlen(sysname[i]); if(!SString::_strnicmp(szName,sysname[i],L)) { if((szName[L]==0)|| strchr(syssymbol,szName[L])) { REPORT_ERROR0(VLDTR_E_FILE_SYSNAME); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } } } } if (pRecord->GetFlags() & (~0x00000003)) { REPORT_ERROR1(VLDTR_E_FILE_BADFLAGS, pRecord->GetFlags()); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Validate hash value { const BYTE *pbHashValue = NULL; ULONG cbHashValue; IfFailGo(m_pStgdb->m_MiniMd.getHashValueOfFile(pRecord, &pbHashValue, &cbHashValue)); if ((pbHashValue == NULL) || (cbHashValue == 0)) { REPORT_ERROR0(VLDTR_E_FILE_NULLHASH); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // Validate that the name is not the same as the file containing // the manifest. // File name must be a valid file name. // Each ModuleRef in the assembly must have a corresponding File table entry. hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateFile() //***************************************************************************** // Validate the given ExportedType. //***************************************************************************** HRESULT RegMeta::ValidateExportedType(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd for the scope. ExportedTypeRec *pRecord; // ExportedType record. mdExportedType tkExportedType; // Duplicate ExportedType. mdToken tkImpl; // Implementation token mdToken tkTypeDef; // TypeDef token LPCSTR szName; // ExportedType Name. LPCSTR szNamespace; // ExportedType Namespace. VEContext veCtxt; // Context structure. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = TokenFromRid(rid, mdtExportedType); veCtxt.uOffset = 0; // Get the ExportedType record. IfFailGo(pMiniMd->GetExportedTypeRecord(rid, &pRecord)); tkImpl = pMiniMd->getImplementationOfExportedType(pRecord); tkTypeDef = pRecord->GetTypeDefId(); if ((TypeFromToken(tkImpl) == mdtFile) && IsNilToken(tkTypeDef)) { // Report 'No TypeDefId' warning only for types exported from other modules (do not report it for // type forwarders) REPORT_ERROR0(VLDTR_E_CT_NOTYPEDEFID); SetVldtrCode(&hrSave, VLDTR_S_WRN); } // Do checks for name validity. IfFailGo(pMiniMd->getTypeNameOfExportedType(pRecord, &szName)); IfFailGo(pMiniMd->getTypeNamespaceOfExportedType(pRecord, &szNamespace)); if (!*szName) { // ExportedType Name is null. REPORT_ERROR0(VLDTR_E_CT_NAMENULL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { if(!strcmp(szName,COR_DELETED_NAME_A)) goto ErrExit; ULONG L = (ULONG)(strlen(szName)+strlen(szNamespace)); if(L >= MAX_CLASSNAME_LENGTH) { // Name too long REPORT_ERROR2(VLDTR_E_TD_NAMETOOLONG, L, (ULONG)(MAX_CLASSNAME_LENGTH-1)); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Check for duplicates based on Name and Enclosing ExportedType. hr = ImportHelper::FindExportedType(pMiniMd, szNamespace, szName, tkImpl, &tkExportedType, rid); if (hr == S_OK) { REPORT_ERROR1(VLDTR_E_CT_DUP, tkExportedType); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (hr == CLDB_E_RECORD_NOTFOUND) hr = S_OK; else IfFailGo(hr); // Check for duplicate TypeDef based on Name/NameSpace - only for top-level ExportedTypes. if(TypeFromToken(tkImpl)==mdtFile) { mdToken tkTypeDef2; hr = ImportHelper::FindTypeDefByName(pMiniMd, szNamespace, szName, mdTypeDefNil, &tkTypeDef2, 0); if (hr == S_OK) { REPORT_ERROR1(VLDTR_E_CT_DUPTDNAME, tkTypeDef2); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (hr == CLDB_E_RECORD_NOTFOUND) hr = S_OK; else IfFailGo(hr); } } // Check if flag value is valid { DWORD dwFlags = pRecord->GetFlags(); DWORD dwInvalidMask, dwExtraBits; dwInvalidMask = (DWORD)~(tdVisibilityMask | tdLayoutMask | tdClassSemanticsMask | tdAbstract | tdSealed | tdSpecialName | tdImport | tdSerializable | tdForwarder | tdStringFormatMask | tdBeforeFieldInit | tdReservedMask); // check for extra bits dwExtraBits = dwFlags & dwInvalidMask; if(!dwExtraBits) { // if no extra bits, check layout dwExtraBits = dwFlags & tdLayoutMask; if(dwExtraBits != tdLayoutMask) { // layout OK, check string format dwExtraBits = dwFlags & tdStringFormatMask; if(dwExtraBits != tdStringFormatMask) dwExtraBits = 0; } } if(dwExtraBits) { REPORT_ERROR1(VLDTR_E_TD_EXTRAFLAGS, dwExtraBits); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } if(IsNilToken(tkImpl) || ((TypeFromToken(tkImpl) != mdtFile)&&(TypeFromToken(tkImpl) != mdtExportedType)&&(TypeFromToken(tkImpl) != mdtAssemblyRef)) || (!IsValidToken(tkImpl))) { REPORT_ERROR1(VLDTR_E_CT_BADIMPL, tkImpl); SetVldtrCode(&hrSave, VLDTR_S_ERR); } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateExportedType() //***************************************************************************** // Validate the given ManifestResource. //***************************************************************************** HRESULT RegMeta::ValidateManifestResource(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd for the scope. ManifestResourceRec *pRecord; // ManifestResource record. LPCSTR szName; // ManifestResource Name. DWORD dwFlags; // ManifestResource flags. mdManifestResource tkmar; // Duplicate ManifestResource. VEContext veCtxt; // Context structure. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. mdToken tkImplementation; BOOL bIsValidImplementation = TRUE; BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = TokenFromRid(rid, mdtManifestResource); veCtxt.uOffset = 0; // Get the ManifestResource record. IfFailGo(pMiniMd->GetManifestResourceRecord(rid, &pRecord)); // Do checks for name validity. IfFailGo(pMiniMd->getNameOfManifestResource(pRecord, &szName)); if (!*szName) { // ManifestResource Name is null. REPORT_ERROR0(VLDTR_E_MAR_NAMENULL); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { // Check for duplicates based on Name. hr = ImportHelper::FindManifestResource(pMiniMd, szName, &tkmar, rid); if (hr == S_OK) { REPORT_ERROR1(VLDTR_E_MAR_DUP, tkmar); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else if (hr == CLDB_E_RECORD_NOTFOUND) hr = S_OK; else IfFailGo(hr); } // Get the flags of the ManifestResource. dwFlags = pMiniMd->getFlagsOfManifestResource(pRecord); if(dwFlags &(~0x00000003)) { REPORT_ERROR1(VLDTR_E_MAR_BADFLAGS, dwFlags); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Visibility of ManifestResource flags must either be public or private. if (!IsMrPublic(dwFlags) && !IsMrPrivate(dwFlags)) { REPORT_ERROR0(VLDTR_E_MAR_NOTPUBPRIV); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Implementation must be Nil or valid AssemblyRef or File tkImplementation = pMiniMd->getImplementationOfManifestResource(pRecord); if(!IsNilToken(tkImplementation)) { switch(TypeFromToken(tkImplementation)) { case mdtAssemblyRef: bIsValidImplementation = IsValidToken(tkImplementation); break; case mdtFile: if((bIsValidImplementation = IsValidToken(tkImplementation))) { // if file not PE, offset must be 0 FileRec *pFR; IfFailGo(pMiniMd->GetFileRecord(RidFromToken(tkImplementation), &pFR)); if(IsFfContainsNoMetaData(pFR->GetFlags()) && pRecord->GetOffset()) { REPORT_ERROR1(VLDTR_E_MAR_BADOFFSET, tkImplementation); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } break; default: bIsValidImplementation = FALSE; } } if(!bIsValidImplementation) { REPORT_ERROR1(VLDTR_E_MAR_BADIMPL, tkImplementation); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Validate the Offset into the PE file. hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateManifestResource() //***************************************************************************** // Validate the given NestedClass. //***************************************************************************** HRESULT RegMeta::ValidateNestedClass(RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); // MiniMd for the scope. NestedClassRec *pRecord; // NestedClass record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save the current state. VEContext veCtxt; // Context structure. mdToken tkNested; mdToken tkEncloser; BEGIN_ENTRYPOINT_NOTHROW; memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = rid; veCtxt.uOffset = 0; // Get the NestedClass record. IfFailGo(pMiniMd->GetNestedClassRecord(rid, &pRecord)); tkNested = pMiniMd->getNestedClassOfNestedClass(pRecord); tkEncloser = pMiniMd->getEnclosingClassOfNestedClass(pRecord); // Nested must be valid TypeDef if((TypeFromToken(tkNested) != mdtTypeDef) || !IsValidToken(tkNested)) { REPORT_ERROR1(VLDTR_E_NC_BADNESTED, tkNested); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Encloser must be valid TypeDef if((TypeFromToken(tkEncloser) != mdtTypeDef) || !IsValidToken(tkEncloser)) { REPORT_ERROR1(VLDTR_E_NC_BADENCLOSER, tkEncloser); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Check for duplicates { RID N = pMiniMd->getCountNestedClasss(); RID tmp; NestedClassRec* pRecTmp; mdToken tkEncloserTmp; for(tmp = rid+1; tmp <= N; tmp++) { IfFailGo(pMiniMd->GetNestedClassRecord(tmp, &pRecTmp)); if(tkNested == pMiniMd->getNestedClassOfNestedClass(pRecTmp)) { if(tkEncloser == (tkEncloserTmp = pMiniMd->getEnclosingClassOfNestedClass(pRecTmp))) { REPORT_ERROR1(VLDTR_E_NC_DUP, tmp); SetVldtrCode(&hrSave, VLDTR_S_ERR); } else { REPORT_ERROR3(VLDTR_E_NC_DUPENCLOSER, tkNested, tkEncloser, tkEncloserTmp); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateLocalVariable() //***************************************************************************** // Given a Table ID and a Row ID, validate all the columns contain meaningful // values given the column definitions. Validate that the offsets into the // different pools are valid, the rids are within range and the coded tokens // are valid. Every failure here is considered an error. //***************************************************************************** HRESULT RegMeta::ValidateRecord(ULONG ixTbl, RID rid) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save the current state. ULONG ulCount; // Count of records in the table. ULONG ulRawColVal; // Raw value of the column. void *pRow; // Row with the data. CMiniTableDef *pTbl; // Table definition. CMiniColDef *pCol; // Column definition. const CCodedTokenDef *pCdTkn; // Coded token definition. ULONG ix; // Index into the array of coded tokens. BEGIN_ENTRYPOINT_NOTHROW; // Get the table definition. pTbl = &pMiniMd->m_TableDefs[ixTbl]; // Get the row. We may assume that the Row pointer we get back from // this call is correct since we do the verification on the Record // pools for each table during the open sequence. The only place // this is not valid is for Dynamic IL and we don't do this // verification in that case since we go through IMetaData* APIs // in that case and it should all be consistent. IfFailGo(m_pStgdb->m_MiniMd.getRow(ixTbl, rid, &pRow)); for (ULONG ixCol = 0; ixCol < pTbl->m_cCols; ixCol++) { // Get the column definition. pCol = &pTbl->m_pColDefs[ixCol]; // Get the raw value stored in the column. getIX currently doesn't // handle byte sized fields, but there are some BYTE fields in the // MetaData. So using the conditional to access BYTE fields. if (pCol->m_cbColumn == 1) ulRawColVal = pMiniMd->getI1(pRow, *pCol); else ulRawColVal = pMiniMd->getIX(pRow, *pCol); // Do some basic checks on the non-absurdity of the value stored in the // column. if (IsRidType(pCol->m_Type)) { // Verify that the RID is within range. _ASSERTE(pCol->m_Type < pMiniMd->GetCountTables()); ulCount = pMiniMd->GetCountRecs(pCol->m_Type); // For records storing rids to pointer tables, the stored value may // be one beyond the last record. if (IsTblPtr(pCol->m_Type, ixTbl)) ulCount++; if (ulRawColVal > ulCount) { VEContext veCtxt; memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = 0; veCtxt.uOffset = 0; REPORT_ERROR3(VLDTR_E_RID_OUTOFRANGE, ixTbl, ixCol, rid); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } else if (IsCodedTokenType(pCol->m_Type)) { // Verify that the Coded token and rid are valid. pCdTkn = &g_CodedTokens[pCol->m_Type - iCodedToken]; ix = ulRawColVal & ~(-1 << CMiniMdRW::m_cb[pCdTkn->m_cTokens]); if (ix >= pCdTkn->m_cTokens) { VEContext veCtxt; memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = 0; veCtxt.uOffset = 0; REPORT_ERROR3(VLDTR_E_CDTKN_OUTOFRANGE, ixTbl, ixCol, rid); SetVldtrCode(&hrSave, VLDTR_S_ERR); } ulCount = pMiniMd->GetCountRecs(TypeFromToken(pCdTkn->m_pTokens[ix]) >> 24); if ( (ulRawColVal >> CMiniMdRW::m_cb[pCdTkn->m_cTokens]) > ulCount) { VEContext veCtxt; memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = 0; veCtxt.uOffset = 0; REPORT_ERROR3(VLDTR_E_CDRID_OUTOFRANGE, ixTbl, ixCol, rid); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } else if (IsHeapType(pCol->m_Type)) { // Verify that the offsets for the Heap type fields are valid offsets // into the heaps. switch (pCol->m_Type) { case iSTRING: if (!pMiniMd->m_StringHeap.IsValidIndex(ulRawColVal)) { VEContext veCtxt; memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = 0; veCtxt.uOffset = 0; REPORT_ERROR3(VLDTR_E_STRING_INVALID, ixTbl, ixCol, rid); SetVldtrCode(&hrSave, VLDTR_S_ERR); } break; case iGUID: if (ulRawColVal == 0) { // GUID value 0 is valid value, though it's invalid GUID heap index break; } if (!pMiniMd->m_GuidHeap.IsValidIndex(ulRawColVal)) { VEContext veCtxt; memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = 0; veCtxt.uOffset = 0; REPORT_ERROR3(VLDTR_E_GUID_INVALID, ixTbl, ixCol, rid); SetVldtrCode(&hrSave, VLDTR_S_ERR); } break; case iBLOB: if (! pMiniMd->m_BlobHeap.IsValidIndex(ulRawColVal)) { VEContext veCtxt; memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = 0; veCtxt.uOffset = 0; REPORT_ERROR3(VLDTR_E_BLOB_INVALID, ixTbl, ixCol, rid); SetVldtrCode(&hrSave, VLDTR_S_ERR); } break; default: _ASSERTE(!"Invalid heap type encountered!"); } } else { // Not much checking that can be done on the fixed type in a generic sense. _ASSERTE (IsFixedType(pCol->m_Type)); } hr = hrSave; } ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateRecord() //***************************************************************************** // This function validates that the given Method signature is consistent as per // the compression scheme. //***************************************************************************** HRESULT RegMeta::ValidateSigCompression( mdToken tk, // [IN] Token whose signature needs to be validated. PCCOR_SIGNATURE pbSig, // [IN] Signature. ULONG cbSig) // [IN] Size in bytes of the signature. { VEContext veCtxt; // Context record. ULONG ulCurByte = 0; // Current index into the signature. ULONG ulSize; // Size of uncompressed data at each point. HRESULT hr = S_OK; // Value returned. memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = tk; veCtxt.uOffset = 0; // Check for NULL signature. if (!cbSig) { REPORT_ERROR0(VLDTR_E_SIGNULL); SetVldtrCode(&hr, VLDTR_S_ERR); goto ErrExit; } // Walk through the signature. At each point make sure there is enough // room left in the signature based on the encoding in the current byte. while (cbSig - ulCurByte) { _ASSERTE(ulCurByte <= cbSig); // Get next chunk of uncompressed data size. if ((ulSize = CorSigUncompressedDataSize(pbSig)) > (cbSig - ulCurByte)) { REPORT_ERROR1(VLDTR_E_SIGNODATA, ulCurByte+1); SetVldtrCode(&hr, VLDTR_S_ERR); goto ErrExit; } // Go past this chunk. ulCurByte += ulSize; CorSigUncompressData(pbSig); } ErrExit: return hr; } // RegMeta::ValidateSigCompression() //***************************************************************************** // This function validates one argument given an offset into the signature // where the argument begins. This function assumes that the signature is well // formed as far as the compression scheme is concerned. //***************************************************************************** //@GENERICS: todo: reject uninstantiated generic types used as types. #ifdef _PREFAST_ #pragma warning(push) #pragma warning(disable:21000) // Suppress PREFast warning about overly large function #endif HRESULT RegMeta::ValidateOneArg( mdToken tk, // [IN] Token whose signature is being processed. PCCOR_SIGNATURE &pbSig, // [IN] Pointer to the beginning of argument. ULONG cbSig, // [IN] Size in bytes of the full signature. ULONG *pulCurByte, // [IN/OUT] Current offset into the signature.. ULONG *pulNSentinels, // [IN/OUT] Number of sentinels BOOL bNoVoidAllowed) // [IN] Flag indicating whether "void" is disallowed for this arg { ULONG ulElementType; // Current element type being processed. ULONG ulElemSize; // Size of the element type. mdToken token; // Embedded token. ULONG ulArgCnt; // Argument count for function pointer. ULONG ulRank; // Rank of the array. ULONG ulSizes; // Count of sized dimensions of the array. ULONG ulLbnds; // Count of lower bounds of the array. ULONG ulTkSize; // Token size. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BOOL bRepeat = TRUE; // MODOPT and MODREQ belong to the arg after them BOOL bByRefForbidden = FALSE;// ByRef is not allowed for fields BEGIN_ENTRYPOINT_NOTHROW; switch(TypeFromToken(tk)) { case mdtFieldDef: bByRefForbidden = TRUE; break; case mdtName: tk = TokenFromRid(RidFromToken(tk),mdtFieldDef); // Field type can be a FNPTR with a sig containing ByRefs. // So we change the token type not to be mdtFieldDef and thus allow ByRefs, // but the token needs to be restored to its original type for reporting break; } _ASSERTE (pulCurByte); memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = tk; veCtxt.uOffset = 0; while(bRepeat) { bRepeat = FALSE; // Validate that the argument is not missing. _ASSERTE(*pulCurByte <= cbSig); if (cbSig == *pulCurByte) { hr = VLDTR_E_SIG_MISSARG; goto ErrExit; } // Get the element type. *pulCurByte += (ulElemSize = CorSigUncompressedDataSize(pbSig)); ulElementType = CorSigUncompressData(pbSig); // Walk past all the modifier types. while (ulElementType & ELEMENT_TYPE_MODIFIER) { _ASSERTE(*pulCurByte <= cbSig); if(ulElementType == ELEMENT_TYPE_SENTINEL) { if(pulNSentinels) *pulNSentinels+=1; if(TypeFromToken(tk) == mdtMethodDef) { REPORT_ERROR0(VLDTR_E_SIG_SENTINMETHODDEF); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if (cbSig == *pulCurByte) { REPORT_ERROR0(VLDTR_E_SIG_LASTSENTINEL); SetVldtrCode(&hrSave, VLDTR_S_ERR); goto ErrExit; } } if (cbSig == *pulCurByte) { REPORT_ERROR2(VLDTR_E_SIG_MISSELTYPE, ulElementType, *pulCurByte + 1); SetVldtrCode(&hr, hrSave); goto ErrExit; } *pulCurByte += (ulElemSize = CorSigUncompressedDataSize(pbSig)); ulElementType = CorSigUncompressData(pbSig); } switch (ulElementType) { case ELEMENT_TYPE_VOID: if(bNoVoidAllowed) { IfBreakGo(m_pVEHandler->VEHandler(VLDTR_E_SIG_BADVOID, veCtxt, 0)); SetVldtrCode(&hrSave, VLDTR_S_ERR); } case ELEMENT_TYPE_BOOLEAN: case ELEMENT_TYPE_CHAR: case ELEMENT_TYPE_I1: case ELEMENT_TYPE_U1: case ELEMENT_TYPE_I2: case ELEMENT_TYPE_U2: case ELEMENT_TYPE_I4: case ELEMENT_TYPE_U4: case ELEMENT_TYPE_I8: case ELEMENT_TYPE_U8: case ELEMENT_TYPE_R4: case ELEMENT_TYPE_R8: case ELEMENT_TYPE_STRING: case ELEMENT_TYPE_OBJECT: case ELEMENT_TYPE_TYPEDBYREF: case ELEMENT_TYPE_U: case ELEMENT_TYPE_I: break; case ELEMENT_TYPE_BYREF: //fallthru if(bByRefForbidden) { IfBreakGo(m_pVEHandler->VEHandler(VLDTR_E_SIG_BYREFINFIELD, veCtxt, 0)); SetVldtrCode(&hr, hrSave); } case ELEMENT_TYPE_PTR: // Validate the referenced type. IfFailGo(ValidateOneArg(tk, pbSig, cbSig, pulCurByte,pulNSentinels,FALSE)); if (hr != S_OK) SetVldtrCode(&hrSave, hr); break; case ELEMENT_TYPE_PINNED: case ELEMENT_TYPE_SZARRAY: // Validate the referenced type. IfFailGo(ValidateOneArg(tk, pbSig, cbSig, pulCurByte,pulNSentinels,TRUE)); if (hr != S_OK) SetVldtrCode(&hrSave, hr); break; case ELEMENT_TYPE_VALUETYPE: //fallthru case ELEMENT_TYPE_CLASS: case ELEMENT_TYPE_CMOD_OPT: case ELEMENT_TYPE_CMOD_REQD: // See if the token is missing. _ASSERTE(*pulCurByte <= cbSig); if (cbSig == *pulCurByte) { REPORT_ERROR1(VLDTR_E_SIG_MISSTKN, ulElementType); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } // See if the token is a valid token. ulTkSize = CorSigUncompressedDataSize(pbSig); token = CorSigUncompressToken(pbSig); if (!IsValidToken(token)) { REPORT_ERROR2(VLDTR_E_SIG_TKNBAD, token, *pulCurByte); SetVldtrCode(&hrSave, VLDTR_S_ERR); *pulCurByte += ulTkSize; break; } *pulCurByte += ulTkSize; if ((ulElementType == ELEMENT_TYPE_CLASS) || (ulElementType == ELEMENT_TYPE_VALUETYPE)) { // Check for long-form encoding CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); LPCSTR szName = ""; // token's Name. LPCSTR szNameSpace = ""; // token's NameSpace. // Check for TypeDef or TypeRef // To prevent cycles in metadata, token must not be a TypeSpec. if ((TypeFromToken(token) != mdtTypeRef) && (TypeFromToken(token) != mdtTypeDef)) { REPORT_ERROR2(VLDTR_E_SIG_BADTOKTYPE, token, *pulCurByte); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if (TypeFromToken(token) == mdtTypeRef) { TypeRefRec *pTokenRec; IfFailGo(pMiniMd->GetTypeRefRecord(RidFromToken(token), &pTokenRec)); mdToken tkResScope = pMiniMd->getResolutionScopeOfTypeRef(pTokenRec); if (RidFromToken(tkResScope) && (TypeFromToken(tkResScope) == mdtAssemblyRef)) { AssemblyRefRec * pARRec; IfFailGo(pMiniMd->GetAssemblyRefRecord(RidFromToken(tkResScope), &pARRec)); LPCSTR szAssemblyRefName; IfFailGo(pMiniMd->getNameOfAssemblyRef(pARRec, &szAssemblyRefName)); if((0 == SString::_stricmp("mscorlib", szAssemblyRefName)) || (0 == SString::_stricmp("System.Runtime", szAssemblyRefName))) { IfFailGo(pMiniMd->getNamespaceOfTypeRef(pTokenRec, &szNameSpace)); IfFailGo(pMiniMd->getNameOfTypeRef(pTokenRec, &szName)); } } } else if (TypeFromToken(token) == mdtTypeDef) { TypeDefRec *pTokenRec; IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(token), &pTokenRec)); if(g_fValidatingMscorlib) // otherwise don't even bother checking the name { IfFailGo(pMiniMd->getNameOfTypeDef(pTokenRec, &szName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pTokenRec, &szNameSpace)); } // while at it, check if token is indeed a class (valuetype) BOOL bValueType = FALSE; if(!IsTdInterface(pTokenRec->GetFlags())) { mdToken tkExtends = pMiniMd->getExtendsOfTypeDef(pTokenRec); if(RidFromToken(tkExtends)) { LPCSTR szExtName = ""; // parent's Name. LPCSTR szExtNameSpace = ""; // parent's NameSpace. if(TypeFromToken(tkExtends)==mdtTypeRef) { TypeRefRec *pExtRec; IfFailGo(pMiniMd->GetTypeRefRecord(RidFromToken(tkExtends), &pExtRec)); mdToken tkResScope = pMiniMd->getResolutionScopeOfTypeRef(pExtRec); if(RidFromToken(tkResScope) && (TypeFromToken(tkResScope)==mdtAssemblyRef)) { AssemblyRefRec *pARRec; IfFailGo(pMiniMd->GetAssemblyRefRecord(RidFromToken(tkResScope), &pARRec)); LPCSTR szAssemblyRefName; IfFailGo(pMiniMd->getNameOfAssemblyRef(pARRec, &szAssemblyRefName)); if((0 == SString::_stricmp("mscorlib", szAssemblyRefName)) || (0 == SString::_stricmp("System.Runtime", szAssemblyRefName))) { IfFailGo(pMiniMd->getNamespaceOfTypeRef(pExtRec, &szExtNameSpace)); IfFailGo(pMiniMd->getNameOfTypeRef(pExtRec, &szExtName)); } } } else if(TypeFromToken(tkExtends)==mdtTypeDef) { if(g_fValidatingMscorlib) // otherwise don't even bother checking the name { TypeDefRec *pExtRec; IfFailGo(pMiniMd->GetTypeDefRecord(RidFromToken(tkExtends), &pExtRec)); IfFailGo(pMiniMd->getNameOfTypeDef(pExtRec, &szExtName)); IfFailGo(pMiniMd->getNamespaceOfTypeDef(pExtRec, &szExtNameSpace)); } } if(0 == strcmp(szExtNameSpace,BASE_NAMESPACE)) { if(0==strcmp(szExtName,BASE_ENUM_CLASSNAME)) bValueType = TRUE; else if(0==strcmp(szExtName,BASE_VTYPE_CLASSNAME)) { bValueType = (strcmp(szNameSpace,BASE_NAMESPACE) || strcmp(szName,BASE_ENUM_CLASSNAME)); } } } } if(bValueType != (ulElementType == ELEMENT_TYPE_VALUETYPE)) { REPORT_ERROR2(VLDTR_E_SIG_TOKTYPEMISMATCH, token, *pulCurByte); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } if(0 == strcmp(szNameSpace,BASE_NAMESPACE)) { for(unsigned jjj = 0; jjj < g_NumSigLongForms; jjj++) { if(0 == strcmp(szName,g_SigLongFormName[jjj])) { REPORT_ERROR2(VLDTR_E_SIG_LONGFORM, token, *pulCurByte); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } } } } else // i.e. if(ELEMENT_TYPE_CMOD_OPT || ELEMENT_TYPE_CMOD_REQD) bRepeat = TRUE; // go on validating, we're not done with this arg break; case ELEMENT_TYPE_FNPTR: // Validate that calling convention is present. _ASSERTE(*pulCurByte <= cbSig); if (cbSig == *pulCurByte) { REPORT_ERROR1(VLDTR_E_SIG_MISSFPTR, *pulCurByte + 1); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } // Consume calling convention. *pulCurByte += CorSigUncompressedDataSize(pbSig); CorSigUncompressData(pbSig); // Validate that argument count is present. _ASSERTE(*pulCurByte <= cbSig); if (cbSig == *pulCurByte) { REPORT_ERROR1(VLDTR_E_SIG_MISSFPTRARGCNT, *pulCurByte + 1); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } // Consume argument count. *pulCurByte += CorSigUncompressedDataSize(pbSig); ulArgCnt = CorSigUncompressData(pbSig); // Checking the signature, ByRefs OK if(bByRefForbidden) tk = TokenFromRid(RidFromToken(tk),mdtName); // Validate and consume return type. IfFailGo(ValidateOneArg(tk, pbSig, cbSig, pulCurByte,NULL,FALSE)); if (hr != S_OK) { SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } // Validate and consume the arguments. while(ulArgCnt--) { IfFailGo(ValidateOneArg(tk, pbSig, cbSig, pulCurByte,NULL,TRUE)); if (hr != S_OK) { SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } } break; case ELEMENT_TYPE_ARRAY: // Validate and consume the base type. IfFailGo(ValidateOneArg(tk, pbSig, cbSig, pulCurByte,pulNSentinels,TRUE)); // Validate that the rank is present. _ASSERTE(*pulCurByte <= cbSig); if (cbSig == *pulCurByte) { REPORT_ERROR1(VLDTR_E_SIG_MISSRANK, *pulCurByte + 1); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } // Consume the rank. *pulCurByte += CorSigUncompressedDataSize(pbSig); ulRank = CorSigUncompressData(pbSig); // Process the sizes. if (ulRank) { // Validate that the count of sized-dimensions is specified. _ASSERTE(*pulCurByte <= cbSig); if (cbSig == *pulCurByte) { REPORT_ERROR1(VLDTR_E_SIG_MISSNSIZE, *pulCurByte + 1); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } // Consume the count of sized dimensions. *pulCurByte += CorSigUncompressedDataSize(pbSig); ulSizes = CorSigUncompressData(pbSig); // Loop over the sizes. while (ulSizes--) { // Validate the current size. _ASSERTE(*pulCurByte <= cbSig); if (cbSig == *pulCurByte) { REPORT_ERROR1(VLDTR_E_SIG_MISSSIZE, *pulCurByte + 1); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } // Consume the current size. *pulCurByte += CorSigUncompressedDataSize(pbSig); CorSigUncompressData(pbSig); } // Validate that the count of lower bounds is specified. _ASSERTE(*pulCurByte <= cbSig); if (cbSig == *pulCurByte) { REPORT_ERROR1(VLDTR_E_SIG_MISSNLBND, *pulCurByte + 1); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } // Consume the count of lower bound. *pulCurByte += CorSigUncompressedDataSize(pbSig); ulLbnds = CorSigUncompressData(pbSig); // Loop over the lower bounds. while (ulLbnds--) { // Validate the current lower bound. _ASSERTE(*pulCurByte <= cbSig); if (cbSig == *pulCurByte) { REPORT_ERROR1(VLDTR_E_SIG_MISSLBND, *pulCurByte + 1); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } // Consume the current size. *pulCurByte += CorSigUncompressedDataSize(pbSig); CorSigUncompressData(pbSig); } } break; case ELEMENT_TYPE_VAR: case ELEMENT_TYPE_MVAR: // Consume index. *pulCurByte += CorSigUncompressedDataSize(pbSig); CorSigUncompressData(pbSig); break; case ELEMENT_TYPE_GENERICINST: { PCCOR_SIGNATURE pbGenericTypeSig = pbSig; BOOL fCheckArity = FALSE; ULONG ulGenericArity = 0; // Validate and consume the type constructor IfFailGo(ValidateOneArg(tk, pbSig, cbSig, pulCurByte, NULL, TRUE)); // Extract its arity { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); switch(CorSigUncompressElementType(pbGenericTypeSig)) { case ELEMENT_TYPE_VALUETYPE: case ELEMENT_TYPE_CLASS: { mdToken tkGenericType = CorSigUncompressToken(pbGenericTypeSig); if (TypeFromToken(tkGenericType) == mdtTypeDef) { HENUMInternal hEnumTyPars; hr = pMiniMd->FindGenericParamHelper(tkGenericType, &hEnumTyPars); if (SUCCEEDED(hr)) { IfFailGo(HENUMInternal::GetCount(&hEnumTyPars,&ulGenericArity)); HENUMInternal::ClearEnum(&hEnumTyPars); fCheckArity = TRUE; } ; } // for a mdtTypeRef, don't check anything until load time break; } default: break; } } // Consume argument count. if (cbSig == *pulCurByte) { REPORT_ERROR1(VLDTR_E_SIG_MISSARITY, *pulCurByte + 1); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } *pulCurByte += CorSigUncompressedDataSize(pbSig); ulArgCnt = CorSigUncompressData(pbSig); if (ulArgCnt == 0) { REPORT_ERROR1(VLDTR_E_SIG_ARITYZERO,*pulCurByte); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if (fCheckArity && ulArgCnt != ulGenericArity) { REPORT_ERROR3(VLDTR_E_SIG_ARITYMISMATCH,ulGenericArity,ulArgCnt,*pulCurByte); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Validate and consume the arguments. while(ulArgCnt--) { PCCOR_SIGNATURE pbTypeArg = pbSig; ULONG ulTypeArgByte = *pulCurByte; IfFailGo(ValidateOneArg(tk, pbSig, cbSig, pulCurByte, NULL, TRUE)); if (hr != S_OK) { SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } // reject byref-like args switch (CorSigUncompressData(pbTypeArg)) { case ELEMENT_TYPE_TYPEDBYREF: case ELEMENT_TYPE_BYREF: { REPORT_ERROR1(VLDTR_E_SIG_BYREFINST, ulTypeArgByte); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } default: break; } } break; } case ELEMENT_TYPE_SENTINEL: // this case never works because all modifiers are skipped before switch if(TypeFromToken(tk) == mdtMethodDef) { REPORT_ERROR0(VLDTR_E_SIG_SENTINMETHODDEF); SetVldtrCode(&hrSave, VLDTR_S_ERR); } break; default: REPORT_ERROR2(VLDTR_E_SIG_BADELTYPE, ulElementType, *pulCurByte - ulElemSize); SetVldtrCode(&hrSave, VLDTR_S_ERR); break; } // switch (ulElementType) } // end while(bRepeat) hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateOneArg() #ifdef _PREFAST_ #pragma warning(pop) #endif //***************************************************************************** // This function validates the given Method signature. This function works // with Method signature for both the MemberRef and MethodDef. //***************************************************************************** HRESULT RegMeta::ValidateMethodSig( mdToken tk, // [IN] Token whose signature needs to be validated. PCCOR_SIGNATURE pbSig, // [IN] Signature. ULONG cbSig, // [IN] Size in bytes of the signature. DWORD dwFlags) // [IN] Method flags. { ULONG ulCurByte = 0; // Current index into the signature. ULONG ulCallConv; // Calling convention. ULONG ulArgCount; // Count of arguments. ULONG ulTyArgCount; // Count of type arguments. ULONG i; // Looping index. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. ULONG ulNSentinels = 0; BEGIN_ENTRYPOINT_NOTHROW; _ASSERTE(TypeFromToken(tk) == mdtMethodDef || TypeFromToken(tk) == mdtMemberRef); memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = tk; veCtxt.uOffset = 0; // Validate the signature is well-formed with respect to the compression // scheme. If this fails, no further validation needs to be done. if ((hr = ValidateSigCompression(tk, pbSig, cbSig)) != S_OK) goto ErrExit; // Validate the calling convention. ulCurByte += CorSigUncompressedDataSize(pbSig); ulCallConv = CorSigUncompressData(pbSig); i = ulCallConv & IMAGE_CEE_CS_CALLCONV_MASK; if ((i != IMAGE_CEE_CS_CALLCONV_DEFAULT)&&( i != IMAGE_CEE_CS_CALLCONV_VARARG) || (ulCallConv & IMAGE_CEE_CS_CALLCONV_EXPLICITTHIS)) { REPORT_ERROR1(VLDTR_E_MD_BADCALLINGCONV, ulCallConv); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if (TypeFromToken(tk) == mdtMethodDef) // MemberRefs have no flags available { // If HASTHIS is set on the calling convention, the method should not be static. if ((ulCallConv & IMAGE_CEE_CS_CALLCONV_HASTHIS) && IsMdStatic(dwFlags)) { REPORT_ERROR1(VLDTR_E_MD_THISSTATIC, ulCallConv); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // If HASTHIS is not set on the calling convention, the method should be static. if (!(ulCallConv & IMAGE_CEE_CS_CALLCONV_HASTHIS) && !IsMdStatic(dwFlags)) { REPORT_ERROR1(VLDTR_E_MD_NOTTHISNOTSTATIC, ulCallConv); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } // Get the type argument count. if (ulCallConv & IMAGE_CEE_CS_CALLCONV_GENERIC) { if (i != IMAGE_CEE_CS_CALLCONV_DEFAULT) { REPORT_ERROR1(VLDTR_E_MD_GENERIC_BADCALLCONV, ulCallConv); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if (cbSig == ulCurByte) { REPORT_ERROR1(VLDTR_E_MD_MISSARITY, ulCurByte+1); SetVldtrCode(&hr, hrSave); goto ErrExit; } ulCurByte += CorSigUncompressedDataSize(pbSig); ulTyArgCount = CorSigUncompressData(pbSig); if (ulTyArgCount == 0) { REPORT_ERROR1(VLDTR_E_MD_ARITYZERO, ulCurByte); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // If this is a def, check the arity against the number of generic params if (TypeFromToken(tk) == mdtMethodDef) { CMiniMdRW *pMiniMd = &(m_pStgdb->m_MiniMd); ULONG ulGenericParamCount; HENUMInternal hEnumTyPars; hr = pMiniMd->FindGenericParamHelper(tk, &hEnumTyPars); if (SUCCEEDED(hr)) { IfFailGo(HENUMInternal::GetCount(&hEnumTyPars,&ulGenericParamCount)); HENUMInternal::ClearEnum(&hEnumTyPars); if (ulTyArgCount != ulGenericParamCount) { REPORT_ERROR2(VLDTR_E_MD_GPMISMATCH,ulTyArgCount,ulGenericParamCount); SetVldtrCode(&hrSave, VLDTR_S_ERR); } } } } // Is there any sig left for arguments? _ASSERTE(ulCurByte <= cbSig); if (cbSig == ulCurByte) { REPORT_ERROR1(VLDTR_E_MD_NOARGCNT, ulCurByte+1); SetVldtrCode(&hr, hrSave); goto ErrExit; } // Get the argument count. ulCurByte += CorSigUncompressedDataSize(pbSig); ulArgCount = CorSigUncompressData(pbSig); // Validate the return type and the arguments. // for (i = 0; i < (ulArgCount + 1); i++) for(i=1; ulCurByte < cbSig; i++) { hr = ValidateOneArg(tk, pbSig, cbSig, &ulCurByte,&ulNSentinels,(i > 1)); if (hr != S_OK) { if(hr == VLDTR_E_SIG_MISSARG) { REPORT_ERROR1(VLDTR_E_SIG_MISSARG, i); } SetVldtrCode(&hr, hrSave); hrSave = hr; break; } } if((ulNSentinels != 0) && (!isCallConv(ulCallConv, IMAGE_CEE_CS_CALLCONV_VARARG ))) { REPORT_ERROR0(VLDTR_E_SIG_SENTMUSTVARARG); SetVldtrCode(&hrSave, VLDTR_S_ERR); } if(ulNSentinels > 1) { REPORT_ERROR0(VLDTR_E_SIG_MULTSENTINELS); SetVldtrCode(&hrSave, VLDTR_S_ERR); } hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateMethodSig() //***************************************************************************** // This function validates the given Field signature. This function works // with Field signature for both the MemberRef and FieldDef. //***************************************************************************** HRESULT RegMeta::ValidateFieldSig( mdToken tk, // [IN] Token whose signature needs to be validated. PCCOR_SIGNATURE pbSig, // [IN] Signature. ULONG cbSig) // [IN] Size in bytes of the signature. { ULONG ulCurByte = 0; // Current index into the signature. ULONG ulCallConv; // Calling convention. VEContext veCtxt; // Context record. HRESULT hr = S_OK; // Value returned. HRESULT hrSave = S_OK; // Save state. BEGIN_ENTRYPOINT_NOTHROW; _ASSERTE(TypeFromToken(tk) == mdtFieldDef || TypeFromToken(tk) == mdtMemberRef); memset(&veCtxt, 0, sizeof(VEContext)); veCtxt.Token = tk; veCtxt.uOffset = 0; // Validate the calling convention. ulCurByte += CorSigUncompressedDataSize(pbSig); ulCallConv = CorSigUncompressData(pbSig); if (!isCallConv(ulCallConv, IMAGE_CEE_CS_CALLCONV_FIELD )) { REPORT_ERROR1(VLDTR_E_FD_BADCALLINGCONV, ulCallConv); SetVldtrCode(&hrSave, VLDTR_S_ERR); } // Validate the field. IfFailGo(ValidateOneArg(tk, pbSig, cbSig, &ulCurByte,NULL,TRUE)); SetVldtrCode(&hrSave, hr); hr = hrSave; ErrExit: ; END_ENTRYPOINT_NOTHROW; return hr; } // RegMeta::ValidateFieldSig() //***************************************************************************** // This is a utility function to allocate a one-dimensional zero-based safe // array of variants. //***************************************************************************** static HRESULT _AllocSafeVariantArrayVector( // Return status. VARIANT *rVar, // [IN] Variant array. int cElem, // [IN] Size of the array. SAFEARRAY **ppArray) // [OUT] Double pointer to SAFEARRAY. { HRESULT hr = S_OK; LONG i; _ASSERTE(rVar && cElem && ppArray); IfNullGo(*ppArray = SafeArrayCreateVector(VT_VARIANT, 0, cElem)); for (i = 0; i < cElem; i++) IfFailGo(SafeArrayPutElement(*ppArray, &i, &rVar[i])); ErrExit: return hr; } // _AllocSafeVariantArrayVector() //***************************************************************************** // Helper function for reporting error with no arguments //***************************************************************************** HRESULT RegMeta::_ValidateErrorHelper( HRESULT VECode, VEContext Context) { HRESULT hr = S_OK; // // MDValidator does not zero out the Context. Fix it here. This fix relies // on the fact that MDValidator just uses the token and offset field of the // context. // if (Context.Token != 0) { Context.flags = VER_ERR_TOKEN; } IfBreakGo(m_pVEHandler->VEHandler(VECode, Context, NULL)); ErrExit: return hr; } // _ValidateErrorHelper() //***************************************************************************** // Helper function for reporting error with 1 argument //***************************************************************************** HRESULT RegMeta::_ValidateErrorHelper( HRESULT VECode, VEContext Context, ULONG ulVal1) { HRESULT hr = S_OK; SAFEARRAY *psa = 0; // The SAFEARRAY. VARIANT rVar[1]; // The VARIANT array if (Context.Token != 0) { Context.flags = VER_ERR_TOKEN; } V_VT(&rVar[0]) = VT_UI4; V_UI4(&rVar[0]) = ulVal1; IfFailGo(_AllocSafeVariantArrayVector(rVar, 1, &psa)); IfBreakGo(m_pVEHandler->VEHandler(VECode, Context, psa)); ErrExit: if (psa) { HRESULT hrSave = SafeArrayDestroy(psa); if (FAILED(hrSave)) hr = hrSave; } return hr; } // _ValidateErrorHelper() //***************************************************************************** // Helper function for reporting error with 2 arguments //***************************************************************************** HRESULT RegMeta::_ValidateErrorHelper( HRESULT VECode, VEContext Context, ULONG ulVal1, ULONG ulVal2) { HRESULT hr = S_OK; SAFEARRAY *psa = 0; // The SAFEARRAY. VARIANT rVar[2]; // The VARIANT array if (Context.Token != 0) { Context.flags = VER_ERR_TOKEN; } V_VT(&rVar[0]) = VT_UI4; V_UI4(&rVar[0]) = ulVal1; V_VT(&rVar[1]) = VT_UI4; V_UI4(&rVar[1]) = ulVal2; IfFailGo(_AllocSafeVariantArrayVector(rVar, 2, &psa)); IfBreakGo(m_pVEHandler->VEHandler(VECode, Context, psa)); ErrExit: if (psa) { HRESULT hrSave = SafeArrayDestroy(psa); if (FAILED(hrSave)) hr = hrSave; } return hr; } // _ValidateErrorHelper() //***************************************************************************** // Helper function for reporting error with 3 arguments //***************************************************************************** HRESULT RegMeta::_ValidateErrorHelper( HRESULT VECode, VEContext Context, ULONG ulVal1, ULONG ulVal2, ULONG ulVal3) { HRESULT hr = S_OK; SAFEARRAY *psa = 0; // The SAFEARRAY. VARIANT rVar[3]; // The VARIANT array if (Context.Token != 0) { Context.flags = VER_ERR_TOKEN; } V_VT(&rVar[0]) = VT_UI4; V_UI4(&rVar[0]) = ulVal1; V_VT(&rVar[1]) = VT_UI4; V_UI4(&rVar[1]) = ulVal2; V_VT(&rVar[2]) = VT_UI4; V_UI4(&rVar[2]) = ulVal3; IfFailGo(_AllocSafeVariantArrayVector(rVar, 3, &psa)); IfBreakGo(m_pVEHandler->VEHandler(VECode, Context, psa)); ErrExit: if (psa) { HRESULT hrSave = SafeArrayDestroy(psa); if (FAILED(hrSave)) hr = hrSave; } return hr; } //***************************************************************************** // Helper function to see if there is a duplicate record for ClassLayout. //***************************************************************************** static HRESULT _FindClassLayout( CMiniMdRW *pMiniMd, // [IN] the minimd to lookup mdTypeDef tkParent, // [IN] the parent that ClassLayout is associated with RID *pclRid, // [OUT] rid for the ClassLayout. RID rid) // [IN] rid to be ignored. { HRESULT hr; ULONG cClassLayoutRecs; ClassLayoutRec *pRecord; mdTypeDef tkParTmp; ULONG i; _ASSERTE(pMiniMd && pclRid && rid); _ASSERTE(TypeFromToken(tkParent) == mdtTypeDef && RidFromToken(tkParent)); cClassLayoutRecs = pMiniMd->getCountClassLayouts(); for (i = 1; i <= cClassLayoutRecs; i++) { // Ignore the rid to be ignored! if (rid == i) continue; IfFailRet(pMiniMd->GetClassLayoutRecord(i, &pRecord)); tkParTmp = pMiniMd->getParentOfClassLayout(pRecord); if (tkParTmp == tkParent) { *pclRid = i; return S_OK; } } return CLDB_E_RECORD_NOTFOUND; } // _FindClassLayout() //***************************************************************************** // Helper function to see if there is a duplicate for FieldLayout. //***************************************************************************** static HRESULT _FindFieldLayout( CMiniMdRW *pMiniMd, // [IN] the minimd to lookup mdFieldDef tkParent, // [IN] the parent that FieldLayout is associated with RID *pflRid, // [OUT] rid for the FieldLayout record. RID rid) // [IN] rid to be ignored. { HRESULT hr; ULONG cFieldLayoutRecs; FieldLayoutRec *pRecord; mdFieldDef tkField; ULONG i; _ASSERTE(pMiniMd && pflRid && rid); _ASSERTE(TypeFromToken(tkParent) == mdtFieldDef && RidFromToken(tkParent)); cFieldLayoutRecs = pMiniMd->getCountFieldLayouts(); for (i = 1; i <= cFieldLayoutRecs; i++) { // Ignore the rid to be ignored! if (rid == i) continue; IfFailRet(pMiniMd->GetFieldLayoutRecord(i, &pRecord)); tkField = pMiniMd->getFieldOfFieldLayout(pRecord); if (tkField == tkParent) { *pflRid = i; return S_OK; } } return CLDB_E_RECORD_NOTFOUND; } // _FindFieldLayout() //***************************************************************************** //***************************************************************************** HRESULT MDSigComparer::CompareMethodSignature() { HRESULT hr = S_OK; EX_TRY { hr = _CompareMethodSignature(); } EX_CATCH { hr = E_FAIL; } EX_END_CATCH(SwallowAllExceptions) return hr; } //***************************************************************************** //***************************************************************************** HRESULT MDSigComparer::_CompareMethodSignature() { HRESULT hr; // Test equivalency of method signature header ULONG cArgs; IfFailRet(_CompareMethodSignatureHeader(cArgs)); // Iterate for cArgs + 1 to include the return type for (ULONG i = 0; i < cArgs + 1; i++) { IfFailRet(_CompareExactlyOne()); } return S_OK; } //***************************************************************************** //***************************************************************************** HRESULT MDSigComparer::_CompareExactlyOne() { HRESULT hr; CorElementType typ1, typ2; IfFailRet(m_sig1.GetElemType(&typ1)); IfFailRet(m_sig2.GetElemType(&typ2)); if (typ1 != typ2) { return E_FAIL; } CorElementType typ = typ1; if (!CorIsPrimitiveType((CorElementType)typ)) { switch (typ) { default: { // _ASSERT(!"Illegal or unimplement type in COM+ sig."); return META_E_BAD_SIGNATURE; break; } case ELEMENT_TYPE_VAR: case ELEMENT_TYPE_MVAR: { IfFailRet(_CompareData(NULL)); // Skip variable number break; } case ELEMENT_TYPE_OBJECT: case ELEMENT_TYPE_STRING: case ELEMENT_TYPE_TYPEDBYREF: { break; } case ELEMENT_TYPE_BYREF: // fallthru case ELEMENT_TYPE_PTR: case ELEMENT_TYPE_PINNED: case ELEMENT_TYPE_SZARRAY: { IfFailRet(_CompareExactlyOne()); // Compare referenced type break; } case ELEMENT_TYPE_VALUETYPE: // fallthru case ELEMENT_TYPE_CLASS: { mdToken tok1, tok2; IfFailRet(m_sig1.GetToken(&tok1)); IfFailRet(m_sig2.GetToken(&tok2)); IfFailRet(m_comparer.CompareToken(tok1, tok2)); break; } case ELEMENT_TYPE_FNPTR: { IfFailRet(_CompareMethodSignature()); break; } case ELEMENT_TYPE_ARRAY: { IfFailRet(_CompareExactlyOne()); // Compare element type ULONG rank; IfFailRet(_CompareData(&rank)); // Compare & get rank if (rank) { ULONG nsizes; IfFailRet(_CompareData(&nsizes)); // Compare & get # of sizes while (nsizes--) { IfFailRet(_CompareData(NULL)); // Compare size } ULONG nlbounds; IfFailRet(_CompareData(&nlbounds)); // Compare & get # of lower bounds while (nlbounds--) { IfFailRet(_CompareData(NULL)); // Compare lower bounds } } break; } case ELEMENT_TYPE_SENTINEL: { // Should be unreachable since GetElem strips it break; } case ELEMENT_TYPE_INTERNAL: { // Shouldn't ever get this since it is internal to the runtime, // but just in case we know how to compare and skip these. PVOID val1 = *((PVOID *)m_sig1.m_ptr); PVOID val2 = *((PVOID *)m_sig2.m_ptr); if (val1 != val2) { return E_FAIL; } m_sig1.SkipBytes(sizeof(void*)); m_sig2.SkipBytes(sizeof(void*)); break; } case ELEMENT_TYPE_GENERICINST: { IfFailRet(_CompareExactlyOne()); // Compare generic type ULONG argCnt; IfFailRet(_CompareData(&argCnt)); // Compare & get number of parameters _ASSERTE(argCnt > 0); while (argCnt--) { IfFailRet(_CompareExactlyOne()); // Compare the parameters } break; } } } return S_OK; } //***************************************************************************** //***************************************************************************** HRESULT MDSigComparer::_CompareData( ULONG *pulData) { ULONG cbCompressedData1, cbCompressedData2; ULONG ulData1, ulData2; cbCompressedData1 = CorSigUncompressData(m_sig1.m_ptr, &ulData1); cbCompressedData2 = CorSigUncompressData(m_sig2.m_ptr, &ulData2); if ((cbCompressedData1 == ((ULONG)(-1))) || (cbCompressedData2 == ((ULONG)(-1))) || (cbCompressedData1 != cbCompressedData2) || (ulData1 != ulData2)) { return E_FAIL; } m_sig1.SkipBytes(cbCompressedData1); m_sig2.SkipBytes(cbCompressedData2); // Out data if (pulData) *pulData = ulData1; return S_OK; } //***************************************************************************** //***************************************************************************** HRESULT MDSigComparer::_CompareMethodSignatureHeader( ULONG &cArgs) { HRESULT hr; // Get calling convention information, but only use it to get type param information. ULONG uCallConv1, uCallConv2; IfFailRet(m_sig1.GetData(&uCallConv1)); IfFailRet(m_sig2.GetData(&uCallConv2)); // Check type parameter information ULONG uTypeParamCount1 = 0; ULONG uTypeParamCount2 = 0; if (uCallConv1 & IMAGE_CEE_CS_CALLCONV_GENERIC) IfFailRet(m_sig1.GetData(&uTypeParamCount1)); if (uCallConv2 & IMAGE_CEE_CS_CALLCONV_GENERIC) IfFailRet(m_sig2.GetData(&uTypeParamCount2)); if (uTypeParamCount1 != uTypeParamCount2) { return E_FAIL; } // Get arg count ULONG cArgs1, cArgs2; IfFailRet(m_sig1.GetData(&cArgs1)); IfFailRet(m_sig2.GetData(&cArgs2)); if (cArgs1 != cArgs2) { return E_FAIL; } // Out parameter cArgs = cArgs1; return S_OK; } //***************************************************************************** //***************************************************************************** HRESULT UnifiedAssemblySigComparer::_CompareAssemblies(mdToken tkAsmRef1,mdToken tkAsmRef2, BOOL* pfEquivalent) { HRESULT hr; void const * pvPublicKey1; ULONG cbPublicKey1; ULONG cchName1; ASSEMBLYMETADATA amd1; void const * pvHashValue; ULONG cbHashValue; DWORD dwFlags1; void const * pvPublicKey2; ULONG cbPublicKey2; ULONG cchName2; ASSEMBLYMETADATA amd2; DWORD dwFlags2; ZeroMemory(&amd1, sizeof(amd1)); ZeroMemory(&amd2, sizeof(amd2)); IfFailRet(m_pRegMeta->GetAssemblyRefProps(tkAsmRef1, NULL, NULL, NULL, 0, &cchName1, &amd1, NULL, NULL, NULL)); StackSString ssName1; StackSString ssLocale1; amd1.szLocale = ssLocale1.OpenUnicodeBuffer(amd1.cbLocale); IfFailRet(m_pRegMeta->GetAssemblyRefProps(tkAsmRef1, &pvPublicKey1, &cbPublicKey1, ssName1.OpenUnicodeBuffer(cchName1), cchName1, &cchName1, &amd1, &pvHashValue, &cbHashValue, &dwFlags1)); ssName1.CloseBuffer(); ssLocale1.CloseBuffer(); IfFailRet(m_pRegMeta->GetAssemblyRefProps(tkAsmRef2, NULL, NULL, NULL, 0, &cchName2, &amd2, NULL, NULL, NULL)); StackSString ssName2; StackSString ssLocale2; amd2.szLocale = ssLocale2.OpenUnicodeBuffer(amd2.cbLocale); IfFailRet(m_pRegMeta->GetAssemblyRefProps(tkAsmRef2, &pvPublicKey2, &cbPublicKey2, ssName2.OpenUnicodeBuffer(cchName2), cchName2, &cchName2, &amd2, &pvHashValue, &cbHashValue, &dwFlags2)); ssName2.CloseBuffer(); ssLocale2.CloseBuffer(); StackSString sMscorlib(W("mscorlib")); if(ssName1.CompareCaseInsensitive(sMscorlib)==0 && ssName2.CompareCaseInsensitive(sMscorlib)==0 ) { *pfEquivalent=TRUE; return S_OK; } *pfEquivalent=FALSE; if (ssName1.CompareCaseInsensitive(ssName2)!=0) return S_OK; if (ssLocale1.CompareCaseInsensitive(ssLocale2)!=0) return S_OK; if(cbPublicKey1!=cbPublicKey2) return S_OK; if(memcmp(pvPublicKey1,pvPublicKey2,cbPublicKey1)!=0) return S_OK; if(dwFlags1!=dwFlags2) return S_OK; if(amd1.usMajorVersion!=amd2.usMajorVersion) return S_OK; if(amd1.usMinorVersion!=amd2.usMinorVersion) return S_OK; if(amd1.usBuildNumber!=amd2.usBuildNumber) return S_OK; if(amd1.usRevisionNumber!=amd2.usRevisionNumber) return S_OK; *pfEquivalent=TRUE; return S_OK; }; //***************************************************************************** //***************************************************************************** HRESULT UnifiedAssemblySigComparer::_CreateTypeNameFromTypeRef( mdToken tkTypeRef, SString &ssName, mdToken &tkParent) { HRESULT hr; // Get the parent token as well as the name, and return. ULONG cchTypeRef; IfFailRet(m_pRegMeta->GetTypeRefProps(tkTypeRef, NULL, NULL, 0, &cchTypeRef)); IfFailRet(m_pRegMeta->GetTypeRefProps(tkTypeRef, &tkParent, ssName.OpenUnicodeBuffer(cchTypeRef), cchTypeRef, NULL)); ssName.CloseBuffer(); return S_OK; } //***************************************************************************** //***************************************************************************** HRESULT UnifiedAssemblySigComparer::_CreateFullyQualifiedTypeNameFromTypeRef( mdToken tkTypeRef, SString &ssFullName, mdToken &tkParent) { HRESULT hr; StackSString ssBuf; StackSString ssName; mdToken tok = tkTypeRef; BOOL fFirstLoop = TRUE; // Loop stops at first non-typeref parent token. do { // Get the name for this token, as well as the parent token value. IfFailRet(_CreateTypeNameFromTypeRef(tok, ssName, tok)); // If this is the first time through the loop, just assign values. if (fFirstLoop) { ssFullName = ssName; fFirstLoop = FALSE; } // If this isn't the first time through, make nested type name else { ns::MakeNestedTypeName(ssBuf, ssName, ssFullName); ssFullName = ssBuf; } } while (TypeFromToken(tok) == mdtTypeRef); // Assign non-typeref token parent tkParent = tok; return S_OK; } //***************************************************************************** //***************************************************************************** HRESULT UnifiedAssemblySigComparer::CompareToken( const mdToken &tok1, const mdToken &tok2) { HRESULT hr; // Check binary equality if (tok1 == tok2) { return S_OK; } // Currently only want to do extra checking on TypeRefs if (TypeFromToken(tok1) != mdtTypeRef || TypeFromToken(tok2) != mdtTypeRef) { return E_FAIL; } // Get the fully qualified type names as well as the non-typeref parents. mdToken tkParent1, tkParent2; StackSString ssName1, ssName2; IfFailRet(_CreateFullyQualifiedTypeNameFromTypeRef(tok1, ssName1, tkParent1)); IfFailRet(_CreateFullyQualifiedTypeNameFromTypeRef(tok2, ssName2, tkParent2)); // Currently only want to do extra checking if the parent tokens are AssemblyRefs if (TypeFromToken(tkParent1) != mdtAssemblyRef || TypeFromToken(tkParent2) != mdtAssemblyRef) { return E_FAIL; } // If the type names are not equal, no need to check the assembly refs for unification since // we know the types couldn't possibly match. if (!ssName1.Equals(ssName2)) { return E_FAIL; } BOOL fEquivalent; // no redirects supported IfFailRet(_CompareAssemblies(tkParent1,tkParent2,&fEquivalent)); if (!fEquivalent) { return E_FAIL; } return S_OK; } //***************************************************************************** // Helper function to validate a locale. //***************************************************************************** static const char* const g_szValidLocale_V1[] = { "ar","ar-SA","ar-IQ","ar-EG","ar-LY","ar-DZ","ar-MA","ar-TN","ar-OM","ar-YE","ar-SY","ar-JO","ar-LB","ar-KW","ar-AE","ar-BH","ar-QA", "bg","bg-BG", "ca","ca-ES", "zh-CHS","zh-TW","zh-CN","zh-HK","zh-SG","zh-MO","zh-CHT", "cs","cs-CZ", "da","da-DK", "de","de-DE","de-CH","de-AT","de-LU","de-LI", "el","el-GR", "en","en-US","en-GB","en-AU","en-CA","en-NZ","en-IE","en-ZA","en-JM","en-CB","en-BZ","en-TT","en-ZW","en-PH", "es","es-ES-Ts","es-MX","es-ES","es-GT","es-CR","es-PA","es-DO","es-VE","es-CO","es-PE","es-AR","es-EC","es-CL", "es-UY","es-PY","es-BO","es-SV","es-HN","es-NI","es-PR", "fi","fi-FI", "fr","fr-FR","fr-BE","fr-CA","fr-CH","fr-LU","fr-MC", "he","he-IL", "hu","hu-HU", "is","is-IS", "it","it-IT","it-CH", "ja","ja-JP", "ko","ko-KR", "nl","nl-NL","nl-BE", "no", "nb-NO", "nn-NO", "pl","pl-PL", "pt","pt-BR","pt-PT", "ro","ro-RO", "ru","ru-RU", "hr","hr-HR", "sk","sk-SK", "sq","sq-AL", "sv","sv-SE","sv-FI", "th","th-TH", "tr","tr-TR", "ur","ur-PK", "id","id-ID", "uk","uk-UA", "be","be-BY", "sl","sl-SI", "et","et-EE", "lv","lv-LV", "lt","lt-LT", "fa","fa-IR", "vi","vi-VN", "hy","hy-AM", "az", "eu","eu-ES", "mk","mk-MK", "af","af-ZA", "ka","ka-GE", "fo","fo-FO", "hi","hi-IN", "ms","ms-MY","ms-BN", "kk","kk-KZ", "ky","ky-KZ", "sw","sw-KE", "uz", "tt","tt-RU", "pa","pa-IN", "gu","gu-IN", "ta","ta-IN", "te","te-IN", "kn","kn-IN", "mr","mr-IN", "sa","sa-IN", "mn","mn-MN", "gl","gl-ES", "kok","kok-IN", "syr","syr-SY", "div" }; static const char* const g_szValidLocale_V2[] = { "bn", "bn-IN", "bs-Latn-BA", "bs-Cyrl-BA", "hr-BA", "fil", "fil-PH", "fy", "fy-NL", "iu-Latn-CA", "ga", "ga-IE", "ky-KG", "lb", "lb-LU", "ml", "ml-IN", "mt", "mt-MT", "mi", "mi-NZ", "arn", "arn-CL", "moh", "moh-CA", "ne", "ne-NP", "ps", "ps-AF", "quz", "quz-BO", "quz-EC", "quz-PE", "rm", "rm-CH", "smn", "smn-FI", "smj" , "smj-SE", "smj-NO", "se", "se-NO", "se-SE", "se-FI", "sms", "sms-FI", "sma", "sma-NO", "sma-SE", "sr-Latn-BA", "sr-Cyrl-BA", "nso", "nso-ZA" }; // Pre-vista specific cultures (renamed on Vista) static const char* const g_szValidLocale_PreVista[] = { "div-MV", "sr-SP-Latn", "sr-SP-Cyrl", "az-AZ-Latn", "az-AZ-Cyrl", "uz-UZ-Latn", "uz-UZ-Cyrl", }; // Vista only specific cultures (renamed and freshly introduced) static const char * const g_szValidLocale_Vista[] = { "dv-MV", "sr-Latn-CS", "sr-Cyrl-CS", "az-Latn-AZ", "az-Cyrl-AZ", "uz-Latn-UZ", "uz-Cyrl-UZ", "zh-Hant", "zh-Hans", "gsw", "gsw-FR", "am", "am-ET", "as", "as-IN", "ba", "ba-RU", "br", "br-FR", "en-IN", "kl", "kl-GL", "iu-Cans-CA", "km", "km-KH", "lo", "lo-LA", "dsb", "dsb-DE", "mn-Mong-CN", "oc", "oc-FR", "or", "or-IN" }; static BOOL FindInArray(LPCUTF8 szLocale, const char * const *cultureArr, const int nCultures) { for (int i = 0; i < nCultures; i++) { if(!SString::_stricmp(szLocale, cultureArr[i])) return TRUE; } return FALSE; } #define LENGTH_OF(x) (sizeof(x) / sizeof(x[0])) // For Everett assemblies, only the preVista cultures are valid even if running on Vista. static BOOL _IsValidLocale(LPCUTF8 szLocale, BOOL fIsV2Assembly) { if (szLocale && *szLocale) { // Locales valid for Everett and Whidbey if (FindInArray(szLocale, g_szValidLocale_V1, LENGTH_OF(g_szValidLocale_V1))) return TRUE; // Locales valid for Whidbey assemblies only if (fIsV2Assembly && FindInArray(szLocale, g_szValidLocale_V2, LENGTH_OF(g_szValidLocale_V2))) return TRUE; // Finally search OS specific cultures if (fIsV2Assembly) return FindInArray(szLocale, g_szValidLocale_Vista, LENGTH_OF(g_szValidLocale_Vista)); else return FindInArray(szLocale, g_szValidLocale_PreVista, LENGTH_OF(g_szValidLocale_PreVista)); } return TRUE; } #endif //FEATURE_METADATA_VALIDATOR
37.074967
165
0.530069
[ "object", "vector" ]
ce6db9c98e257994cec83ddc09dcad4a7eda0234
16,417
cpp
C++
lib/VM/GCBase.cpp
Jhingun1/hermes
fa4828779532d5bbe6122194cd15b00120d243b0
[ "MIT" ]
null
null
null
lib/VM/GCBase.cpp
Jhingun1/hermes
fa4828779532d5bbe6122194cd15b00120d243b0
[ "MIT" ]
null
null
null
lib/VM/GCBase.cpp
Jhingun1/hermes
fa4828779532d5bbe6122194cd15b00120d243b0
[ "MIT" ]
null
null
null
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #define DEBUG_TYPE "gc" #include "hermes/VM/GC.h" #include "hermes/Platform/Logging.h" #include "hermes/Support/ErrorHandling.h" #include "hermes/Support/OSCompat.h" #include "hermes/VM/CellKind.h" #include "hermes/VM/GCPointer-inline.h" #include "hermes/VM/JSWeakMapImpl.h" #include "hermes/VM/Runtime.h" #include "hermes/VM/VTable.h" #include "llvm/Support/Debug.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/Format.h" #include "llvm/Support/NativeFormatting.h" #include "llvm/Support/raw_ostream.h" #include <inttypes.h> #include <stdexcept> #include <system_error> using llvm::dbgs; using llvm::format; namespace hermes { namespace vm { GCBase::GCBase( MetadataTable metaTable, GCCallbacks *gcCallbacks, PointerBase *pointerBase, const GCConfig &gcConfig, std::shared_ptr<CrashManager> crashMgr) : metaTable_(metaTable), gcCallbacks_(gcCallbacks), pointerBase_(pointerBase), crashMgr_(crashMgr), analyticsCallback_(gcConfig.getAnalyticsCallback()), recordGcStats_(gcConfig.getShouldRecordStats()), // Start off not in GC. inGC_(false), name_(gcConfig.getName()), allocationLocationTracker_(this), #ifdef HERMESVM_MEMORY_PROFILER memEventTracker_(gcConfig.getMemEventTracker()), #endif tripwireCallback_(gcConfig.getTripwireConfig().getCallback()), tripwireLimit_(gcConfig.getTripwireConfig().getLimit()) #ifdef HERMESVM_SANITIZE_HANDLES , sanitizeRate_(gcConfig.getSanitizeConfig().getSanitizeRate()) #endif #ifndef NDEBUG , randomizeAllocSpace_(gcConfig.getShouldRandomizeAllocSpace()) #endif { #ifdef HERMESVM_PLATFORM_LOGGING hermesLog( "HermesGC", "Initialisation (Init: %dMB, Max: %dMB, Tripwire: %dMB)", gcConfig.getInitHeapSize() >> 20, gcConfig.getMaxHeapSize() >> 20, gcConfig.getTripwireConfig().getLimit() >> 20); #endif // HERMESVM_PLATFORM_LOGGING #ifdef HERMESVM_SANITIZE_HANDLES const std::minstd_rand::result_type seed = gcConfig.getSanitizeConfig().getRandomSeed() >= 0 ? gcConfig.getSanitizeConfig().getRandomSeed() : std::random_device()(); if (sanitizeRate_ > 0.0 && sanitizeRate_ < 1.0) { llvm::errs() << "Warning: you are using handle sanitization with random sampling.\n" << "Sanitize Rate: "; llvm::write_double(llvm::errs(), sanitizeRate_, llvm::FloatStyle::Percent); llvm::errs() << "\n" << "Sanitize Rate Seed: " << seed << "\n" << "Re-run with -gc-sanitize-handles-random-seed=" << seed << " for deterministic crashes.\n"; } randomEngine_.seed(seed); #endif } GCBase::GCCycle::GCCycle( GCBase *gc, OptValue<GCCallbacks *> gcCallbacksOpt, std::string extraInfo) : gc_(gc), gcCallbacksOpt_(gcCallbacksOpt), extraInfo_(std::move(extraInfo)) { gc_->inGC_ = true; if (gcCallbacksOpt_.hasValue()) { gcCallbacksOpt_.getValue()->onGCEvent( GCEventKind::CollectionStart, extraInfo_); } } GCBase::GCCycle::~GCCycle() { if (gcCallbacksOpt_.hasValue()) { gcCallbacksOpt_.getValue()->onGCEvent( GCEventKind::CollectionEnd, extraInfo_); } gc_->inGC_ = false; } void GCBase::runtimeWillExecute() { if (recordGcStats_ && !execStartTimeRecorded_) { execStartTime_ = std::chrono::steady_clock::now(); execStartCPUTime_ = oscompat::thread_cpu_time(); oscompat::num_context_switches( startNumVoluntaryContextSwitches_, startNumInvoluntaryContextSwitches_); execStartTimeRecorded_ = true; } } std::error_code GCBase::createSnapshotToFile(const std::string &fileName) { std::error_code code; llvm::raw_fd_ostream os(fileName, code, llvm::sys::fs::FileAccess::FA_Write); if (code) { return code; } createSnapshot(os); return std::error_code{}; } void GCBase::checkTripwire(size_t dataSize) { if (LLVM_LIKELY(!tripwireCallback_) || LLVM_LIKELY(dataSize < tripwireLimit_) || tripwireCalled_) { return; } class Ctx : public GCTripwireContext { public: Ctx(GCBase *gc) : gc_(gc) {} std::error_code createSnapshotToFile(const std::string &path) override { return gc_->createSnapshotToFile(path); } private: GCBase *gc_; } ctx(this); tripwireCalled_ = true; tripwireCallback_(ctx); } void GCBase::printAllCollectedStats(llvm::raw_ostream &os) { if (!recordGcStats_) return; dump(os); os << "GC stats:\n" << "{\n" << "\t\"type\": \"hermes\",\n" << "\t\"version\": 0,\n"; printStats(os, false); os << "}\n"; } void GCBase::getHeapInfo(HeapInfo &info) { info.numCollections = cumStats_.numCollections; } #ifndef NDEBUG void GCBase::getDebugHeapInfo(DebugHeapInfo &info) { recordNumAllocatedObjects(); info.numAllocatedObjects = numAllocatedObjects_; info.numReachableObjects = numReachableObjects_; info.numCollectedObjects = numCollectedObjects_; info.numFinalizedObjects = numFinalizedObjects_; info.numMarkedSymbols = numMarkedSymbols_; info.numHiddenClasses = numHiddenClasses_; info.numLeafHiddenClasses = numLeafHiddenClasses_; } #endif #ifndef NDEBUG void GCBase::DebugHeapInfo::assertInvariants() const { // The number of allocated objects at any time is at least the number // found reachable in the last collection. assert(numAllocatedObjects >= numReachableObjects); // The number of objects finalized in the last collection is at most the // number of objects collected. assert(numCollectedObjects >= numFinalizedObjects); } #endif void GCBase::dump(llvm::raw_ostream &, bool) { /* nop */ } void GCBase::printStats(llvm::raw_ostream &os, bool trailingComma) { std::chrono::duration<double> elapsedTime = std::chrono::steady_clock::now() - execStartTime_; auto elapsedCPUSeconds = std::chrono::duration_cast<std::chrono::duration<double>>( oscompat::thread_cpu_time()) .count() - std::chrono::duration_cast<std::chrono::duration<double>>( execStartCPUTime_) .count(); HeapInfo info; getHeapInfoWithMallocSize(info); getHeapInfo(info); #ifndef NDEBUG DebugHeapInfo debugInfo; getDebugHeapInfo(debugInfo); #endif os << "\t\"heapInfo\": {\n" #ifndef NDEBUG << "\t\t\"Num allocated cells\": " << debugInfo.numAllocatedObjects << ",\n" << "\t\t\"Num reachable cells\": " << debugInfo.numReachableObjects << ",\n" << "\t\t\"Num collected cells\": " << debugInfo.numCollectedObjects << ",\n" << "\t\t\"Num finalized cells\": " << debugInfo.numFinalizedObjects << ",\n" << "\t\t\"Num marked symbols\": " << debugInfo.numMarkedSymbols << ",\n" << "\t\t\"Num hidden classes\": " << debugInfo.numHiddenClasses << ",\n" << "\t\t\"Num leaf classes\": " << debugInfo.numLeafHiddenClasses << ",\n" << "\t\t\"Num weak references\": " << ((GC *)this)->countUsedWeakRefs() << ",\n" #endif << "\t\t\"Peak RSS\": " << oscompat::peak_rss() << ",\n" << "\t\t\"Current RSS\": " << oscompat::current_rss() << ",\n" << "\t\t\"Current Dirty\": " << oscompat::current_private_dirty() << ",\n" << "\t\t\"Heap size\": " << info.heapSize << ",\n" << "\t\t\"Allocated bytes\": " << info.allocatedBytes << ",\n" << "\t\t\"Num collections\": " << info.numCollections << ",\n" << "\t\t\"Malloc size\": " << info.mallocSizeEstimate << "\n" << "\t},\n"; long vol = -1; long invol = -1; if (oscompat::num_context_switches(vol, invol)) { vol -= startNumVoluntaryContextSwitches_; invol -= startNumInvoluntaryContextSwitches_; } os << "\t\"general\": {\n" << "\t\t\"numCollections\": " << cumStats_.numCollections << ",\n" << "\t\t\"totalTime\": " << elapsedTime.count() << ",\n" << "\t\t\"totalCPUTime\": " << elapsedCPUSeconds << ",\n" << "\t\t\"totalGCTime\": " << formatSecs(cumStats_.gcWallTime.sum()).secs << ",\n" << "\t\t\"volCtxSwitch\": " << vol << ",\n" << "\t\t\"involCtxSwitch\": " << invol << ",\n" << "\t\t\"avgGCPause\": " << formatSecs(cumStats_.gcWallTime.average()).secs << ",\n" << "\t\t\"maxGCPause\": " << formatSecs(cumStats_.gcWallTime.max()).secs << ",\n" << "\t\t\"totalGCCPUTime\": " << formatSecs(cumStats_.gcCPUTime.sum()).secs << ",\n" << "\t\t\"avgGCCPUPause\": " << formatSecs(cumStats_.gcCPUTime.average()).secs << ",\n" << "\t\t\"maxGCCPUPause\": " << formatSecs(cumStats_.gcCPUTime.max()).secs << ",\n" << "\t\t\"finalHeapSize\": " << formatSize(cumStats_.finalHeapSize).bytes << ",\n" << "\t\t\"peakAllocatedBytes\": " << formatSize(getPeakAllocatedBytes()).bytes << ",\n" << "\t\t\"peakLiveAfterGC\": " << formatSize(getPeakLiveAfterGC()).bytes << ",\n" << "\t\t\"totalAllocatedBytes\": " << formatSize(info.totalAllocatedBytes).bytes << "\n" << "\t}"; if (trailingComma) { os << ","; } os << "\n"; } void GCBase::recordGCStats( double wallTime, double cpuTime, gcheapsize_t finalHeapSize, gcheapsize_t usedBefore, gcheapsize_t usedAfter, CumulativeHeapStats *stats) { stats->gcWallTime.record(wallTime); stats->gcCPUTime.record(cpuTime); stats->finalHeapSize = finalHeapSize; stats->usedBefore.record(usedBefore); stats->usedAfter.record(usedAfter); stats->numCollections++; } void GCBase::recordGCStats( double wallTime, double cpuTime, gcheapsize_t usedBefore, gcheapsize_t usedAfter, gcheapsize_t finalHeapSize) { recordGCStats( wallTime, cpuTime, finalHeapSize, usedBefore, usedAfter, &cumStats_); } void GCBase::oom(std::error_code reason) { #ifdef HERMESVM_EXCEPTION_ON_OOM HeapInfo heapInfo; getHeapInfo(heapInfo); char detailBuffer[400]; snprintf( detailBuffer, sizeof(detailBuffer), "Javascript heap memory exhausted: heap size = %d, allocated = %d.", heapInfo.heapSize, heapInfo.allocatedBytes); throw JSOutOfMemoryError( std::string(detailBuffer) + "\ncall stack:\n" + gcCallbacks_->getCallStackNoAlloc()); #else oomDetail(reason); hermes_fatal((llvm::Twine("OOM: ") + convert_error_to_message(reason)).str()); #endif } void GCBase::oomDetail(std::error_code reason) { HeapInfo heapInfo; getHeapInfo(heapInfo); // Could use a stringstream here, but want to avoid dynamic allocation. char detailBuffer[400]; snprintf( detailBuffer, sizeof(detailBuffer), "[%.20s] reason = %.150s (%d from category: %.50s), numCollections = %d, heapSize = %d, allocated = %d, va = %" PRIu64, name_.c_str(), reason.message().c_str(), reason.value(), reason.category().name(), heapInfo.numCollections, heapInfo.heapSize, heapInfo.allocatedBytes, heapInfo.va); hermesLog("HermesGC", "OOM: %s.", detailBuffer); // Record the OOM custom data with the crash manager. crashMgr_->setCustomData("HermesGCOOMDetailBasic", detailBuffer); } #ifndef NDEBUG /*static*/ bool GCBase::isMostRecentCellInFinalizerVector( const std::vector<GCCell *> &finalizables, const GCCell *cell) { return !finalizables.empty() && finalizables.back() == cell; } #endif #ifdef HERMESVM_SANITIZE_HANDLES bool GCBase::shouldSanitizeHandles() { static std::uniform_real_distribution<> dist(0.0, 1.0); return dist(randomEngine_) < sanitizeRate_; } #endif /*static*/ std::list<detail::WeakRefKey *> GCBase::buildKeyList( GC *gc, JSWeakMap *weakMap) { std::list<detail::WeakRefKey *> res; for (auto iter = weakMap->keys_begin(), end = weakMap->keys_end(); iter != end; iter++) { if (iter->getObject(gc)) { res.push_back(&(*iter)); } } return res; } /*static*/ double GCBase::clockDiffSeconds(TimePoint start, TimePoint end) { std::chrono::duration<double> elapsed = (end - start); return elapsed.count(); } /*static*/ double GCBase::clockDiffSeconds( std::chrono::microseconds start, std::chrono::microseconds end) { std::chrono::duration<double> elapsed = (end - start); return elapsed.count(); } llvm::raw_ostream &operator<<( llvm::raw_ostream &os, const DurationFormatObj &dfo) { if (dfo.secs >= 1.0) { os << format("%5.3f", dfo.secs) << " s"; } else if (dfo.secs >= 0.001) { os << format("%5.3f", dfo.secs * 1000.0) << " ms"; } else { os << format("%5.3f", dfo.secs * 1000000.0) << " us"; } return os; } llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const SizeFormatObj &sfo) { double dblsize = static_cast<double>(sfo.bytes); if (sfo.bytes >= (1024 * 1024 * 1024)) { double gbs = dblsize / (1024.0 * 1024.0 * 1024.0); os << format("%0.3f GiB", gbs); } else if (sfo.bytes >= (1024 * 1024)) { double mbs = dblsize / (1024.0 * 1024.0); os << format("%0.3f MiB", mbs); } else if (sfo.bytes >= 1024) { double kbs = dblsize / 1024.0; os << format("%0.3f KiB", kbs); } else { os << sfo.bytes << " B"; } return os; } GCBase::GCCallbacks::~GCCallbacks() {} GCBase::IDTracker::IDTracker() { assert(nextID_ % 2 == 1 && "First JS object ID isn't odd"); assert(nextNativeID_ % 2 == 0 && "First native object ID isn't even"); } #ifdef HERMESVM_SERIALIZE void GCBase::AllocationLocationTracker::serialize(Serializer &s) const { if (enabled_) { hermes_fatal( "Serialization not supported when AllocationLocationTracker enabled"); } } void GCBase::AllocationLocationTracker::deserialize(Deserializer &d) { if (enabled_) { hermes_fatal( "Deserialization not supported when AllocationLocationTracker enabled"); } } void GCBase::IDTracker::serialize(Serializer &s) const { s.writeInt<HeapSnapshot::NodeID>(nextID_); s.writeInt<HeapSnapshot::NodeID>(nextNativeID_); s.writeInt<size_t>(objectIDMap_.size()); for (auto it = objectIDMap_.begin(); it != objectIDMap_.end(); it++) { s.writeRelocation(it->first); s.writeInt<HeapSnapshot::NodeID>(it->second); } } void GCBase::IDTracker::deserialize(Deserializer &d) { nextID_ = d.readInt<HeapSnapshot::NodeID>(); nextNativeID_ = d.readInt<HeapSnapshot::NodeID>(); size_t size = d.readInt<size_t>(); for (size_t i = 0; i < size; i++) { // Heap must have been deserialized before this function. All deserialized // pointer must be non-null at this time. const void *ptr = d.getNonNullPtr(); auto res = objectIDMap_.try_emplace(ptr, d.readInt<HeapSnapshot::NodeID>()).second; (void)res; assert(res && "Shouldn't fail to insert during deserialization"); } } #endif void GCBase::IDTracker::untrackUnmarkedSymbols( const std::vector<bool> &markedSymbols) { std::vector<uint32_t> toUntrack; for (const auto &pair : symbolIDMap_) { if (!markedSymbols[pair.first]) { toUntrack.push_back(pair.first); } } for (uint32_t symIdx : toUntrack) { symbolIDMap_.erase(symIdx); } } HeapSnapshot::NodeID GCBase::IDTracker::getNumberID(double num) { auto &numberRef = numberIDMap_[num]; // If the entry didn't exist, the value was initialized to 0. if (numberRef != 0) { return numberRef; } // Else, it is a number that hasn't been seen before. return numberRef = nextNumberID(); } llvm::Optional<HeapSnapshot::NodeID> GCBase::getSnapshotID(HermesValue val) { if (val.isPointer() && val.getPointer()) { // Make nullptr HermesValue look like a JS null. // This should be rare, but is occasionally used by some parts of the VM. return val.getPointer() ? getObjectID(val.getPointer()) : static_cast<HeapSnapshot::NodeID>(IDTracker::ReservedObjectID::Null); } else if (val.isNumber()) { return idTracker_.getNumberID(val.getNumber()); } else if (val.isUndefined()) { return static_cast<HeapSnapshot::NodeID>( IDTracker::ReservedObjectID::Undefined); } else if (val.isNull()) { return static_cast<HeapSnapshot::NodeID>(IDTracker::ReservedObjectID::Null); } else if (val.isBool()) { return static_cast<HeapSnapshot::NodeID>( val.getBool() ? IDTracker::ReservedObjectID::True : IDTracker::ReservedObjectID::False); } else { return llvm::None; } } } // namespace vm } // namespace hermes
31.330153
125
0.658829
[ "object", "vector" ]
ce6fb1abe92141e3b078734d196a4afeb6a05d2a
20,248
cpp
C++
src/apps/adop_viewer.cpp
bulutthecat/Testing-ADOP-inviorment
a433698b5df973e2dde323db3a698fe70f6b3198
[ "MIT" ]
1,319
2021-10-14T03:30:13.000Z
2022-03-30T12:34:18.000Z
src/apps/adop_viewer.cpp
dingjiongfeng/ADOP
a433698b5df973e2dde323db3a698fe70f6b3198
[ "MIT" ]
57
2021-10-21T20:39:11.000Z
2022-03-23T06:54:58.000Z
src/apps/adop_viewer.cpp
dingjiongfeng/ADOP
a433698b5df973e2dde323db3a698fe70f6b3198
[ "MIT" ]
153
2021-10-15T18:41:51.000Z
2022-03-31T17:23:46.000Z
/** * Copyright (c) 2021 Darius Rückert * Licensed under the MIT License. * See LICENSE file for more information. */ #include "adop_viewer.h" #include "saiga/core/geometry/cameraAnimation.h" #include "saiga/core/util/commandLineArguments.h" #include "saiga/core/util/exif/TinyEXIF.h" #include "git_sha1.h" ADOPViewer::ADOPViewer(std::string scene_dir, std::unique_ptr<DeferredRenderer> renderer_, std::unique_ptr<WindowType> window_) : StandaloneWindow<wm, DeferredRenderer>(std::move(renderer_), std::move(window_)) { main_menu.AddItem( "Saiga", "MODEL", [this]() { view_mode = ViewMode::MODEL; }, GLFW_KEY_F1, "F1"); main_menu.AddItem( "Saiga", "NEURAL", [this]() { view_mode = ViewMode::NEURAL; }, GLFW_KEY_F2, "F2"); main_menu.AddItem( "Saiga", "SPLIT_NEURAL", [this]() { view_mode = ViewMode::SPLIT_NEURAL; }, GLFW_KEY_F3, "F3"); std::cout << "Program Initialized!" << std::endl; std::cout << "Loading Scene " << scene_dir << std::endl; LoadScene(scene_dir); LoadSceneImpl(); std::filesystem::create_directories("videos/"); recording_dir = "videos/" + scene->scene->scene_name + "/"; view_mode = ViewMode::SPLIT_NEURAL; } void ADOPViewer::LoadSceneImpl() { if (renderer->tone_mapper.auto_exposure || renderer->tone_mapper.auto_white_balance) { renderer->tone_mapper.download_tmp_values = true; } renderer->lighting.pointLights.clear(); renderer->lighting.directionalLights.clear(); renderer->lighting.spotLights.clear(); ::camera = &scene->scene_camera; window->setCamera(camera); if (scene->scene->point_cloud.NumVertices() > 15000000) { // by default don't render very large point clouds in the viewport render_points = false; } auto& f = scene->scene->frames.front(); camera->setModelMatrix(f.OpenglModel()); camera->updateFromModel(); renderer->params.useSSAO = false; sun = std::make_shared<DirectionalLight>(); sun->ambientIntensity = exp2(scene->scene->dataset_params.scene_exposure_value); sun->intensity = 0; renderer->lighting.AddLight(sun); renderer->tone_mapper.params.exposure_value = scene->scene->dataset_params.scene_exposure_value; } void ADOPViewer::render(RenderInfo render_info) { if (renderObject && render_info.render_pass == RenderPass::Deferred) { if (!scene->model.mesh.empty()) { if (renderTexture && scene->model.mesh.front().HasTC()) { if (!object_tex) { object_tex = std::make_shared<TexturedAsset>(scene->model); } object_tex->render(render_info.camera, mat4::Identity()); } else { if (!object_col) { scene->model.ComputeColor(); auto mesh = scene->model.CombinedMesh(VERTEX_POSITION | VERTEX_NORMAL | VERTEX_COLOR).first; mesh.RemoveDoubles(0.001); // mesh.SmoothVertexColors(10, 0); object_col = std::make_shared<ColoredAsset>(mesh); } object_col->render(render_info.camera, mat4::Identity()); } } } if (render_info.render_pass == RenderPass::Final) { if (view_mode == ViewMode::NEURAL) { auto fd = scene->CurrentFrameData(); fd.w = fd.w * render_scale; fd.h = fd.h * render_scale; fd.K = fd.K.scale(render_scale); fd.exposure_value = renderer->tone_mapper.params.exposure_value; fd.white_balance = renderer->tone_mapper.params.white_point; if (!neural_renderer) { neural_renderer = std::make_unique<RealTimeRenderer>(scene->scene); } neural_renderer->tone_mapper.params = renderer->tone_mapper.params; neural_renderer->tone_mapper.tm_operator = renderer->tone_mapper.tm_operator; neural_renderer->tone_mapper.params.exposure_value -= scene->scene->dataset_params.scene_exposure_value; neural_renderer->tone_mapper.params_dirty = true; neural_renderer->timer_system.BeginFrame(); neural_renderer->Render(fd); neural_renderer->timer_system.EndFrame(); if (neural_renderer->use_gl_tonemapping) { display.render(neural_renderer->output_texture_ldr.get(), ivec2(0, 0), renderer->viewport_size, true); } else { display.render(neural_renderer->output_texture.get(), ivec2(0, 0), renderer->viewport_size, true); } } } // Debug view of point cloud + image frames if ((view_mode == ViewMode::SPLIT_NEURAL || view_mode == ViewMode::MODEL) && render_info.render_pass == RenderPass::Forward) { if (render_debug) { scene->RenderDebug(render_info.camera); } if (spline_mesh) { glLineWidth(3); spline_mesh->renderForward(render_info.camera, mat4::Identity()); glLineWidth(1); } if (render_points) { if (!scene->gl_points) { scene->gl_points = std::make_shared<NeuralPointCloudOpenGL>(scene->scene->point_cloud); } // Create a frame around the current gl-camera FrameData fd; fd.w = renderer->viewport_size.x(); fd.h = renderer->viewport_size.y(); fd.pose = Sophus::SE3f::fitToSE3(camera->model * GL2CVView()).cast<double>(); fd.K = GLProjectionMatrix2CVCamera(camera->proj, fd.w, fd.h); fd.distortion = scene->scene->scene_cameras.front().distortion; fd.exposure_value = scene->scene->dataset_params.scene_exposure_value; { auto tim = renderer->timer->Measure("GL_POINTS render"); scene->gl_points->render(fd, 0); } } if (renderWireframe) { glEnable(GL_POLYGON_OFFSET_LINE); // glLineWidth(1); glPolygonOffset(0, -500); // object.renderWireframe(cam); glDisable(GL_POLYGON_OFFSET_LINE); } } if (render_info.render_pass == RenderPass::GUI) { if (ImGui::Begin("Video Recording")) { } ImGui::End(); ViewerBase::imgui(); ImGui::Begin("Model Viewer"); ImGui::SliderFloat("render_scale", &render_scale, 0.1, 2); if (neural_renderer) { if (ImGui::Button("Set to closest frame")) { auto& f = scene->scene->frames[neural_renderer->current_best_gt]; ::camera->setModelMatrix(f.OpenglModel()); ::camera->updateFromModel(); renderer->tone_mapper.params.exposure_value = f.exposure_value; renderer->tone_mapper.params_dirty = true; } } ImGui::End(); auto fd = scene->CurrentFrameData(); fd.w = fd.w * render_scale; fd.h = fd.h * render_scale; fd.K = fd.K.scale(render_scale); fd.exposure_value = renderer->tone_mapper.params.exposure_value; fd.white_balance = renderer->tone_mapper.params.white_point; if (view_mode == ViewMode::SPLIT_NEURAL) { if (!neural_renderer) { neural_renderer = std::make_unique<RealTimeRenderer>(scene->scene); } mouse_in_gt = neural_renderer->mouse_on_view; neural_renderer->tone_mapper.params = renderer->tone_mapper.params; neural_renderer->tone_mapper.tm_operator = renderer->tone_mapper.tm_operator; neural_renderer->tone_mapper.params.exposure_value -= scene->scene->dataset_params.scene_exposure_value; neural_renderer->tone_mapper.params_dirty = true; // neural_renderer->tone_mapper.params_dirty |= renderer->tone_mapper.params_dirty; neural_renderer->Forward(&scene->scene_camera, fd); } if (ImGui::Begin("Video Recording")) { Recording(fd); } ImGui::End(); } } void ADOPViewer::Recording(ImageInfo& fd) { std::string out_dir = recording_dir; static bool is_recording = false; static bool downscale_gt = false; static bool interpolate_exposure = false; static bool record_debug = true; static bool record_gt = true; static bool record_neural = true; ImGui::Checkbox("record_debug", &record_debug); ImGui::Checkbox("record_gt", &record_gt); ImGui::Checkbox("record_neural", &record_neural); ImGui::Checkbox("downscale_gt", &downscale_gt); static std::vector<SplineKeyframe> traj; auto insert = [this](int id) { SplineKeyframe kf; kf.user_index = id; kf.pose = scene->scene->frames[id].pose; camera_spline.Insert(kf); }; bool update_curve = false; static bool hdr_video_gen = false; static int current_frame = 0; if (is_recording) { std::string frame_name = std::to_string(current_frame) + ".png"; if (record_neural) { SAIGA_ASSERT(neural_renderer); auto frame = neural_renderer->DownloadRender(); frame.save(out_dir + "/neural/" + frame_name); } if (record_debug) { SAIGA_ASSERT(neural_renderer); auto frame = neural_renderer->DownloadColor(); frame.save(out_dir + "/debug/" + frame_name); } if (record_gt) { SAIGA_ASSERT(neural_renderer); TemplatedImage<ucvec4> frame = neural_renderer->DownloadGt(); if (downscale_gt) { TemplatedImage<ucvec4> gt_small(frame.h / 2, frame.w / 2); frame.getImageView().copyScaleDownPow2(gt_small.getImageView(), 2); frame = gt_small; } frame.save(out_dir + "/gt/" + frame_name); } current_frame++; if (current_frame == traj.size() || ImGui::Button("stop recording")) { is_recording = false; } } if (ImGui::Button("preset lighthouse")) { camera_spline.keyframes.clear(); camera_spline.frame_rate = 60; std::vector<int> kfs = {108, 108, 121, 138, 6, 43, 71, 90, 108, 108}; for (auto i : kfs) { insert(i); } renderer->tone_mapper.params.exposure_value = 0; renderer->tone_mapper.params_dirty = true; update_curve = true; } if (ImGui::Button("preset m60")) { camera_spline.keyframes.clear(); camera_spline.frame_rate = 60; std::vector<int> kfs = {0, 0, 148, 27, 190, 67, 84, 90, 96, 277, 290, 303, 0, 0}; for (auto i : kfs) { insert(i); } renderer->tone_mapper.params.exposure_value = scene->scene->frames[kfs[0]].exposure_value; renderer->tone_mapper.params_dirty = true; update_curve = true; } if (ImGui::Button("preset playground")) { camera_spline.keyframes.clear(); camera_spline.frame_rate = 60; std::vector<int> kfs = {0, 0, 23, 52, 73, 88, 98, 136, 157, 170, 0, 0}; for (auto i : kfs) { insert(i); } renderer->tone_mapper.params.exposure_value = 0; renderer->tone_mapper.params_dirty = true; update_curve = true; } if (ImGui::Button("preset train")) { camera_spline.keyframes.clear(); camera_spline.frame_rate = 60; std::vector<int> kfs = {0, 0, 13, 20, 30, 40, 50, 207, 95, 100, 110, 120, 130, 140, 150, 160, 0, 0}; for (auto i : kfs) { insert(i); } renderer->tone_mapper.params.exposure_value = scene->scene->frames[kfs[0]].exposure_value; renderer->tone_mapper.params_dirty = true; update_curve = true; } if (ImGui::Button("preset kemenate")) { ::camera->position = vec4(7.79858, 1.07699, -0.849739, 1); ::camera->rot = quat(0.731483, -0.00347084, 0.68185, 0.00113975); } if (ImGui::Button("preset boat")) { camera_spline.keyframes.clear(); camera_spline.frame_rate = 60; std::vector<int> kfs = {// outer circle 568, 568, 568, 590, 679, 556, 68, 101, 146, 190, 224, 290, 346, 446, 490, 590, 194, // inner 442, 447, 462, 474, 475, 477, 372, // close up sign 543, 548, 548, 541, 398, // end 396, 664, 663, 663, 663}; for (auto i : kfs) { insert(i); } renderer->tone_mapper.params.exposure_value = 14.1; renderer->tone_mapper.params_dirty = true; renderer->tone_mapper.tm_operator = 4; neural_renderer->use_gl_tonemapping = true; camera_spline.time_in_seconds = 30; downscale_gt = true; update_curve = true; } if (ImGui::Button("preset boat hdr stuff")) { camera_spline.keyframes.clear(); camera_spline.frame_rate = 30; std::vector<int> kfs = {663, 663, 663, 663}; for (auto i : kfs) { insert(i); } renderer->tone_mapper.params.exposure_value = 14.1; renderer->tone_mapper.params_dirty = true; renderer->tone_mapper.tm_operator = 4; auto exp_ref = scene->scene->frames[kfs[0]].exposure_value; auto exp_target = 13; Eigen::Matrix<double, -1, 1> x(1); for (auto& k : camera_spline.keyframes) { k.user_data = x; } camera_spline.keyframes[0].user_data(0) = exp_ref; camera_spline.keyframes[1].user_data(0) = exp_ref; camera_spline.keyframes[2].user_data(0) = exp_target; camera_spline.keyframes[3].user_data(0) = exp_target; hdr_video_gen = true; camera_spline.time_in_seconds = 15; update_curve = true; } if (ImGui::Button("playground extrapolation1")) { ::camera->position = vec4(2.97414, -2.65628, 4.64867, 1); ::camera->rot = quat(0.0477469, 0.270376, -0.280752, 0.919671); ::camera->calculateModel(); ::camera->updateFromModel(); std::cout << Sophus::SE3f::fitToSE3(camera->model * GL2CVView()).cast<double>() << std::endl; std::cout << Sophus::SE3f::fitToSE3(camera->model * GL2CVView()).cast<double>().inverse() << std::endl; } if (ImGui::Button("playground extrapolation2")) { camera->position = vec4(-3.72784, -2.68887, -5.74922, 1); camera->rot = quat(-0.190701, -0.93891, -0.0748287, 0.276543); ::camera->calculateModel(); ::camera->updateFromModel(); std::cout << Sophus::SE3f::fitToSE3(camera->model * GL2CVView()).cast<double>() << std::endl; std::cout << Sophus::SE3f::fitToSE3(camera->model * GL2CVView()).cast<double>().inverse() << std::endl; } update_curve |= camera_spline.imgui(); if (ImGui::Button("add yellow frame")) { if (scene->selected_capture >= 0) { insert(scene->selected_capture); update_curve = true; } } ImGui::SameLine(); if (ImGui::Button("remove yellow frame")) { int id = -1; for (int i = 0; i < camera_spline.keyframes.size(); ++i) { if (camera_spline.keyframes[i].user_index == scene->selected_capture) { id = i; } } std::cout << "remove id " << id << " selected " << scene->selected_capture << std::endl; if (id != -1) { camera_spline.keyframes.erase(camera_spline.keyframes.begin() + id); update_curve = true; } } if (ImGui::Button("add gl camera")) { SplineKeyframe kf; kf.user_index = 0; kf.pose = Sophus::SE3f::fitToSE3(scene->scene_camera.model * GL2CVView()).cast<double>(); camera_spline.Insert(kf); update_curve = true; } if (update_curve) { for (auto& f : scene->scene->frames) { f.display_color = vec4(1, 0, 0, 1); } for (auto& kf : camera_spline.keyframes) { scene->scene->frames[kf.user_index].display_color = vec4(0, 1, 0, 1); } camera_spline.updateCurve(); auto mesh = camera_spline.ProxyMesh(); if (mesh.NumVertices() > 0) { spline_mesh = std::make_shared<LineVertexColoredAsset>( mesh.SetVertexColor(exp2(scene->scene->dataset_params.scene_exposure_value) * vec4(0, 1, 0, 1))); } } if (!is_recording && ImGui::Button("start recording")) { SAIGA_ASSERT(neural_renderer); neural_renderer->current_best_gt = -1; is_recording = true; traj = camera_spline.Trajectory(); current_frame = 0; std::filesystem::create_directories(out_dir); if (record_debug) { std::filesystem::remove_all(out_dir + "/debug"); std::filesystem::create_directories(out_dir + "/debug"); } if (record_gt) { std::filesystem::remove_all(out_dir + "/gt"); std::filesystem::create_directories(out_dir + "/gt"); } if (record_neural) { std::filesystem::remove_all(out_dir + "/neural"); std::filesystem::create_directories(out_dir + "/neural"); } } if (is_recording && !traj.empty()) { auto frame = traj[current_frame]; mat4 model = frame.pose.matrix().cast<float>() * CV2GLView(); if (interpolate_exposure) { float alpha = 0.001; auto new_exp = scene->scene->frames[neural_renderer->current_best_gt].exposure_value; renderer->tone_mapper.params.exposure_value = (1 - alpha) * renderer->tone_mapper.params.exposure_value + alpha * new_exp; renderer->tone_mapper.params_dirty = true; } if (hdr_video_gen) { auto new_exp = frame.user_data(0); renderer->tone_mapper.params.exposure_value = new_exp; renderer->tone_mapper.params_dirty = true; } ::camera->setModelMatrix(model); ::camera->updateFromModel(); } } int main(int argc, char* argv[]) { std::cout << "Git ref: " << GIT_SHA1 << std::endl; float render_scale = 1.0f; std::string scene_dir; CLI::App app{"ADOP Viewer for Scenes", "adop_viewer"}; app.add_option("--scene_dir", scene_dir)->required(); app.add_option("--render_scale", render_scale); CLI11_PARSE(app, argc, argv); // This should be only called if this is a sample located in saiga/samples initSaigaSample(); WindowParameters windowParameters; OpenGLParameters openglParameters; DeferredRenderingParameters rendererParameters; windowParameters.fromConfigFile("config.ini"); rendererParameters.hdr = true; auto window = std::make_unique<WindowType>(windowParameters, openglParameters); auto renderer = std::make_unique<DeferredRenderer>(*window, rendererParameters); MainLoopParameters mlp; ADOPViewer viewer(scene_dir, std::move(renderer), std::move(window)); viewer.render_scale = render_scale; viewer.run(mlp); }
32.658065
118
0.562031
[ "mesh", "geometry", "render", "object", "vector", "model" ]
ce70755902d4765bbecb17f81e4c8ae65fb2a2b7
34,321
cpp
C++
src/gridcoin/upgrade.cpp
barton2526/Gridcoin-Research
636935836245be3ed9a5131e31a5029e95c0567a
[ "MIT" ]
366
2015-02-01T13:39:21.000Z
2018-05-24T15:30:57.000Z
src/gridcoin/upgrade.cpp
barton2526/Gridcoin-Research
636935836245be3ed9a5131e31a5029e95c0567a
[ "MIT" ]
897
2015-01-13T19:30:36.000Z
2018-05-26T09:59:24.000Z
src/gridcoin/upgrade.cpp
barton2526/Gridcoin-Research
636935836245be3ed9a5131e31a5029e95c0567a
[ "MIT" ]
226
2015-01-05T07:44:32.000Z
2018-05-25T18:28:46.000Z
// Copyright (c) 2014-2021 The Gridcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or https://opensource.org/licenses/mit-license.php. #include "gridcoin/upgrade.h" #include "util.h" #include "init.h" #include <algorithm> #include <univalue.h> #include <vector> #include <boost/thread.hpp> #include <boost/exception/exception.hpp> #include <boost/algorithm/string/case_conv.hpp> #include <iostream> #include <zip.h> #include <openssl/sha.h> using namespace GRC; SnapshotExtractStatus GRC::ExtractStatus; bool GRC::fCancelOperation = false; Upgrade::Upgrade() { DownloadStatus.Reset(); ExtractStatus.Reset(); } void Upgrade::ScheduledUpdateCheck() { std::string VersionResponse = ""; CheckForLatestUpdate(VersionResponse); } bool Upgrade::CheckForLatestUpdate(std::string& client_message_out, bool ui_dialog, bool snapshotrequest) { // If testnet skip this || If the user changes this to disable while wallet running just drop out of here now. // (Need a way to remove items from scheduler.) if (fTestNet || (gArgs.GetBoolArg("-disableupdatecheck", false) && !snapshotrequest)) return false; Http VersionPull; std::string GithubResponse = ""; std::string VersionResponse = ""; // We receive the response and it's in a json reply UniValue Response(UniValue::VOBJ); try { VersionResponse = VersionPull.GetLatestVersionResponse(); } catch (const std::runtime_error& e) { return error("%s: Exception occurred while checking for latest update. (%s)", __func__, e.what()); } if (VersionResponse.empty()) { LogPrintf("WARNING %s: No Response from GitHub", __func__); return false; } std::string GithubReleaseData = ""; std::string GithubReleaseTypeData = ""; std::string GithubReleaseBody = ""; std::string GithubReleaseType = ""; try { Response.read(VersionResponse); // Get the information we need: // 'body' for information about changes // 'tag_name' for version // 'name' for checking if it is a mandatory or leisure GithubReleaseData = find_value(Response, "tag_name").get_str(); GithubReleaseTypeData = find_value(Response, "name").get_str(); GithubReleaseBody = find_value(Response, "body").get_str(); } catch (std::exception& ex) { error("%s: Exception occurred while parsing json response (%s)", __func__, ex.what()); return false; } GithubReleaseTypeData = ToLower(GithubReleaseTypeData); if (GithubReleaseTypeData.find("leisure") != std::string::npos) GithubReleaseType = _("leisure"); else if (GithubReleaseTypeData.find("mandatory") != std::string::npos) GithubReleaseType = _("mandatory"); else GithubReleaseType = _("unknown"); // Parse version data std::vector<std::string> GithubVersion; std::vector<int> LocalVersion; ParseString(GithubReleaseData, '.', GithubVersion); LocalVersion.push_back(CLIENT_VERSION_MAJOR); LocalVersion.push_back(CLIENT_VERSION_MINOR); LocalVersion.push_back(CLIENT_VERSION_REVISION); if (GithubVersion.size() != 4) { error("%s: Got malformed version (%s)", __func__, GithubReleaseData); return false; } bool NewVersion = false; bool NewMandatory = false; try { // Left to right version numbers. // 3 numbers to check for production. for (unsigned int x = 0; x < 3; x++) { int github_version = 0; if (!ParseInt(GithubVersion[x], &github_version)) { throw std::invalid_argument("Failed to parse GitHub version from official GitHub project repo."); } if (github_version > LocalVersion[x]) { NewVersion = true; if (x < 2) { NewMandatory = true; } break; } } } catch (std::exception& ex) { error("%s: Exception occurred checking client version against GitHub version (%s)", __func__, ToString(ex.what())); return false; } if (!NewVersion) return NewVersion; // New version was found client_message_out = _("Local version: ") + strprintf("%d.%d.%d.%d", CLIENT_VERSION_MAJOR, CLIENT_VERSION_MINOR, CLIENT_VERSION_REVISION, CLIENT_VERSION_BUILD) + "\r\n"; client_message_out.append(_("GitHub version: ") + GithubReleaseData + "\r\n"); client_message_out.append(_("This update is ") + GithubReleaseType + "\r\n\r\n"); // For snapshot requests we will handle things differently after this point if (snapshotrequest && NewMandatory) return NewVersion; if (NewMandatory) client_message_out.append(_("WARNING: A mandatory release is available. Please upgrade as soon as possible.") + "\n"); std::string ChangeLog = GithubReleaseBody; if (ui_dialog) uiInterface.UpdateMessageBox(client_message_out, ChangeLog); return NewVersion; } void Upgrade::SnapshotMain() { std::cout << std::endl; std::cout << _("Snapshot Process Has Begun.") << std::endl; std::cout << _("Warning: Ending this process after Stage 2 will result in syncing from 0 or an " "incomplete/corrupted blockchain.") << std::endl << std::endl; // Verify a mandatory release is not available before we continue to snapshot download. std::string VersionResponse = ""; if (CheckForLatestUpdate(VersionResponse, false, true)) { std::cout << this->ResetBlockchainMessages(UpdateAvailable) << std::endl; std::cout << this->ResetBlockchainMessages(GithubResponse) << std::endl; std::cout << VersionResponse << std::endl; throw std::runtime_error(_("Failed to download snapshot as mandatory client is available for download.")); } Progress progress; progress.SetType(Progress::Type::SnapshotDownload); // Create a worker thread to do all of the heavy lifting. We are going to use a ping-pong workflow state here, // with progress Type as the trigger. boost::thread WorkerMainThread(std::bind(&Upgrade::WorkerMain, boost::ref(progress))); while (!DownloadStatus.GetSnapshotDownloadComplete()) { if (DownloadStatus.GetSnapshotDownloadFailed()) { WorkerMainThread.interrupt(); WorkerMainThread.join(); throw std::runtime_error("Failed to download snapshot.zip; See debug.log"); } if (progress.Update(DownloadStatus.GetSnapshotDownloadProgress(), DownloadStatus.GetSnapshotDownloadSpeed(), DownloadStatus.GetSnapshotDownloadAmount(), DownloadStatus.GetSnapshotDownloadSize())) { std::cout << progress.Status() << std::flush; } UninterruptibleSleep(std::chrono::milliseconds{1000}); } // This is needed in some spots as the download can complete before the next progress update occurs so just 100% here // as it was successful if (progress.Update(100, -1, DownloadStatus.GetSnapshotDownloadSize(), DownloadStatus.GetSnapshotDownloadSize())) { std::cout << progress.Status() << std::flush; } std::cout << std::endl; progress.SetType(Progress::Type::SHA256SumVerification); while (!DownloadStatus.GetSHA256SUMComplete()) { if (DownloadStatus.GetSHA256SUMFailed()) { WorkerMainThread.interrupt(); WorkerMainThread.join(); throw std::runtime_error("Failed to verify SHA256SUM of snapshot.zip; See debug.log"); } if (progress.Update(DownloadStatus.GetSHA256SUMProgress())) { std::cout << progress.Status() << std::flush; } UninterruptibleSleep(std::chrono::milliseconds{1000}); } if (progress.Update(100)) std::cout << progress.Status() << std::flush; std::cout << std::endl; progress.SetType(Progress::Type::CleanupBlockchainData); while (!DownloadStatus.GetCleanupBlockchainDataComplete()) { if (DownloadStatus.GetCleanupBlockchainDataFailed()) { WorkerMainThread.interrupt(); WorkerMainThread.join(); throw std::runtime_error("Failed to cleanup previous blockchain data prior to extraction of snapshot.zip; " "See debug.log"); } if (progress.Update(DownloadStatus.GetCleanupBlockchainDataProgress())) { std::cout << progress.Status() << std::flush; } UninterruptibleSleep(std::chrono::milliseconds{1000}); } if (progress.Update(100)) std::cout << progress.Status() << std::flush; std::cout << std::endl; progress.SetType(Progress::Type::SnapshotExtraction); while (!ExtractStatus.GetSnapshotExtractComplete()) { if (ExtractStatus.GetSnapshotExtractFailed()) { WorkerMainThread.interrupt(); WorkerMainThread.join(); // Do this without checking on success, If it passed in stage 3 it will pass here. CleanupBlockchainData(); throw std::runtime_error("Failed to extract snapshot.zip; See debug.log"); } if (progress.Update(ExtractStatus.GetSnapshotExtractProgress())) std::cout << progress.Status() << std::flush; UninterruptibleSleep(std::chrono::milliseconds{1000}); } if (progress.Update(100)) std::cout << progress.Status() << std::flush; std::cout << std::endl; // This interrupt-join needs to be here to ensure the WorkerMain interrupts the while loop and collapses before the // Progress object that was passed to it is destroyed. WorkerMainThread.interrupt(); WorkerMainThread.join(); std::cout << _("Snapshot Process Complete!") << std::endl; return; } void Upgrade::WorkerMain(Progress& progress) { // The "steps" are triggered in SnapshotMain but processed here in this switch statement. bool finished = false; while (!finished && !fCancelOperation) { boost::this_thread::interruption_point(); switch (progress.GetType()) { case Progress::Type::SnapshotDownload: if (DownloadStatus.GetSnapshotDownloadFailed()) { finished = true; return; } else if (!DownloadStatus.GetSnapshotDownloadComplete()) { DownloadSnapshot(); } break; case Progress::Type::SHA256SumVerification: if (DownloadStatus.GetSHA256SUMFailed()) { finished = true; return; } else if (!DownloadStatus.GetSHA256SUMComplete()) { VerifySHA256SUM(); } break; case Progress::Type::CleanupBlockchainData: if (DownloadStatus.GetCleanupBlockchainDataFailed()) { finished = true; return; } else if (!DownloadStatus.GetCleanupBlockchainDataComplete()) { CleanupBlockchainData(); } break; case Progress::Type::SnapshotExtraction: if (ExtractStatus.GetSnapshotExtractFailed()) { finished = true; return; } else if (!ExtractStatus.GetSnapshotExtractComplete()) { ExtractSnapshot(); } } UninterruptibleSleep(std::chrono::milliseconds{1000}); } } void Upgrade::DownloadSnapshot() { // Download the snapshot.zip Http HTTPHandler; try { HTTPHandler.DownloadSnapshot(); } catch(std::runtime_error& e) { error("%s: Exception occurred while attempting to download snapshot (%s)", __func__, e.what()); DownloadStatus.SetSnapshotDownloadFailed(true); return; } LogPrint(BCLog::LogFlags::VERBOSE, "INFO: %s: Snapshot download complete.", __func__); DownloadStatus.SetSnapshotDownloadComplete(true); return; } void Upgrade::VerifySHA256SUM() { Http HTTPHandler; std::string ServerSHA256SUM = ""; try { ServerSHA256SUM = HTTPHandler.GetSnapshotSHA256(); } catch (std::runtime_error& e) { error("%s: Exception occurred while attempting to retrieve snapshot SHA256SUM (%s)", __func__, e.what()); DownloadStatus.SetSHA256SUMFailed(true); return; } if (ServerSHA256SUM.empty()) { error("%s: Empty SHA256SUM returned from server.", __func__); DownloadStatus.SetSHA256SUMFailed(true); return; } unsigned char digest[SHA256_DIGEST_LENGTH]; SHA256_CTX ctx; SHA256_Init(&ctx); fs::path fileloc = GetDataDir() / "snapshot.zip"; unsigned char *buffer[32768]; int bytesread = 0; CAutoFile file(fsbridge::fopen(fileloc, "rb"), SER_DISK, CLIENT_VERSION); if (file.IsNull()) { error("%s: Failed to open snapshot.zip.", __func__); DownloadStatus.SetSHA256SUMFailed(true); return; } unsigned int total_reads = fs::file_size(fileloc) / sizeof(buffer) + 1; unsigned int read_count = 0; while ((bytesread = fread(buffer, 1, sizeof(buffer), file.Get()))) { SHA256_Update(&ctx, buffer, bytesread); ++read_count; DownloadStatus.SetSHA256SUMProgress(read_count * 100 / total_reads); } SHA256_Final(digest, &ctx); const std::vector<unsigned char> digest_vector(digest, digest + SHA256_DIGEST_LENGTH); std::string FileSHA256SUM = HexStr(digest_vector); if (ServerSHA256SUM == FileSHA256SUM) { LogPrint(BCLog::LogFlags::VERBOSE, "INFO %s: SHA256SUM verification successful (Server = %s, File = %s).", __func__, ServerSHA256SUM, FileSHA256SUM); DownloadStatus.SetSHA256SUMProgress(100); DownloadStatus.SetSHA256SUMComplete(true); return; } else { error("%s: Mismatch of SHA256SUM of snapshot.zip (Server = %s / File = %s)", __func__, ServerSHA256SUM, FileSHA256SUM); DownloadStatus.SetSHA256SUMFailed(true); return; } } bool Upgrade::GetActualCleanupPath(fs::path& actual_cleanup_path) { actual_cleanup_path = GetDataDir(); // This is required because of problems with junction point handling in the boost filesystem library. Please see // https://github.com/boostorg/filesystem/issues/125. We are not quite ready to switch over to std::filesystem yet. // 1. I don't know whether the issue is fixed there, and // 2. Not all C++17 compilers have the filesystem headers, since this was merged from boost in 2017. // // I don't believe it is very common for Windows users to redirect the Gridcoin data directory with a junction point, // but it is certainly possible. We should handle it as gracefully as possible. if (fs::is_symlink(actual_cleanup_path)) { LogPrintf("INFO: %s: Data directory is a symlink.", __func__); try { LogPrintf("INFO: %s: True path for the symlink is %s.", __func__, fs::read_symlink(actual_cleanup_path).string()); actual_cleanup_path = fs::read_symlink(actual_cleanup_path); } catch (fs::filesystem_error &ex) { error("%s: The data directory symlink or junction point cannot be resolved to the true canonical path. " "This can happen on Windows. Please change the data directory specified to the actual true path " "using the -datadir=<path> option and try again.", __func__); DownloadStatus.SetCleanupBlockchainDataFailed(true); return false; } } return true; } void Upgrade::CleanupBlockchainData(bool include_blockchain_data_files) { fs::path CleanupPath; if (!GetActualCleanupPath(CleanupPath)) return; unsigned int total_items = 0; unsigned int items = 0; // We must delete previous blockchain data // txleveldb // accrual // blk*.dat fs::directory_iterator IterEnd; // Count for progress bar first try { for (fs::directory_iterator Iter(CleanupPath); Iter != IterEnd; ++Iter) { if (fs::is_directory(Iter->path())) { if (fs::relative(Iter->path(), CleanupPath) == (fs::path) "txleveldb") { for (fs::recursive_directory_iterator it(Iter->path()); it != fs::recursive_directory_iterator(); ++it) { ++total_items; } } if (fs::relative(Iter->path(), CleanupPath) == (fs::path) "accrual") { for (fs::recursive_directory_iterator it(Iter->path()); it != fs::recursive_directory_iterator(); ++it) { ++total_items; } } // If it was a directory no need to check if a regular file below. continue; } else if (fs::is_regular_file(*Iter) && include_blockchain_data_files) { size_t FileLoc = Iter->path().filename().string().find("blk"); if (FileLoc != std::string::npos) { std::string filetocheck = Iter->path().filename().string(); // Check it ends with .dat and starts with blk if (filetocheck.substr(0, 3) == "blk" && filetocheck.substr(filetocheck.length() - 4, 4) == ".dat") { ++total_items; } } } } } catch (fs::filesystem_error &ex) { error("%s: Exception occurred: %s", __func__, ex.what()); DownloadStatus.SetCleanupBlockchainDataFailed(true); return; } if (!total_items) { // Nothing to clean up! DownloadStatus.SetCleanupBlockchainDataComplete(true); return; } // Now try the cleanup. try { // Remove the files. We iterate as we know blk* will exist more and more in future as well for (fs::directory_iterator Iter(CleanupPath); Iter != IterEnd; ++Iter) { if (fs::is_directory(Iter->path())) { if (fs::relative(Iter->path(), CleanupPath) == (fs::path) "txleveldb") { for (fs::recursive_directory_iterator it(Iter->path()); it != fs::recursive_directory_iterator();) { fs::path filepath = *it++; if (fs::remove(filepath)) { ++items; DownloadStatus.SetCleanupBlockchainDataProgress(items * 100 / total_items); } else { DownloadStatus.SetCleanupBlockchainDataFailed(true); return; } } } if (fs::relative(Iter->path(), CleanupPath) == (fs::path) "accrual") { for (fs::recursive_directory_iterator it(Iter->path()); it != fs::recursive_directory_iterator();) { fs::path filepath = *it++; if (fs::remove(filepath)) { ++items; DownloadStatus.SetCleanupBlockchainDataProgress(items * 100 / total_items); } else { DownloadStatus.SetCleanupBlockchainDataFailed(true); return; } } } // If it was a directory no need to check if a regular file below. continue; } else if (fs::is_regular_file(*Iter) && include_blockchain_data_files) { size_t FileLoc = Iter->path().filename().string().find("blk"); if (FileLoc != std::string::npos) { std::string filetocheck = Iter->path().filename().string(); // Check it ends with .dat and starts with blk if (filetocheck.substr(0, 3) == "blk" && filetocheck.substr(filetocheck.length() - 4, 4) == ".dat") { if (fs::remove(*Iter)) { ++items; DownloadStatus.SetCleanupBlockchainDataProgress(items * 100 / total_items); } else { DownloadStatus.SetCleanupBlockchainDataFailed(true); return; } } } } } } catch (fs::filesystem_error &ex) { error("%s: Exception occurred: %s", __func__, ex.what()); DownloadStatus.SetCleanupBlockchainDataFailed(true); return; } LogPrint(BCLog::LogFlags::VERBOSE, "INFO: %s: Prior blockchain data cleanup successful.", __func__); DownloadStatus.SetCleanupBlockchainDataProgress(100); DownloadStatus.SetCleanupBlockchainDataComplete(true); return; } void Upgrade::ExtractSnapshot() { try { zip_error_t* err = new zip_error_t; struct zip* ZipArchive; std::string archive_file_string = (GetDataDir() / "snapshot.zip").string(); const char* archive_file = archive_file_string.c_str(); int ze; ZipArchive = zip_open(archive_file, 0, &ze); zip_error_init_with_code(err, ze); if (ZipArchive == nullptr) { ExtractStatus.SetSnapshotExtractFailed(true); error("%s: Error opening snapshot.zip as zip archive: %s", __func__, zip_error_strerror(err)); return; } fs::path ExtractPath = GetDataDir(); struct zip_stat ZipStat; int64_t lastupdated = GetAdjustedTime(); long long totaluncompressedsize = 0; long long currentuncompressedsize = 0; uint64_t entries = (uint64_t) zip_get_num_entries(ZipArchive, 0); // Let's scan for total size uncompressed so we can do a detailed progress for the watching user for (u_int64_t j = 0; j < entries; ++j) { if (zip_stat_index(ZipArchive, j, 0, &ZipStat) == 0) { if (ZipStat.name[strlen(ZipStat.name) - 1] != '/') totaluncompressedsize += ZipStat.size; } } // This protects against a divide by error below and properly returns false // if the zip file has no entries. if (!totaluncompressedsize) { ExtractStatus.SetSnapshotZipInvalid(true); error("%s: Error - snapshot.zip has no entries", __func__); return; } // Now extract for (u_int64_t i = 0; i < entries; ++i) { if (zip_stat_index(ZipArchive, i, 0, &ZipStat) == 0) { // Does this require a directory if (ZipStat.name[strlen(ZipStat.name) - 1] == '/') { fs::create_directory(ExtractPath / ZipStat.name); } else { struct zip_file* ZipFile; ZipFile = zip_fopen_index(ZipArchive, i, 0); if (!ZipFile) { ExtractStatus.SetSnapshotExtractFailed(true); error("%s: Error opening file %s within snapshot.zip", __func__, ZipStat.name); return; } fs::path ExtractFileString = ExtractPath / ZipStat.name; CAutoFile ExtractFile(fsbridge::fopen(ExtractFileString, "wb"), SER_DISK, CLIENT_VERSION); if (ExtractFile.IsNull()) { ExtractStatus.SetSnapshotExtractFailed(true); error("%s: Error opening file %s on filesystem", __func__, ZipStat.name); return; } int64_t sum = 0; while ((uint64_t) sum < ZipStat.size) { int64_t len = 0; // Note that using a buffer larger than this risks crashes on macOS. char Buf[256*1024]; boost::this_thread::interruption_point(); len = zip_fread(ZipFile, &Buf, 256*1024); if (len < 0) { ExtractStatus.SetSnapshotExtractFailed(true); error("%s: Failed to read zip buffer", __func__); return; } fwrite(Buf, 1, (uint64_t) len, ExtractFile.Get()); sum += len; currentuncompressedsize += len; // Update Progress every 1 second if (GetAdjustedTime() > lastupdated) { lastupdated = GetAdjustedTime(); ExtractStatus.SetSnapshotExtractProgress(currentuncompressedsize * 100 / totaluncompressedsize); } } zip_fclose(ZipFile); } } } if (zip_close(ZipArchive) == -1) { ExtractStatus.SetSnapshotExtractFailed(true); error("%s: Failed to close snapshot.zip", __func__); return; } } catch (boost::thread_interrupted&) { ExtractStatus.SetSnapshotExtractFailed(true); return; } catch (std::exception& e) { error("%s: Error occurred during snapshot zip file extraction: %s", __func__, e.what()); ExtractStatus.SetSnapshotExtractFailed(true); return; } LogPrint(BCLog::LogFlags::VERBOSE, "INFO: %s: Snapshot.zip extraction successful.", __func__); ExtractStatus.SetSnapshotExtractProgress(100); ExtractStatus.SetSnapshotExtractComplete(true); return; } void Upgrade::DeleteSnapshot() { // File is out of scope now check if it exists and if so delete it. try { fs::path snapshotpath = GetDataDir() / "snapshot.zip"; if (fs::exists(snapshotpath)) if (fs::is_regular_file(snapshotpath)) fs::remove(snapshotpath); } catch (fs::filesystem_error& e) { LogPrintf("Snapshot Downloader: Exception occurred while attempting to delete snapshot (%s)", e.code().message()); } } bool Upgrade::ResetBlockchainData(bool include_blockchain_data_files) { CleanupBlockchainData(include_blockchain_data_files); return (DownloadStatus.GetCleanupBlockchainDataComplete() && !DownloadStatus.GetCleanupBlockchainDataFailed()); } bool Upgrade::MoveBlockDataFiles(std::vector<std::pair<fs::path, uintmax_t>>& block_data_files) { fs::path cleanup_path; if (!GetActualCleanupPath(cleanup_path)) return false; fs::directory_iterator IterEnd; try { for (fs::directory_iterator Iter(cleanup_path); Iter != IterEnd; ++Iter) { if (fs::is_regular_file(*Iter)) { size_t FileLoc = Iter->path().filename().string().find("blk"); if (FileLoc != std::string::npos) { std::string filetocheck = Iter->path().filename().string(); // Check it ends with .dat and starts with blk if (filetocheck.substr(0, 3) == "blk" && filetocheck.substr(filetocheck.length() - 4, 4) == ".dat") { fs::path new_name = *Iter; new_name.replace_extension(".dat.orig"); uintmax_t file_size = fs::file_size(Iter->path()); // Rename with orig as the extension, because ProcessBlock will load blocks into a new block data // file. fs::rename(*Iter, new_name); block_data_files.push_back(std::make_pair(new_name, file_size)); } } } } } catch (fs::filesystem_error &ex) { error("%s: Exception occurred: %s. Failed to rename block data files to blk*.dat.orig in preparation for " "reindexing.", __func__, ex.what()); return false; } return true; } bool Upgrade::LoadBlockchainData(std::vector<std::pair<fs::path, uintmax_t>>& block_data_files, bool sort, bool cleanup_imported_files) { bool successful = true; uintmax_t total_size = 0; uintmax_t cumulative_size = 0; for (const auto& iter : block_data_files) { total_size += iter.second; } if (!total_size) return false; // This conditional sort is necessary to allow for two different desired behaviors. -reindex requires the filesystem // entries to be sorted, because the order of files in a filesystem iterator in a directory is not guaranteed. On the // other hand, for multiple -loadblock arguments, the order of the arguments should be preserved. if (sort) std::sort(block_data_files.begin(), block_data_files.end()); try { for (const auto& iter : block_data_files) { unsigned int percent_start = cumulative_size * (uintmax_t) 100 / total_size; cumulative_size += iter.second; unsigned int percent_end = cumulative_size * (uintmax_t) 100 / total_size; FILE *block_data_file = fsbridge::fopen(iter.first, "rb"); LogPrintf("INFO: %s: Loading blocks from %s.", __func__, iter.first.filename().string()); if (!LoadExternalBlockFile(block_data_file, iter.second, percent_start, percent_end)) { successful = false; break; } } } catch (fs::filesystem_error &ex) { error("%s: Exception occurred: %s. Failure occurred during attempt to load blocks from original " "block data file(s).", __func__, ex.what()); successful = false; } if (successful) { // Only delete the source files that were imported if cleanup_imported_files is set to true if (cleanup_imported_files) { try { for (const auto& iter : block_data_files) { if (!fs::remove(iter.first)) { LogPrintf("WARN: %s: Reindexing of the blockchain was successful; however, one or more of " "the original block data files (%s) was not able to be deleted. You " "will have to delete this file manually.", __func__, iter.first.filename().string()); } } } catch (fs::filesystem_error &ex) { LogPrintf("WARN: %s: Exception occurred: %s. This error occurred while attempting to delete the original " "block data files (blk*.dat.orig). You will have to delete these manually.", __func__, ex.what()); } } } else { error("%s: A failure occurred during the reindexing of the block data files. The blockchain state is invalid and " "you should restart the wallet with the -resetblockchaindata option to clear out the blockchain database " "and re-sync the blockchain from the network.", __func__); DownloadStatus.SetCleanupBlockchainDataFailed(true); return false; } LogPrintf("INFO: %s: Reindex of the blockchain data was successful.", __func__); return true; } std::string Upgrade::ResetBlockchainMessages(ResetBlockchainMsg _msg) { std::stringstream stream; switch (_msg) { case CleanUp: { stream << _("Datadir: "); stream << GetDataDir().string(); stream << "\r\n\r\n"; stream << _("Due to the failure to delete the blockchain data you will be required to manually delete the data " "before starting your wallet."); stream << "\r\n"; stream << _("Failure to do so will result in undefined behaviour or failure to start wallet."); stream << "\r\n\r\n"; stream << _("You will need to delete the following."); stream << "\r\n\r\n"; stream << _("Files:"); stream << "\r\n"; stream << "blk000*.dat"; stream << "\r\n\r\n"; stream << _("Directories:"); stream << "\r\n"; stream << "txleveldb"; stream << "\r\n"; stream << "accrual"; break; } case UpdateAvailable: stream << _("Unable to download a snapshot, as the wallet has detected that a new mandatory " "version is available for install. The mandatory upgrade must be installed before " "the snapshot can be downloaded and applied."); break; case GithubResponse: stream << _("Latest Version GitHub data response:"); break; } const std::string& output = stream.str(); return output; }
32.655566
126
0.56496
[ "object", "vector" ]
ce7351fe891be6148b36884d803570256747069c
1,094
cpp
C++
src/math.cpp
liamst19/asteroids-study
809e6573eb45800ba06ec8e03e7103815188a70b
[ "MIT" ]
null
null
null
src/math.cpp
liamst19/asteroids-study
809e6573eb45800ba06ec8e03e7103815188a70b
[ "MIT" ]
null
null
null
src/math.cpp
liamst19/asteroids-study
809e6573eb45800ba06ec8e03e7103815188a70b
[ "MIT" ]
null
null
null
/** math.cpp * * Collection of math functions and classes, * specifically a Vector class. */ // ---------------------------------------------------------------- // From Game Programming in C++ by Sanjay Madhav // Copyright (C) 2017 Sanjay Madhav. All rights reserved. // // Released under the BSD License // See LICENSE in root directory for full details. // ---------------------------------------------------------------- // #include "Math.h" // const Vector2d Vector2d::Zero(0.0f, 0.0f); // const Vector2d Vector2d::UnitX(1.0f, 0.0f); // const Vector2d Vector2d::UnitY(0.0f, 1.0f); // const Vector2d Vector2d::NegUnitX(-1.0f, 0.0f); // const Vector2d Vector2d::NegUnitY(0.0f, -1.0f); // Vector2d Vector2d::Transform(const Vector2& vec, const Matrix3& mat, float w /*= 1.0f*/) // { // Vector2d retVal; // retVal.x = vec.x * mat.mat[0][0] + vec.y * mat.mat[1][0] + w * mat.mat[2][0]; // retVal.y = vec.x * mat.mat[0][1] + vec.y * mat.mat[1][1] + w * mat.mat[2][1]; // //ignore w since we aren't returning a new value for it... // return retVal; // }
36.466667
92
0.547532
[ "vector", "transform" ]
ce73cf5bf2dc527dffca35d9c0dce9726f1494cb
6,499
cc
C++
mediapipe/examples/desktop/autoflip/quality/visual_scorer.cc
xiong-jie-y/mediapipe
024f7bf0f1e74149ea92b942cf168ccddf317073
[ "Apache-2.0" ]
47
2019-12-29T02:52:48.000Z
2022-02-21T08:39:14.000Z
mediapipe/examples/desktop/autoflip/quality/visual_scorer.cc
xiong-jie-y/mediapipe
024f7bf0f1e74149ea92b942cf168ccddf317073
[ "Apache-2.0" ]
5
2020-07-28T14:11:21.000Z
2021-05-02T10:11:29.000Z
mediapipe/examples/desktop/autoflip/quality/visual_scorer.cc
xiong-jie-y/mediapipe
024f7bf0f1e74149ea92b942cf168ccddf317073
[ "Apache-2.0" ]
41
2020-01-27T00:30:43.000Z
2022-03-24T01:35:19.000Z
// Copyright 2019 The MediaPipe Authors. // // 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 "mediapipe/examples/desktop/autoflip/quality/visual_scorer.h" #include <math.h> #include <algorithm> #include <cmath> #include <memory> #include <vector> #include "mediapipe/framework/port/opencv_core_inc.h" #include "mediapipe/framework/port/opencv_imgproc_inc.h" #include "mediapipe/framework/port/ret_check.h" #include "mediapipe/framework/port/status.h" #include "mediapipe/framework/port/status_builder.h" // Weight threshold for computing a value. constexpr float kEpsilon = 0.0001; namespace mediapipe { namespace autoflip { namespace { // Crop the given rectangle so that it fits in the given 2D matrix. void CropRectToMat(const cv::Mat& image, cv::Rect* rect) { int x = std::min(std::max(rect->x, 0), image.cols); int y = std::min(std::max(rect->y, 0), image.rows); int w = std::min(std::max(rect->x + rect->width, 0), image.cols) - x; int h = std::min(std::max(rect->y + rect->height, 0), image.rows) - y; *rect = cv::Rect(x, y, w, h); } } // namespace VisualScorer::VisualScorer(const VisualScorerOptions& options) : options_(options) {} mediapipe::Status VisualScorer::CalculateScore(const cv::Mat& image, const SalientRegion& region, float* score) const { const float weight_sum = options_.area_weight() + options_.sharpness_weight() + options_.colorfulness_weight(); // Crop the region to fit in the image. cv::Rect region_rect; if (region.has_location()) { region_rect = cv::Rect(region.location().x(), region.location().y(), region.location().width(), region.location().height()); } else if (region.has_location_normalized()) { region_rect = cv::Rect(region.location_normalized().x() * image.cols, region.location_normalized().y() * image.rows, region.location_normalized().width() * image.cols, region.location_normalized().height() * image.rows); } else { return ::mediapipe::UnknownErrorBuilder(MEDIAPIPE_LOC) << "Unset region location."; } CropRectToMat(image, &region_rect); if (region_rect.area() == 0) { *score = 0; return ::mediapipe::OkStatus(); } // Compute a score based on area covered by this region. const float area_score = options_.area_weight() * region_rect.area() / (image.cols * image.rows); // Convert the visible region to cv::Mat. cv::Mat image_region_mat = image(region_rect); // Compute a score from sharpness. float sharpness_score_result = 0.0; if (options_.sharpness_weight() > kEpsilon) { // TODO: implement a sharpness score or remove this code block. return ::mediapipe::InvalidArgumentErrorBuilder(MEDIAPIPE_LOC) << "sharpness scorer is not yet implemented, please set weight to " "0.0"; } const float sharpness_score = options_.sharpness_weight() * sharpness_score_result; // Compute a colorfulness score. float colorfulness_score = 0; if (options_.colorfulness_weight() > kEpsilon) { MP_RETURN_IF_ERROR( CalculateColorfulness(image_region_mat, &colorfulness_score)); colorfulness_score *= options_.colorfulness_weight(); } *score = (area_score + sharpness_score + colorfulness_score) / weight_sum; if (*score > 1.0f || *score < 0.0f) { LOG(WARNING) << "Score of region outside expected range: " << *score; } return ::mediapipe::OkStatus(); } mediapipe::Status VisualScorer::CalculateColorfulness( const cv::Mat& image, float* colorfulness) const { // Convert the image to HSV. cv::Mat image_hsv; cv::cvtColor(image, image_hsv, CV_RGB2HSV); // Mask out pixels that are too dark or too bright. cv::Mat mask(image.rows, image.cols, CV_8UC1); bool empty_mask = true; for (int x = 0; x < image.cols; ++x) { for (int y = 0; y < image.rows; ++y) { const cv::Vec3b& pixel = image.at<cv::Vec3b>(x, y); const bool is_usable = (std::min(pixel.val[0], std::min(pixel.val[1], pixel.val[2])) < 250 && std::max(pixel.val[0], std::max(pixel.val[1], pixel.val[2])) > 5); mask.at<unsigned char>(y, x) = is_usable ? 255 : 0; if (is_usable) empty_mask = false; } } // If the mask is empty, return. if (empty_mask) { *colorfulness = 0; return ::mediapipe::OkStatus(); } // Generate a 2D histogram (hue/saturation). cv::MatND hs_histogram; const int kHueBins = 10, kSaturationBins = 8; const int kHistogramChannels[] = {0, 1}; const int kHistogramBinNum[] = {kHueBins, kSaturationBins}; const float kHueRange[] = {0, 180}; const float kSaturationRange[] = {0, 256}; const float* kHistogramRange[] = {kHueRange, kSaturationRange}; cv::calcHist(&image_hsv, 1, kHistogramChannels, mask, hs_histogram, 2 /* histogram dims */, kHistogramBinNum, kHistogramRange, true /* uniform */, false /* accumulate */); // Convert to a hue histogram and weigh saturated pixels more. std::vector<float> hue_histogram(kHueBins, 0.0f); float hue_sum = 0.0f; for (int bin_s = 0; bin_s < kSaturationBins; ++bin_s) { const float weight = std::pow(2.0f, bin_s); for (int bin_h = 0; bin_h < kHueBins; ++bin_h) { float value = hs_histogram.at<float>(bin_h, bin_s) * weight; hue_histogram[bin_h] += value; hue_sum += value; } } if (hue_sum == 0.0f) { *colorfulness = 0; return ::mediapipe::OkStatus(); } // Compute the histogram entropy. *colorfulness = 0; for (int bin = 0; bin < kHueBins; ++bin) { float value = hue_histogram[bin] / hue_sum; if (value > 0.0f) { *colorfulness -= value * std::log(value); } } *colorfulness /= std::log(2.0f); return ::mediapipe::OkStatus(); } } // namespace autoflip } // namespace mediapipe
35.513661
80
0.650254
[ "vector" ]
ce74b9ad4e7be2b79a16bfb4b75e9ba778ee3a7b
3,184
cpp
C++
src/trajopt/test/cast-cost-unit.cpp
HARPLab/trajopt
40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4
[ "BSD-2-Clause" ]
250
2015-01-13T04:38:59.000Z
2022-03-09T15:52:54.000Z
src/trajopt/test/cast-cost-unit.cpp
HARPLab/trajopt
40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4
[ "BSD-2-Clause" ]
31
2015-08-19T13:14:56.000Z
2022-03-22T08:08:26.000Z
src/trajopt/test/cast-cost-unit.cpp
HARPLab/trajopt
40e2260d8f1e4d0a6a7a8997927bd65e5f36c3a4
[ "BSD-2-Clause" ]
118
2015-01-08T16:06:50.000Z
2022-03-19T11:44:00.000Z
#include <gtest/gtest.h> #include <openrave-core.h> #include <openrave/openrave.h> #include "trajopt/collision_checker.hpp" #include "utils/stl_to_string.hpp" #include "trajopt/common.hpp" #include "trajopt/problem_description.hpp" #include "sco/optimizers.hpp" #include "trajopt/rave_utils.hpp" #include "osgviewer/osgviewer.hpp" #include <ctime> #include "utils/eigen_conversions.hpp" #include "utils/clock.hpp" #include <boost/foreach.hpp> #include <boost/assign.hpp> #include "utils/config.hpp" #include "trajopt/plot_callback.hpp" #include "trajopt_test_utils.hpp" #include "trajopt/collision_terms.hpp" using namespace trajopt; using namespace std; using namespace OpenRAVE; using namespace util; using namespace boost::assign; string data_dir() { string out = DATA_DIR; return out; } bool plotting=false, verbose=false; #ifdef __CDT_PARSER__ #define TEST(a,b) void asdf() #endif TEST(cast, boxes) { EnvironmentBasePtr env = RaveCreateEnvironment(); ASSERT_TRUE(env->Load(data_dir() + "/boxbot.xml")); ASSERT_TRUE(env->Load(data_dir() + "/box.xml")); KinBodyPtr box = env->GetKinBody("box"); RobotBasePtr boxbot = env->GetRobot("boxbot"); RobotAndDOFPtr rad(new RobotAndDOF(boxbot, IntVec(), DOF_X | DOF_Y, Vector())); rad->GetRobot()->SetActiveDOFs(rad->GetJointIndices(), DOF_X | DOF_Y, Vector()); Json::Value root = readJsonFile(string(DATA_DIR) + "/box_cast_test.json"); DblVec start_dofs; start_dofs += -1.9, 0; rad->SetDOFValues(start_dofs); TrajOptProbPtr prob = ConstructProblem(root, env); TrajArray traj = prob->GetInitTraj(); //shouldn't be necessary: #if 0 ASSERT_TRUE(!!prob); double dist_pen = .02, coeff = 10; prob->addCost(CostPtr(new CollisionCost(dist_pen, coeff, rad, prob->GetVarRow(0), prob->GetVarRow(1)))); prob->addCost(CostPtr(new CollisionCost(dist_pen, coeff, rad, prob->GetVarRow(1), prob->GetVarRow(2)))); CollisionCheckerPtr checker = CollisionChecker::GetOrCreate(*prob->GetEnv()); { vector<Collision> collisions; checker->ContinuousCheckTrajectory(traj, *rad, collisions); } vector<Collision> collisions; cout << "traj: " << endl << traj << endl; checker->CastVsAll(*rad, rad->GetRobot()->GetLinks(), toDblVec(traj.row(0)), toDblVec(traj.row(1)), collisions); cout << collisions.size() << endl; #endif BasicTrustRegionSQP opt(prob); if (plotting) opt.addCallback(PlotCallback(*prob)); opt.initialize(trajToDblVec(prob->GetInitTraj())); opt.optimize(); vector<Collision> collisions; CollisionChecker::GetOrCreate(*env)->ContinuousCheckTrajectory(getTraj(opt.x(), prob->GetVars()), *rad, collisions); RAVELOG_INFO("number of continuous collisions: %i\n", collisions.size()); ASSERT_EQ(collisions.size(), 0); } int main(int argc, char** argv) { { Config config; config.add(new Parameter<bool>("plotting", &plotting, "plotting")); config.add(new Parameter<bool>("verbose", &verbose, "verbose")); CommandParser parser(config); parser.read(argc, argv); } ::testing::InitGoogleTest(&argc, argv); RaveInitialize(false); if (verbose) RaveSetDebugLevel(Level_Debug); int result = RUN_ALL_TESTS(); RaveDestroy(); return result; }
31.215686
118
0.721106
[ "vector" ]
ce74bee3028539d3c538477eb0a21a4e267bcf56
10,090
cpp
C++
src/base/util/UtcDate.cpp
rockstorm101/GMAT
00b6b61a40560c095da3d83dab4ab1e9157f01c7
[ "Apache-2.0" ]
1
2018-09-18T07:09:36.000Z
2018-09-18T07:09:36.000Z
src/base/util/UtcDate.cpp
rockstorm101/GMAT
00b6b61a40560c095da3d83dab4ab1e9157f01c7
[ "Apache-2.0" ]
null
null
null
src/base/util/UtcDate.cpp
rockstorm101/GMAT
00b6b61a40560c095da3d83dab4ab1e9157f01c7
[ "Apache-2.0" ]
2
2020-06-18T04:45:30.000Z
2021-07-20T02:11:54.000Z
//$Id$ //------------------------------------------------------------------------------ // UtcDate //------------------------------------------------------------------------------ // GMAT: General Mission Analysis Tool // // Copyright (c) 2002 - 2015 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration. // All Other Rights Reserved. // // 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. // // Developed jointly by NASA/GSFC and Thinking Systems, Inc. under contract // number S-67573-G // // Author: Linda Jun // Created: 1995/10/18 for GSS project // Modified: // 2003/09/12 Linda Jun - Added member data: descs, stringValues. // Replaced GSSString with std::string. // 2004/05/06 J. Gurganus - See UtcDate.hpp for details. // /** * Provides conversions among various ways representing UTC calendar * dates and times. */ //------------------------------------------------------------------------------ #include <cmath> #include "gmatdefs.hpp" #include "RealUtilities.hpp" // for Round() #include "A1Mjd.hpp" // for A1Mjd #include "UtcDate.hpp" // for UtcDate #include "TimeSystemConverter.hpp" // #include "A1Date.hpp" // for A1Date using namespace GmatTimeConstants; using namespace GmatMathUtil; //--------------------------------- // public methods //--------------------------------- //------------------------------------------------------------------------------ // UtcDate() //------------------------------------------------------------------------------ /** * @note Calls A1Mjd default constructor which creates an object with 0 * second from reference. */ //------------------------------------------------------------------------------ UtcDate::UtcDate() : Date() { } //------------------------------------------------------------------------------ // UtcDate (Integer year, Integer month, Integer day, Integer hour, // Integer minute, Real second) //------------------------------------------------------------------------------ /** * @note Assumes input date is in UTC time system. */ //------------------------------------------------------------------------------ UtcDate::UtcDate (Integer year, Integer month, Integer day, Integer hour, Integer minute, Real second) : Date(year, month, day, hour, minute, second) { } //------------------------------------------------------------------------------ // UtcDate (Integer year, Integer dayOfYear, Integer hour, Integer minute, // Real second) //------------------------------------------------------------------------------ /** * @note Assumes input date is in UTC time system. */ //------------------------------------------------------------------------------ UtcDate::UtcDate (Integer year, Integer dayOfYear, Integer hour, Integer minute, Real second) : Date(year, dayOfYear, hour, minute, second) { } //------------------------------------------------------------------------------ // UtcDate (Integer year, Integer month, Integer day, Real secondsOfDay); //------------------------------------------------------------------------------ /** * @note Assumes input date is in UTC time system. */ //------------------------------------------------------------------------------ UtcDate::UtcDate (Integer year, Integer month, Integer day, Real secondsOfDay) : Date(year, month, day, secondsOfDay) { } //------------------------------------------------------------------------------ // UtcDate (const GmatTimeUtil::CalDate &date) //------------------------------------------------------------------------------ /** * @note Assumes input date is in UTC time system. */ //------------------------------------------------------------------------------ UtcDate::UtcDate (const GmatTimeUtil::CalDate &date) : Date(date) { } //------------------------------------------------------------------------------ // UtcDate (const std::string& time) //------------------------------------------------------------------------------ /** * @param <time> Time in "YYMMDD.hhmmssnnn" format * * @note Assumes input date is in UTC time system. */ //------------------------------------------------------------------------------ UtcDate::UtcDate (const std::string& time) : Date(time) { } //------------------------------------------------------------------------------ // UtcDate (const UtcDate &date) //------------------------------------------------------------------------------ UtcDate::UtcDate (const UtcDate &date) : Date(date) { } //------------------------------------------------------------------------------ // UtcDate operator= (const UtcDate &date) //------------------------------------------------------------------------------ UtcDate UtcDate::operator= (const UtcDate &date) { yearD = date.yearD; monthD = date.monthD; dayD = date.dayD; secondsOfDayD = date.secondsOfDayD; return *this; } //------------------------------------------------------------------------------ // ~UtcDate () //------------------------------------------------------------------------------ UtcDate::~UtcDate () { } // //------------------------------------------------------------------------------ // // Real operator- (const UtcDate &date) const // //------------------------------------------------------------------------------ // Real UtcDate::operator- (const UtcDate &date) const // { // Real offset; // A1Mjd t1(yearD, monthD, dayD, secondsOfDayD); // A1Mjd t2(date.yearD, date.monthD, date.dayD, date.secondsOfDayD); // //loj:offset = t1 - t2; // offset = t1.Subtract(t2); // return offset; // } // //------------------------------------------------------------------------------ // // UtcDate operator+ (const Real seconds) const // //------------------------------------------------------------------------------ // UtcDate UtcDate::operator+ (const Real seconds) const // { // A1Mjd tempTime(*this); // tempTime = tempTime + seconds; // return UtcDate(tempTime); // } // //------------------------------------------------------------------------------ // // UtcDate& operator+= (const Real seconds) // //------------------------------------------------------------------------------ // UtcDate& UtcDate::operator+= (const Real seconds) // { // UtcDate utcDate; // A1Mjd tempTime(*this); // tempTime = tempTime + seconds; // utcDate = UtcDate(tempTime); // *this = utcDate; // return *this; // } // //------------------------------------------------------------------------------ // // UtcDate operator- (const Real seconds) const // //------------------------------------------------------------------------------ // UtcDate UtcDate::operator- (const Real seconds) const // { // A1Mjd tempTime(*this); // tempTime = tempTime - seconds; // return UtcDate(tempTime); // } // //------------------------------------------------------------------------------ // // UtcDate& operator-= (const Real seconds) // //------------------------------------------------------------------------------ // UtcDate& UtcDate::operator-= (const Real seconds) // { // UtcDate utcDate; // A1Mjd tempTime(*this); // tempTime = tempTime - seconds; // utcDate = UtcDate(tempTime); // *this = utcDate; // return *this; // } //------------------------------------------------------------------------------ // A1Date ToA1Date() //------------------------------------------------------------------------------ /** * @note The two time systems label time differently. At any given moment, * the A.1 system is several seconds ahead of the UTC system. This offset * is constant between leap insertions. For example, the instant of time * labeled July 1, 1992, 12:00:27.0343817 in the A.1 system will be labeled * July 1, 1992, 12:00:00 (Noon) in the UTC system. */ //------------------------------------------------------------------------------ // A1Date UtcDate::ToA1Date() // { // A1Date a1Date; // CalDate tempDate; // // convert UTC date to equivalent A1 date // A1Mjd utcMjd(*this); //loj: should subtract leap seconds when A1Mjd is constructed // //a1Date = A1Date(utcMjd); //loj: compile error // return utcMjd.ToA1Date(); // } //------------------------------------------------------------------------------ // Real ToA1Mjd() const //------------------------------------------------------------------------------ /** * Converts from UtcDate to A1 Modified Julian date. * * @return A1 Modified Julian Date */ //------------------------------------------------------------------------------ Real UtcDate::ToA1Mjd() const { Integer year = GetYear(); Integer month = GetMonth(); Integer day = GetDay(); Integer hour = GetHour(); Integer minute = GetMinute(); Real second = GetSecond(); // Convert to Modified Julian date Real utcmjd = ModifiedJulianDate(year,month,day,hour,minute,second); // Convert to A1Mjd Real a1Mjd = TimeConverterUtil::Convert(utcmjd, TimeConverterUtil::UTCMJD, TimeConverterUtil::A1MJD); return a1Mjd; }
37.37037
105
0.402478
[ "object" ]
706aec04f2169e9bde5dca0e68a88b8ff2521c6b
6,646
cpp
C++
Gems/AWSGameLift/Code/AWSGameLiftClient/Tests/Activity/AWSGameLiftStartMatchmakingActivityTest.cpp
carbonated-dev/o3de
150060441eccb98318febe17d3915f0781823b19
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/AWSGameLift/Code/AWSGameLiftClient/Tests/Activity/AWSGameLiftStartMatchmakingActivityTest.cpp
carbonated-dev/o3de
150060441eccb98318febe17d3915f0781823b19
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/AWSGameLift/Code/AWSGameLiftClient/Tests/Activity/AWSGameLiftStartMatchmakingActivityTest.cpp
carbonated-dev/o3de
150060441eccb98318febe17d3915f0781823b19
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <Activity/AWSGameLiftStartMatchmakingActivity.h> #include <AWSGameLiftClientFixture.h> using namespace AWSGameLift; using AWSGameLiftStartMatchmakingActivityTest = AWSGameLiftClientFixture; TEST_F(AWSGameLiftStartMatchmakingActivityTest, BuildAWSGameLiftStartMatchmakingRequest_Call_GetExpectedResult) { AWSGameLiftStartMatchmakingRequest request; request.m_configurationName = "dummyConfiguration"; request.m_ticketId = "dummyTicketId"; AWSGameLiftPlayerInformation player; player.m_playerAttributes["dummy"] = "{\"S\": \"test\"}"; player.m_playerId = "dummyPlayerId"; player.m_team = "dummyTeam"; player.m_latencyInMs["us-east-1"] = 10; request.m_players.emplace_back(player); auto awsRequest = StartMatchmakingActivity::BuildAWSGameLiftStartMatchmakingRequest(request); EXPECT_TRUE(strcmp(awsRequest.GetConfigurationName().c_str(), request.m_configurationName.c_str()) == 0); EXPECT_TRUE(strcmp(awsRequest.GetTicketId().c_str(), request.m_ticketId.c_str()) == 0); EXPECT_TRUE(awsRequest.GetPlayers().size() == request.m_players.size()); EXPECT_TRUE(strcmp(awsRequest.GetPlayers()[0].GetPlayerId().c_str(), request.m_players[0].m_playerId.c_str()) == 0); EXPECT_TRUE(strcmp(awsRequest.GetPlayers()[0].GetTeam().c_str(), request.m_players[0].m_team.c_str()) == 0); EXPECT_TRUE(awsRequest.GetPlayers()[0].GetLatencyInMs().size() == request.m_players[0].m_latencyInMs.size()); EXPECT_TRUE(strcmp(awsRequest.GetPlayers()[0].GetLatencyInMs().begin()->first.c_str(), request.m_players[0].m_latencyInMs.begin()->first.c_str()) == 0); EXPECT_TRUE(awsRequest.GetPlayers()[0].GetLatencyInMs().begin()->second == request.m_players[0].m_latencyInMs.begin()->second); EXPECT_TRUE(awsRequest.GetPlayers()[0].GetPlayerAttributes().size() == request.m_players[0].m_playerAttributes.size()); EXPECT_TRUE(strcmp(awsRequest.GetPlayers()[0].GetPlayerAttributes().begin()->first.c_str(), request.m_players[0].m_playerAttributes.begin()->first.c_str()) == 0); EXPECT_TRUE(strcmp(awsRequest.GetPlayers()[0].GetPlayerAttributes().begin()->second.GetS().c_str(), "test") == 0); } TEST_F(AWSGameLiftStartMatchmakingActivityTest, ValidateStartMatchmakingRequest_CallWithBaseType_GetFalseResult) { AZ_TEST_START_TRACE_SUPPRESSION; auto result = StartMatchmakingActivity::ValidateStartMatchmakingRequest(AzFramework::StartMatchmakingRequest()); EXPECT_FALSE(result); AZ_TEST_STOP_TRACE_SUPPRESSION(1); // capture 1 error message } TEST_F(AWSGameLiftStartMatchmakingActivityTest, ValidateStartMatchmakingRequest_CallWithoutConfigurationName_GetFalseResult) { AWSGameLiftStartMatchmakingRequest request; request.m_ticketId = "dummyTicketId"; AWSGameLiftPlayerInformation player; player.m_playerAttributes["dummy"] = "{\"S\": \"test\"}"; player.m_playerId = "dummyPlayerId"; player.m_team = "dummyTeam"; player.m_latencyInMs["us-east-1"] = 10; request.m_players.emplace_back(player); AZ_TEST_START_TRACE_SUPPRESSION; auto result = StartMatchmakingActivity::ValidateStartMatchmakingRequest(request); EXPECT_FALSE(result); AZ_TEST_STOP_TRACE_SUPPRESSION(1); // capture 1 error message } TEST_F(AWSGameLiftStartMatchmakingActivityTest, ValidateStartMatchmakingRequest_CallWithoutPlayers_GetFalseResult) { AWSGameLiftStartMatchmakingRequest request; request.m_configurationName = "dummyConfiguration"; request.m_ticketId = "dummyTicketId"; AZ_TEST_START_TRACE_SUPPRESSION; auto result = StartMatchmakingActivity::ValidateStartMatchmakingRequest(request); EXPECT_FALSE(result); AZ_TEST_STOP_TRACE_SUPPRESSION(1); // capture 1 error message } TEST_F(AWSGameLiftStartMatchmakingActivityTest, ValidateStartMatchmakingRequest_CallWithoutPlayerId_GetFalseResult) { AWSGameLiftStartMatchmakingRequest request; request.m_configurationName = "dummyConfiguration"; request.m_ticketId = "dummyTicketId"; AWSGameLiftPlayerInformation player; player.m_playerAttributes["dummy"] = "{\"S\": \"test\"}"; player.m_team = "dummyTeam"; player.m_latencyInMs["us-east-1"] = 10; request.m_players.emplace_back(player); AZ_TEST_START_TRACE_SUPPRESSION; auto result = StartMatchmakingActivity::ValidateStartMatchmakingRequest(request); EXPECT_FALSE(result); AZ_TEST_STOP_TRACE_SUPPRESSION(1); // capture 1 error message } TEST_F(AWSGameLiftStartMatchmakingActivityTest, ValidateStartMatchmakingRequest_CallWithInvalidPlayerAttribute_GetFalseResult) { AWSGameLiftStartMatchmakingRequest request; request.m_configurationName = "dummyConfiguration"; request.m_ticketId = "dummyTicketId"; AWSGameLiftPlayerInformation player; player.m_playerAttributes["dummy"] = "{\"A\": \"test\"}"; player.m_playerId = "dummyPlayerId"; player.m_team = "dummyTeam"; player.m_latencyInMs["us-east-1"] = 10; request.m_players.emplace_back(player); AZ_TEST_START_TRACE_SUPPRESSION; auto result = StartMatchmakingActivity::ValidateStartMatchmakingRequest(request); EXPECT_FALSE(result); AZ_TEST_STOP_TRACE_SUPPRESSION(1); // capture 1 error message } TEST_F(AWSGameLiftStartMatchmakingActivityTest, ValidateStartMatchmakingRequest_CallWithoutTicketId_GetTrueResult) { AWSGameLiftStartMatchmakingRequest request; request.m_configurationName = "dummyConfiguration"; AWSGameLiftPlayerInformation player; player.m_playerAttributes["dummy"] = "{\"S\": \"test\"}"; player.m_playerId = "dummyPlayerId"; player.m_team = "dummyTeam"; player.m_latencyInMs["us-east-1"] = 10; request.m_players.emplace_back(player); auto result = StartMatchmakingActivity::ValidateStartMatchmakingRequest(request); EXPECT_TRUE(result); } TEST_F(AWSGameLiftStartMatchmakingActivityTest, ValidateStartMatchmakingRequest_CallWithValidParameters_GetTrueResult) { AWSGameLiftStartMatchmakingRequest request; request.m_ticketId = "dummyTicketId"; request.m_configurationName = "dummyConfiguration"; AWSGameLiftPlayerInformation player; player.m_playerAttributes["dummy"] = "{\"S\": \"test\"}"; player.m_playerId = "dummyPlayerId"; player.m_team = "dummyTeam"; player.m_latencyInMs["us-east-1"] = 10; request.m_players.emplace_back(player); auto result = StartMatchmakingActivity::ValidateStartMatchmakingRequest(request); EXPECT_TRUE(result); }
43.437908
166
0.772645
[ "3d" ]
706cb62642c1470aef42b9f6d909daf5029d7e34
13,118
cpp
C++
tests/PhiCore/unittests/src/core/invoke.test.cpp
AMS21/Phi
d62d7235dc5307dd18607ade0f95432ae3a73dfd
[ "MIT" ]
3
2020-12-21T13:47:35.000Z
2022-03-16T23:53:21.000Z
tests/PhiCore/unittests/src/core/invoke.test.cpp
AMS21/Phi
d62d7235dc5307dd18607ade0f95432ae3a73dfd
[ "MIT" ]
53
2020-08-07T07:46:57.000Z
2022-02-12T11:07:08.000Z
tests/PhiCore/unittests/src/core/invoke.test.cpp
AMS21/Phi
d62d7235dc5307dd18607ade0f95432ae3a73dfd
[ "MIT" ]
1
2020-08-19T15:50:02.000Z
2020-08-19T15:50:02.000Z
#include <phi/test/test_macros.hpp> #include <phi/compiler_support/warning.hpp> #include <phi/core/declval.hpp> #include <phi/core/forward.hpp> #include <phi/core/invoke.hpp> #include <phi/core/move.hpp> #include <phi/type_traits/is_same.hpp> #include <functional> #include <type_traits> PHI_GCC_SUPPRESS_WARNING_PUSH() PHI_GCC_SUPPRESS_WARNING("-Wnoexcept") PHI_GCC_SUPPRESS_WARNING("-Wuseless-cast") struct NonCopyable { NonCopyable() {} private: NonCopyable(NonCopyable const&) = delete; NonCopyable& operator=(NonCopyable const&) = delete; }; struct TestClass { explicit TestClass(int x) : data(x) {} int& operator()(NonCopyable&&) & { return data; } int const& operator()(NonCopyable&&) const& { return data; } int volatile& operator()(NonCopyable&&) volatile& { return data; } int const volatile& operator()(NonCopyable&&) const volatile& { return data; } int&& operator()(NonCopyable&&) && { return phi::move(data); } int const&& operator()(NonCopyable&&) const&& { return phi::move(data); } int volatile&& operator()(NonCopyable&&) volatile&& { return phi::move(data); } int const volatile&& operator()(NonCopyable&&) const volatile&& { return phi::move(data); } int data; private: TestClass(TestClass const&) = delete; TestClass& operator=(TestClass const&) = delete; }; struct DerivedFromTestClass : public TestClass { explicit DerivedFromTestClass(int x) : TestClass(x) {} }; int& foo(NonCopyable&&) { static int data = 42; return data; } template <class Signature, class Expect, class Functor> void test_b12(Functor&& f) { // Create the callable object. using ClassFunc = Signature TestClass::*; ClassFunc func_ptr = &TestClass::operator(); // Create the dummy arg. NonCopyable arg; // Check that the deduced return type of invoke is what is expected. using DeducedReturnType = decltype(phi::invoke(func_ptr, phi::forward<Functor>(f), phi::move(arg))); STATIC_REQUIRE((phi::is_same<DeducedReturnType, Expect>::value)); // Check that result_of_t matches Expect. using ResultOfReturnType = typename std::result_of<ClassFunc && (Functor&&, NonCopyable &&)>::type; STATIC_REQUIRE((phi::is_same<ResultOfReturnType, Expect>::value)); // Run invoke and check the return value. DeducedReturnType ret = phi::invoke(func_ptr, phi::forward<Functor>(f), phi::move(arg)); CHECK(ret == 42); } template <class Expect, class Functor> void test_b34(Functor&& f) { // Create the callable object. using ClassFunc = int TestClass::*; ClassFunc func_ptr = &TestClass::data; // Check that the deduced return type of invoke is what is expected. using DeducedReturnType = decltype(phi::invoke(func_ptr, phi::forward<Functor>(f))); STATIC_REQUIRE((phi::is_same<DeducedReturnType, Expect>::value)); // Check that result_of_t matches Expect. using ResultOfReturnType = typename std::result_of<ClassFunc && (Functor &&)>::type; STATIC_REQUIRE((phi::is_same<ResultOfReturnType, Expect>::value)); // Run invoke and check the return value. DeducedReturnType ret = phi::invoke(func_ptr, phi::forward<Functor>(f)); CHECK(ret == 42); } template <class Expect, class Functor> void test_b5(Functor&& f) { NonCopyable arg; // Check that the deduced return type of invoke is what is expected. using DeducedReturnType = decltype(phi::invoke(phi::forward<Functor>(f), phi::move(arg))); STATIC_REQUIRE((phi::is_same<DeducedReturnType, Expect>::value)); // Check that result_of_t matches Expect. using ResultOfReturnType = typename std::result_of<Functor && (NonCopyable &&)>::type; STATIC_REQUIRE((phi::is_same<ResultOfReturnType, Expect>::value)); // Run invoke and check the return value. DeducedReturnType ret = phi::invoke(phi::forward<Functor>(f), phi::move(arg)); CHECK(ret == 42); } TEST_CASE("invoke bullet one and two") { { TestClass cl(42); test_b12<int&(NonCopyable &&)&, int&>(cl); test_b12<int const&(NonCopyable &&) const&, int const&>(cl); test_b12<int volatile&(NonCopyable &&) volatile&, int volatile&>(cl); test_b12<int const volatile&(NonCopyable &&) const volatile&, int const volatile&>(cl); test_b12<int && (NonCopyable &&)&&, int&&>(phi::move(cl)); test_b12<int const && (NonCopyable &&) const&&, int const&&>(phi::move(cl)); test_b12<int volatile && (NonCopyable &&) volatile&&, int volatile&&>(phi::move(cl)); test_b12<int const volatile && (NonCopyable &&) const volatile&&, int const volatile&&>( phi::move(cl)); } { DerivedFromTestClass cl(42); test_b12<int&(NonCopyable &&)&, int&>(cl); test_b12<int const&(NonCopyable &&) const&, int const&>(cl); test_b12<int volatile&(NonCopyable &&) volatile&, int volatile&>(cl); test_b12<int const volatile&(NonCopyable &&) const volatile&, int const volatile&>(cl); test_b12<int && (NonCopyable &&)&&, int&&>(phi::move(cl)); test_b12<int const && (NonCopyable &&) const&&, int const&&>(phi::move(cl)); test_b12<int volatile && (NonCopyable &&) volatile&&, int volatile&&>(phi::move(cl)); test_b12<int const volatile && (NonCopyable &&) const volatile&&, int const volatile&&>( phi::move(cl)); } { TestClass cl_obj(42); std::reference_wrapper<TestClass> cl(cl_obj); test_b12<int&(NonCopyable &&)&, int&>(cl); test_b12<int const&(NonCopyable &&) const&, int const&>(cl); test_b12<int volatile&(NonCopyable &&) volatile&, int volatile&>(cl); test_b12<int const volatile&(NonCopyable &&) const volatile&, int const volatile&>(cl); test_b12<int&(NonCopyable &&)&, int&>(phi::move(cl)); test_b12<int const&(NonCopyable &&) const&, int const&>(phi::move(cl)); test_b12<int volatile&(NonCopyable &&) volatile&, int volatile&>(phi::move(cl)); test_b12<int const volatile&(NonCopyable &&) const volatile&, int const volatile&>( phi::move(cl)); } { DerivedFromTestClass cl_obj(42); std::reference_wrapper<DerivedFromTestClass> cl(cl_obj); test_b12<int&(NonCopyable &&)&, int&>(cl); test_b12<int const&(NonCopyable &&) const&, int const&>(cl); test_b12<int volatile&(NonCopyable &&) volatile&, int volatile&>(cl); test_b12<int const volatile&(NonCopyable &&) const volatile&, int const volatile&>(cl); test_b12<int&(NonCopyable &&)&, int&>(phi::move(cl)); test_b12<int const&(NonCopyable &&) const&, int const&>(phi::move(cl)); test_b12<int volatile&(NonCopyable &&) volatile&, int volatile&>(phi::move(cl)); test_b12<int const volatile&(NonCopyable &&) const volatile&, int const volatile&>( phi::move(cl)); } { TestClass cl_obj(42); TestClass* cl = &cl_obj; test_b12<int&(NonCopyable &&)&, int&>(cl); test_b12<int const&(NonCopyable &&) const&, int const&>(cl); test_b12<int volatile&(NonCopyable &&) volatile&, int volatile&>(cl); test_b12<int const volatile&(NonCopyable &&) const volatile&, int const volatile&>(cl); } { DerivedFromTestClass cl_obj(42); DerivedFromTestClass* cl = &cl_obj; test_b12<int&(NonCopyable &&)&, int&>(cl); test_b12<int const&(NonCopyable &&) const&, int const&>(cl); test_b12<int volatile&(NonCopyable &&) volatile&, int volatile&>(cl); test_b12<int const volatile&(NonCopyable &&) const volatile&, int const volatile&>(cl); } } TEST_CASE("invoke bullet tree and four") { { using Fn = TestClass; Fn cl(42); test_b34<int&>(cl); test_b34<int const&>(static_cast<Fn const&>(cl)); test_b34<int volatile&>(static_cast<Fn volatile&>(cl)); test_b34<int const volatile&>(static_cast<Fn const volatile&>(cl)); test_b34<int&&>(static_cast<Fn&&>(cl)); test_b34<int const&&>(static_cast<Fn const&&>(cl)); test_b34<int volatile&&>(static_cast<Fn volatile&&>(cl)); test_b34<int const volatile&&>(static_cast<Fn const volatile&&>(cl)); } { using Fn = DerivedFromTestClass; Fn cl(42); test_b34<int&>(cl); test_b34<int const&>(static_cast<Fn const&>(cl)); test_b34<int volatile&>(static_cast<Fn volatile&>(cl)); test_b34<int const volatile&>(static_cast<Fn const volatile&>(cl)); test_b34<int&&>(static_cast<Fn&&>(cl)); test_b34<int const&&>(static_cast<Fn const&&>(cl)); test_b34<int volatile&&>(static_cast<Fn volatile&&>(cl)); test_b34<int const volatile&&>(static_cast<Fn const volatile&&>(cl)); } { using Fn = TestClass; Fn cl(42); test_b34<int&>(std::reference_wrapper<Fn>(cl)); test_b34<int const&>(std::reference_wrapper<Fn const>(cl)); test_b34<int volatile&>(std::reference_wrapper<Fn volatile>(cl)); test_b34<int const volatile&>(std::reference_wrapper<Fn const volatile>(cl)); } { using Fn = DerivedFromTestClass; Fn cl(42); test_b34<int&>(std::reference_wrapper<Fn>(cl)); test_b34<int const&>(std::reference_wrapper<Fn const>(cl)); test_b34<int volatile&>(std::reference_wrapper<Fn volatile>(cl)); test_b34<int const volatile&>(std::reference_wrapper<Fn const volatile>(cl)); } { using Fn = TestClass; Fn cl_obj(42); Fn* cl = &cl_obj; test_b34<int&>(cl); test_b34<int const&>(static_cast<Fn const*>(cl)); test_b34<int volatile&>(static_cast<Fn volatile*>(cl)); test_b34<int const volatile&>(static_cast<Fn const volatile*>(cl)); } { using Fn = DerivedFromTestClass; Fn cl_obj(42); Fn* cl = &cl_obj; test_b34<int&>(cl); test_b34<int const&>(static_cast<Fn const*>(cl)); test_b34<int volatile&>(static_cast<Fn volatile*>(cl)); test_b34<int const volatile&>(static_cast<Fn const volatile*>(cl)); } } TEST_CASE("invoke bullet five") { using FooType = int&(NonCopyable &&); { FooType& fn = foo; test_b5<int&>(fn); } { FooType* fn = foo; test_b5<int&>(fn); } { using Fn = TestClass; Fn cl(42); test_b5<int&>(cl); test_b5<int const&>(static_cast<Fn const&>(cl)); test_b5<int volatile&>(static_cast<Fn volatile&>(cl)); test_b5<int const volatile&>(static_cast<Fn const volatile&>(cl)); test_b5<int&&>(static_cast<Fn&&>(cl)); test_b5<int const&&>(static_cast<Fn const&&>(cl)); test_b5<int volatile&&>(static_cast<Fn volatile&&>(cl)); test_b5<int const volatile&&>(static_cast<Fn const volatile&&>(cl)); } } struct CopyThrows { CopyThrows() {} CopyThrows(CopyThrows const&) {} CopyThrows(CopyThrows&&) noexcept {} }; struct NoThrowCallable { void operator()() noexcept {} void operator()(CopyThrows) noexcept {} }; struct ThrowsCallable { void operator()() {} }; struct MemberObj { int x; }; TEST_CASE("invoke noexcept") { { NoThrowCallable obj; ((void)obj); // suppress unused warning CopyThrows arg; ((void)arg); // suppress unused warning STATIC_REQUIRE(noexcept(phi::invoke(obj))); STATIC_REQUIRE(!noexcept(phi::invoke(obj, arg))); STATIC_REQUIRE(noexcept(phi::invoke(obj, phi::move(arg)))); } { ThrowsCallable obj; ((void)obj); // suppress unused warning STATIC_REQUIRE(!noexcept(phi::invoke(obj))); } { MemberObj obj{42}; ((void)obj); // suppress unused warning. STATIC_REQUIRE(noexcept(phi::invoke(&MemberObj::x, obj))); } } template <typename T, int N> struct Array { typedef T type[N]; }; struct Type { Array<char, 1>::type& f1(); Array<char, 2>::type& f2() const; Array<char, 1>::type& g1() &; Array<char, 2>::type& g2() const&; Array<char, 3>::type& g3() &&; Array<char, 4>::type& g4() const&&; }; TEST_CASE("invoke") { STATIC_REQUIRE(sizeof(phi::invoke(&Type::f1, phi::declval<Type>())) == 1); STATIC_REQUIRE(sizeof(phi::invoke(&Type::f2, phi::declval<Type const>())) == 2); STATIC_REQUIRE(sizeof(phi::invoke(&Type::g1, phi::declval<Type&>())) == 1); STATIC_REQUIRE(sizeof(phi::invoke(&Type::g2, phi::declval<Type const&>())) == 2); STATIC_REQUIRE(sizeof(phi::invoke(&Type::g3, phi::declval<Type&&>())) == 3); STATIC_REQUIRE(sizeof(phi::invoke(&Type::g4, phi::declval<Type const&&>())) == 4); } int foo(int) { return 42; } TEST_CASE("invoke basic test") { //REQUIRE(phi::invoke(foo, 101) == 42); } PHI_GCC_SUPPRESS_WARNING_POP()
32.631841
96
0.615033
[ "object" ]
706f08b62770d4e900244e38b49e395768024c81
21,464
cc
C++
chrome/browser/android/data_usage/tab_data_use_entry_unittest.cc
google-ar/chromium
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
777
2017-08-29T15:15:32.000Z
2022-03-21T05:29:41.000Z
chrome/browser/android/data_usage/tab_data_use_entry_unittest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
66
2017-08-30T18:31:18.000Z
2021-08-02T10:59:35.000Z
chrome/browser/android/data_usage/tab_data_use_entry_unittest.cc
harrymarkovskiy/WebARonARCore
2441c86a5fd975f09a6c30cddb57dfb7fc239699
[ "Apache-2.0", "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
123
2017-08-30T01:19:34.000Z
2022-03-17T22:55:31.000Z
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/android/data_usage/tab_data_use_entry.h" #include <stddef.h> #include <stdint.h> #include <memory> #include <string> #include "base/bind.h" #include "base/bind_helpers.h" #include "base/macros.h" #include "base/strings/stringprintf.h" #include "base/test/histogram_tester.h" #include "base/time/tick_clock.h" #include "base/time/time.h" #include "chrome/browser/android/data_usage/data_use_tab_model.h" #include "testing/gtest/include/gtest/gtest.h" namespace { // Tracking labels for tests. const char kTestLabel1[] = "label_1"; const char kTestLabel2[] = "label_2"; const char kTestLabel3[] = "label_3"; enum TabEntrySessionSize { ZERO = 0, ONE, TWO, THREE }; } // namespace namespace chrome { namespace android { // Test version of |TickClock|. class SimpleOffsetTestTickClock : public base::TickClock { public: SimpleOffsetTestTickClock() {} ~SimpleOffsetTestTickClock() override {} // Returns the spoofed time as Now. base::TimeTicks NowTicks() override { return base::TimeTicks::UnixEpoch() + now_offset_; } // Returns the spoofed Now time after adding |now_offset_seconds| seconds. static base::TimeTicks GetNowWithOffset(uint32_t now_offset_seconds) { return base::TimeTicks::UnixEpoch() + base::TimeDelta::FromSeconds(now_offset_seconds); } // Sets the |now_offset_| delta to |now_offset_seconds| seconds. void SetNowOffsetInSeconds(uint32_t now_offset_seconds) { now_offset_ = base::TimeDelta::FromSeconds(now_offset_seconds); } private: // Represents the delta offset to be added to current time that is returned by // NowTicks. base::TimeDelta now_offset_; DISALLOW_COPY_AND_ASSIGN(SimpleOffsetTestTickClock); }; class TabDataUseEntryTest : public testing::Test { public: TabDataUseEntryTest() { tab_model_.reset(new DataUseTabModel( base::Bind(&TabDataUseEntryTest::FetchMatchingRules, base::Unretained(this)), base::Bind(&TabDataUseEntryTest::OnMatchingRulesFetched, base::Unretained(this)))); tick_clock_ = new SimpleOffsetTestTickClock(); tab_model_->tick_clock_.reset(tick_clock_); tab_entry_.reset(new TabDataUseEntry(tab_model_.get())); } void FetchMatchingRules() {} void OnMatchingRulesFetched(bool is_valid) {} size_t GetMaxSessionsPerTab() const { return tab_model_->max_sessions_per_tab(); } const base::TimeDelta& GetClosedTabExpirationDuration() const { return tab_model_->closed_tab_expiration_duration(); } const base::TimeDelta& GetOpenTabExpirationDuration() const { return tab_model_->open_tab_expiration_duration(); } // Checks if there are |expected_size| tracking session entries in // |sessions_|. void ExpectTabEntrySessionsSize(uint32_t expected_size) const { EXPECT_EQ(expected_size, tab_entry_->sessions_.size()); } // Checks if the tracking session at position |index| in the |sessions_| queue // has the start and end times represented by offsets in seconds // |start_time_offset| and |end_time_offset| respectively. void ExpectStartEndTimeOffsets(uint32_t index, int start_time_offset, int end_time_offset) const { EXPECT_LT(index, tab_entry_->sessions_.size()); const TabDataUseTrackingSession& session = tab_entry_->sessions_[index]; EXPECT_EQ(session.start_time, SimpleOffsetTestTickClock::GetNowWithOffset(start_time_offset)); EXPECT_EQ(session.end_time, SimpleOffsetTestTickClock::GetNowWithOffset(end_time_offset)); } // Checks if the data use time at |offset_seconds| is labeled as // |expected_label|. void ExpectDataUseLabelAtOffsetTime(int offset_seconds, const std::string& expected_label) const { ExpectDataUseLabelAtOffsetTimeWithReturn(offset_seconds, expected_label, true); } // Checks if the data use time at |offset_seconds| is labeled as an empty // string. void ExpectEmptyDataUseLabelAtOffsetTime(int offset_seconds) const { ExpectDataUseLabelAtOffsetTimeWithReturn(offset_seconds, std::string(), false); } // Checks if GetLabel labels the data use time at |offset_seconds| as // |expected_label| and returns |expected_return|. void ExpectDataUseLabelAtOffsetTimeWithReturn( int offset_seconds, const std::string& expected_label, bool expected_return) const { base::TimeTicks data_use_time = SimpleOffsetTestTickClock::GetNowWithOffset(offset_seconds); std::string actual_label; bool actual_return = tab_entry_->GetLabel(data_use_time, &actual_label); EXPECT_EQ(expected_return, actual_return); EXPECT_EQ(expected_label, actual_label); } // Returns true if a tracking session is found labeled with |label|. bool IsTabEntrySessionExists(const std::string& label) const { for (auto session : tab_entry_->sessions_) { if (session.label == label) return true; } return false; } // Pointer to the clock used for spoofing time, owned by |tab_model_|. SimpleOffsetTestTickClock* tick_clock_; std::unique_ptr<DataUseTabModel> tab_model_; std::unique_ptr<TabDataUseEntry> tab_entry_; DISALLOW_COPY_AND_ASSIGN(TabDataUseEntryTest); }; // Starts a single tracking session and checks if a new active session is added // to the vector. Ends the session and checks if it becomes inactive. TEST_F(TabDataUseEntryTest, SingleTabSessionStartEnd) { ExpectTabEntrySessionsSize(TabEntrySessionSize::ZERO); EXPECT_FALSE(tab_entry_->IsTrackingDataUse()); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); ExpectTabEntrySessionsSize(TabEntrySessionSize::ONE); EXPECT_TRUE(tab_entry_->IsTrackingDataUse()); EXPECT_TRUE(tab_entry_->EndTracking()); ExpectTabEntrySessionsSize(TabEntrySessionSize::ONE); EXPECT_FALSE(tab_entry_->IsTrackingDataUse()); } // Starts multiple tracking sessions and checks if new active sessions are added // to the vector for each. Ends the sessions and checks if they become inactive. TEST_F(TabDataUseEntryTest, MultipleTabSessionStartEnd) { ExpectTabEntrySessionsSize(TabEntrySessionSize::ZERO); EXPECT_FALSE(tab_entry_->IsTrackingDataUse()); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); EXPECT_TRUE(tab_entry_->IsTrackingDataUse()); EXPECT_TRUE(tab_entry_->EndTracking()); EXPECT_FALSE(tab_entry_->IsTrackingDataUse()); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel2)); EXPECT_TRUE(tab_entry_->IsTrackingDataUse()); EXPECT_TRUE(tab_entry_->EndTracking()); EXPECT_FALSE(tab_entry_->IsTrackingDataUse()); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel3)); EXPECT_TRUE(tab_entry_->IsTrackingDataUse()); EXPECT_TRUE(tab_entry_->EndTracking()); EXPECT_FALSE(tab_entry_->IsTrackingDataUse()); ExpectTabEntrySessionsSize(TabEntrySessionSize::THREE); } // Checks that starting a session while a tracking session is already active and // ending a session while no tracking session is active return false. TEST_F(TabDataUseEntryTest, DuplicateTabSessionStartEnd) { EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); EXPECT_TRUE(tab_entry_->IsTrackingDataUse()); // Duplicate start tracking returns false. EXPECT_FALSE(tab_entry_->StartTracking(kTestLabel2)); ExpectTabEntrySessionsSize(TabEntrySessionSize::ONE); EXPECT_TRUE(tab_entry_->IsTrackingDataUse()); EXPECT_TRUE(tab_entry_->EndTracking()); EXPECT_FALSE(tab_entry_->IsTrackingDataUse()); // Duplicate end tracking returns false. EXPECT_FALSE(tab_entry_->EndTracking()); EXPECT_FALSE(tab_entry_->IsTrackingDataUse()); ExpectTabEntrySessionsSize(TabEntrySessionSize::ONE); } // Checks that tab close time is updated on a close event for a single tracking // session. TEST_F(TabDataUseEntryTest, SingleTabSessionCloseEvent) { ExpectTabEntrySessionsSize(TabEntrySessionSize::ZERO); EXPECT_TRUE(tab_entry_->tab_close_time_.is_null()); tick_clock_->SetNowOffsetInSeconds(1); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); EXPECT_TRUE(tab_entry_->tab_close_time_.is_null()); tick_clock_->SetNowOffsetInSeconds(2); EXPECT_TRUE(tab_entry_->EndTracking()); EXPECT_TRUE(tab_entry_->tab_close_time_.is_null()); tick_clock_->SetNowOffsetInSeconds(3); base::TimeTicks time_before_close = tick_clock_->NowTicks(); tab_entry_->OnTabCloseEvent(); tick_clock_->SetNowOffsetInSeconds(4); EXPECT_FALSE(tab_entry_->tab_close_time_.is_null()); EXPECT_GE(tab_entry_->tab_close_time_, time_before_close); EXPECT_LE(tab_entry_->tab_close_time_, tick_clock_->NowTicks()); EXPECT_FALSE(tab_entry_->IsTrackingDataUse()); } // Checks that tab close time is updated on a close event after multiple // tracking sessions. TEST_F(TabDataUseEntryTest, MultipleTabSessionCloseEvent) { ExpectTabEntrySessionsSize(TabEntrySessionSize::ZERO); EXPECT_TRUE(tab_entry_->tab_close_time_.is_null()); tick_clock_->SetNowOffsetInSeconds(1); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); EXPECT_TRUE(tab_entry_->tab_close_time_.is_null()); tick_clock_->SetNowOffsetInSeconds(2); EXPECT_TRUE(tab_entry_->EndTracking()); EXPECT_TRUE(tab_entry_->tab_close_time_.is_null()); tick_clock_->SetNowOffsetInSeconds(3); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel2)); EXPECT_TRUE(tab_entry_->tab_close_time_.is_null()); tick_clock_->SetNowOffsetInSeconds(4); EXPECT_TRUE(tab_entry_->EndTracking()); tick_clock_->SetNowOffsetInSeconds(5); EXPECT_TRUE(tab_entry_->tab_close_time_.is_null()); base::TimeTicks time_before_close = tick_clock_->NowTicks(); tab_entry_->OnTabCloseEvent(); EXPECT_FALSE(tab_entry_->tab_close_time_.is_null()); EXPECT_GE(tab_entry_->tab_close_time_, time_before_close); EXPECT_LE(tab_entry_->tab_close_time_, tick_clock_->NowTicks()); EXPECT_FALSE(tab_entry_->IsTrackingDataUse()); } // Tests that active tracking session ends with EndTrackingWithLabel. TEST_F(TabDataUseEntryTest, EndTrackingWithLabel) { EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); EXPECT_TRUE(tab_entry_->IsTrackingDataUse()); EXPECT_TRUE(tab_entry_->EndTrackingWithLabel(kTestLabel1)); EXPECT_FALSE(tab_entry_->IsTrackingDataUse()); ExpectTabEntrySessionsSize(TabEntrySessionSize::ONE); } // Checks that start and end times of tracking sessions are updated for multiple // tracking sessions. TEST_F(TabDataUseEntryTest, TabSessionStartEndTimes) { // Start a tracking session at time=0. tick_clock_->SetNowOffsetInSeconds(0); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); // End the tracking session at time=10. tick_clock_->SetNowOffsetInSeconds(10); EXPECT_TRUE(tab_entry_->EndTracking()); // Start a tracking session at time=20, and end it at time=30. tick_clock_->SetNowOffsetInSeconds(20); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel2)); tick_clock_->SetNowOffsetInSeconds(30); EXPECT_TRUE(tab_entry_->EndTracking()); ExpectTabEntrySessionsSize(TabEntrySessionSize::TWO); ExpectStartEndTimeOffsets(0, 0, 10); ExpectStartEndTimeOffsets(1, 20, 30); } // Checks that correct labels are returned for various mock data use times in a // multiple tracking session scenario. TEST_F(TabDataUseEntryTest, TabSessionLabelDataUse) { // No active session. ExpectEmptyDataUseLabelAtOffsetTime(0); ExpectEmptyDataUseLabelAtOffsetTime(40); // Start a tracking session at time=10, and end it at time=20. tick_clock_->SetNowOffsetInSeconds(10); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); tick_clock_->SetNowOffsetInSeconds(20); EXPECT_TRUE(tab_entry_->EndTracking()); // No tracking session active during the time interval [0-10). ExpectEmptyDataUseLabelAtOffsetTime(0); ExpectEmptyDataUseLabelAtOffsetTime(9); // Tracking session active during the time interval [10-20]. ExpectDataUseLabelAtOffsetTime(10, kTestLabel1); ExpectDataUseLabelAtOffsetTime(15, kTestLabel1); ExpectDataUseLabelAtOffsetTime(20, kTestLabel1); // No tracking session active after time=20. ExpectEmptyDataUseLabelAtOffsetTime(21); // Start a tracking session at time=30, and end it at time=40. tick_clock_->SetNowOffsetInSeconds(30); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel2)); tick_clock_->SetNowOffsetInSeconds(40); EXPECT_TRUE(tab_entry_->EndTracking()); // Tracking session active during the time interval [10-20] and [30-40]. ExpectEmptyDataUseLabelAtOffsetTime(0); ExpectEmptyDataUseLabelAtOffsetTime(9); ExpectDataUseLabelAtOffsetTime(10, kTestLabel1); ExpectDataUseLabelAtOffsetTime(15, kTestLabel1); ExpectDataUseLabelAtOffsetTime(20, kTestLabel1); ExpectEmptyDataUseLabelAtOffsetTime(21); ExpectEmptyDataUseLabelAtOffsetTime(29); ExpectDataUseLabelAtOffsetTime(30, kTestLabel2); ExpectDataUseLabelAtOffsetTime(35, kTestLabel2); ExpectDataUseLabelAtOffsetTime(40, kTestLabel2); // No tracking session active after time=40. ExpectEmptyDataUseLabelAtOffsetTime(41); } // Checks that open tab entries expire after open tab expiration duration from // their latest tracking session start time. TEST_F(TabDataUseEntryTest, OpenTabSessionExpiryFromLatestSessionStart) { const unsigned int open_tab_expiration_seconds = GetOpenTabExpirationDuration().InSeconds(); // Initial tab entry with no sessions is considered expired. EXPECT_TRUE(tab_entry_->IsExpired()); // Start a tracking session at time=10. tick_clock_->SetNowOffsetInSeconds(10); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); EXPECT_FALSE(tab_entry_->IsExpired()); // Fast forward |open_tab_expiration_seconds| seconds from session start time. // Tab entry is not expired. tick_clock_->SetNowOffsetInSeconds(10 + open_tab_expiration_seconds); EXPECT_FALSE(tab_entry_->IsExpired()); // Fast forward |open_tab_expiration_seconds+1| seconds from session start // time. Tab entry is expired. tick_clock_->SetNowOffsetInSeconds(10 + open_tab_expiration_seconds + 1); EXPECT_TRUE(tab_entry_->IsExpired()); } // Checks that open tab entries expire after open tab expiration duration from // their latest tracking session end time. TEST_F(TabDataUseEntryTest, OpenTabSessionExpiryFromLatestSessionEnd) { const unsigned int open_tab_expiration_seconds = GetOpenTabExpirationDuration().InSeconds(); // Initial tab entry with no sessions is considered expired. EXPECT_TRUE(tab_entry_->IsExpired()); // Start a tracking session at time=10, and end it at time=20. tick_clock_->SetNowOffsetInSeconds(10); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); tick_clock_->SetNowOffsetInSeconds(20); EXPECT_TRUE(tab_entry_->EndTracking()); EXPECT_FALSE(tab_entry_->IsExpired()); // Fast forward |open_tab_expiration_seconds| seconds from session end // time. Tab entry is not expired. tick_clock_->SetNowOffsetInSeconds(20 + open_tab_expiration_seconds); EXPECT_FALSE(tab_entry_->IsExpired()); // Fast forward |open_tab_expiration_seconds+1| seconds from session end // time. Tab entry is expired. tick_clock_->SetNowOffsetInSeconds(20 + open_tab_expiration_seconds + 1); EXPECT_TRUE(tab_entry_->IsExpired()); } // Checks that closed tab entries expire after closed tab expiration duration // from their closing time. TEST_F(TabDataUseEntryTest, ClosedTabSessionExpiry) { const unsigned int closed_tab_expiration_seconds = GetClosedTabExpirationDuration().InSeconds(); // Initial tab entry with no sessions is considered expired. EXPECT_TRUE(tab_entry_->IsExpired()); // Start a tracking session at time=10, and end it at time=20. tick_clock_->SetNowOffsetInSeconds(10); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); tick_clock_->SetNowOffsetInSeconds(20); EXPECT_TRUE(tab_entry_->EndTracking()); EXPECT_FALSE(tab_entry_->IsExpired()); // Close the tab entry at time=30. tick_clock_->SetNowOffsetInSeconds(30); tab_entry_->OnTabCloseEvent(); // Fast forward |closed_tab_expiration_seconds| seconds from tab close // time. Tab entry is not expired. tick_clock_->SetNowOffsetInSeconds(30 + closed_tab_expiration_seconds); EXPECT_FALSE(tab_entry_->IsExpired()); // Fast forward |closed_tab_expiration_seconds+1| seconds from tab close // time. Tab entry is expired. tick_clock_->SetNowOffsetInSeconds(30 + closed_tab_expiration_seconds + 1); EXPECT_TRUE(tab_entry_->IsExpired()); } // Checks that tracking session history does not grow beyond // GetMaxSessionsPerTab entries, and automatically compacts itself by removing // the oldest tracking sessions. TEST_F(TabDataUseEntryTest, CompactTabSessionHistory) { const uint32_t per_session_duration = 10; const uint32_t next_session_start_gap = 10; uint32_t session_start_time = 10; uint32_t num_sessions = 1; ExpectTabEntrySessionsSize(TabEntrySessionSize::ZERO); while (num_sessions <= GetMaxSessionsPerTab()) { // Start tracking session at time=|session_start_time| and end after // time=|per_session_duration|. std::string session_label = base::StringPrintf("label_%d", num_sessions); tick_clock_->SetNowOffsetInSeconds(session_start_time); EXPECT_TRUE(tab_entry_->StartTracking(session_label)); tick_clock_->SetNowOffsetInSeconds(session_start_time + per_session_duration); EXPECT_TRUE(tab_entry_->EndTracking()); ExpectTabEntrySessionsSize(num_sessions); // Update next session start time. session_start_time += per_session_duration + next_session_start_gap; ++num_sessions; } int oldest_session = 1; // Oldest session ID that will be removed first. // Check if session history size stays at GetMaxSessionsPerTab, when more // sessions are added. while (num_sessions < GetMaxSessionsPerTab() + 10) { std::string oldest_session_label = base::StringPrintf("label_%d", oldest_session); EXPECT_TRUE(IsTabEntrySessionExists(oldest_session_label)); // Start tracking session at time=|session_start_time| and end after // time=|per_session_duration|. std::string session_label = base::StringPrintf("label_%d", num_sessions); tick_clock_->SetNowOffsetInSeconds(session_start_time); EXPECT_TRUE(tab_entry_->StartTracking(session_label)); tick_clock_->SetNowOffsetInSeconds(session_start_time + per_session_duration); EXPECT_TRUE(tab_entry_->EndTracking()); // Oldest entry got removed. EXPECT_FALSE(IsTabEntrySessionExists(oldest_session_label)); ExpectTabEntrySessionsSize(GetMaxSessionsPerTab()); // Update next session start time. session_start_time += per_session_duration + next_session_start_gap; ++num_sessions; ++oldest_session; } } TEST_F(TabDataUseEntryTest, TrackingSessionLifetimeHistogram) { const char kUMATrackingSessionLifetimeSecondsHistogram[] = "DataUsage.TabModel.TrackingSessionLifetime"; base::HistogramTester histogram_tester; // Tracking session from time=20 to time=30, lifetime of 10 seconds. tick_clock_->SetNowOffsetInSeconds(20); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); tick_clock_->SetNowOffsetInSeconds(30); EXPECT_TRUE(tab_entry_->EndTracking()); histogram_tester.ExpectTotalCount(kUMATrackingSessionLifetimeSecondsHistogram, 1); histogram_tester.ExpectBucketCount( kUMATrackingSessionLifetimeSecondsHistogram, base::TimeDelta::FromSeconds(10).InMilliseconds(), 1); // Tracking session from time=40 to time=70, lifetime of 30 seconds. tick_clock_->SetNowOffsetInSeconds(40); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); tick_clock_->SetNowOffsetInSeconds(70); EXPECT_TRUE(tab_entry_->EndTracking()); histogram_tester.ExpectTotalCount(kUMATrackingSessionLifetimeSecondsHistogram, 2); histogram_tester.ExpectBucketCount( kUMATrackingSessionLifetimeSecondsHistogram, base::TimeDelta::FromSeconds(30).InMilliseconds(), 1); } TEST_F(TabDataUseEntryTest, OldInactiveSessionRemovaltimeHistogram) { const char kUMAOldInactiveSessionRemovalDurationSecondsHistogram[] = "DataUsage.TabModel.OldInactiveSessionRemovalDuration"; base::HistogramTester histogram_tester; const size_t max_sessions_per_tab = GetMaxSessionsPerTab(); // Start a tracking session at time=20, and end it at time=30. tick_clock_->SetNowOffsetInSeconds(20); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); tick_clock_->SetNowOffsetInSeconds(30); EXPECT_TRUE(tab_entry_->EndTracking()); for (size_t session = 1; session < max_sessions_per_tab; ++session) { EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); EXPECT_TRUE(tab_entry_->EndTracking()); } // Add one more session at time=60. This removes the first inactive tracking // session that ended at time=30, with removal duration of 30 seconds. tick_clock_->SetNowOffsetInSeconds(60); EXPECT_TRUE(tab_entry_->StartTracking(kTestLabel1)); EXPECT_TRUE(tab_entry_->EndTracking()); histogram_tester.ExpectUniqueSample( kUMAOldInactiveSessionRemovalDurationSecondsHistogram, base::TimeDelta::FromSeconds(30).InMilliseconds(), 1); } } // namespace android } // namespace chrome
38.328571
80
0.764489
[ "vector" ]
70716ea4208d42b37bc01d93a9642d37b12df70d
381
cpp
C++
1110.cpp
jaemin2682/BAEKJOON_ONLINE_JUDGE
0d5c6907baee61e1fabdbcd96ea473079a9475ed
[ "MIT" ]
null
null
null
1110.cpp
jaemin2682/BAEKJOON_ONLINE_JUDGE
0d5c6907baee61e1fabdbcd96ea473079a9475ed
[ "MIT" ]
null
null
null
1110.cpp
jaemin2682/BAEKJOON_ONLINE_JUDGE
0d5c6907baee61e1fabdbcd96ea473079a9475ed
[ "MIT" ]
null
null
null
#include <iostream> #include <string> #include <cmath> #include <algorithm> #include <vector> using namespace std; int main() { int num; cin >> num; int tem, cnt=0; int res = num; do { if (num >= 10) tem = num / 10 + num % 10; else tem = num; if (tem >= 10) tem %= 10; num = (num % 10) * 10 + tem; cnt++; } while (res != num); cout << cnt; return 0; }
14.111111
44
0.548556
[ "vector" ]
707212ab0945d028a805019009e6e5862655bcd6
2,031
hpp
C++
include/mac_time_tracker/csv.hpp
yoshito-n-students/mac_time_tracker
0532b0c71635bad343ae06b09818156024ff39f5
[ "MIT" ]
null
null
null
include/mac_time_tracker/csv.hpp
yoshito-n-students/mac_time_tracker
0532b0c71635bad343ae06b09818156024ff39f5
[ "MIT" ]
null
null
null
include/mac_time_tracker/csv.hpp
yoshito-n-students/mac_time_tracker
0532b0c71635bad343ae06b09818156024ff39f5
[ "MIT" ]
null
null
null
#ifndef MAC_TIME_TRACKER_CSV_HPP #define MAC_TIME_TRACKER_CSV_HPP #include <iostream> #include <string> #include <vector> #include <boost/algorithm/string/replace.hpp> #include <boost/tokenizer.hpp> #include <mac_time_tracker/io.hpp> namespace mac_time_tracker { class CSV : public std::vector<std::vector<std::string>>, public Readable<CSV>, public Writable { private: using Base = std::vector<std::vector<std::string>>; public: using Base::Base; CSV(const Base &base) : Base(base) {} CSV(Base &&base) : Base(base) {} private: // read CSV from the given stream. // this implements a variant of CSV that // - ends with an empty line or EOF // - allows different number of fields between lines virtual void read(std::istream &is) override { clear(); while (true) { // read a line from the stream std::string line; std::getline(is, line); if (line.empty()) { break; } // tokenize the line boost::tokenizer<boost::escaped_list_separator<char>> tokens(line); emplace_back(tokens.begin(), tokens.end()); } // this means successfully reached EOF but std::getline() set the fail flag // because the last line was empty. cancel the fail flag (i.e. set only the eof flag) // because that is ok as a CSV format. if (is.fail() && !is.bad() && is.eof()) { is.clear(/* new_state = */ std::istream::eofbit); } } // dump data to the given stream virtual void write(std::ostream &os) const override { for (const std::vector<std::string> &line : *this) { for (std::size_t i = 0; i < line.size(); ++i) { if (i > 0) { os << ","; } std::string escaped = line[i]; boost::replace_all(escaped, R"(\)", R"(\\)"); // escape ch boost::replace_all(escaped, R"(")", R"(\")"); // quote boost::replace_all(escaped, "\n", R"(\n)"); // new line os << "\"" << escaped << "\""; } os << "\n"; } } }; } // namespace mac_time_tracker #endif
29.014286
97
0.602166
[ "vector" ]
7072d1fadc5609c6a615d7f74491e0205a03c652
27,231
cpp
C++
unexpected_decisions/pomcp/src/obstacleavoidance.cpp
GiuMaz/XPOMCP
ba109f390ddc3c6224f7f41b20839866d6a232d8
[ "MIT" ]
2
2021-02-01T13:53:52.000Z
2021-12-23T12:56:48.000Z
unexpected_decisions/pomcp/src/obstacleavoidance.cpp
GiuMaz/XPOMCP
ba109f390ddc3c6224f7f41b20839866d6a232d8
[ "MIT" ]
null
null
null
unexpected_decisions/pomcp/src/obstacleavoidance.cpp
GiuMaz/XPOMCP
ba109f390ddc3c6224f7f41b20839866d6a232d8
[ "MIT" ]
null
null
null
#include "obstacleavoidance.h" #include "utils.h" using namespace std; using namespace UTILS; OBSTACLEAVOIDANCE::OBSTACLEAVOIDANCE(std::vector<int> nSubSegs, std::vector<std::vector<double>> subSegLengths, int nEnginePowerValues, int nDifficultyValues, int nVelocityValues) : nSubSegs(nSubSegs), subSegLengths(subSegLengths), nDifficultyValues(nDifficultyValues), nVelocityValues(nVelocityValues), nSeg(subSegLengths.size()) { NumActions = nEnginePowerValues; NumObservations = 4; collisionPenaltyTime=100; // --------------------------------------------------- RewardRange = 90; // <----- correct is 103 // --------------------------------------------------- Discount = 0.95; RandomSeed(0); } STATE* OBSTACLEAVOIDANCE::Copy(const STATE& state) const // Makes a copy of the state state { const OBSTACLEAVOIDANCE_STATE& bmState = safe_cast<const OBSTACLEAVOIDANCE_STATE&>(state); OBSTACLEAVOIDANCE_STATE* newstate = MemoryPool.Allocate(); *newstate = bmState; return newstate; } // NOT USED void OBSTACLEAVOIDANCE::Validate(const STATE& state) const { const OBSTACLEAVOIDANCE_STATE& bmState = safe_cast<const OBSTACLEAVOIDANCE_STATE&>(state); } // Used by standard planner STATE* OBSTACLEAVOIDANCE::CreateStartState() const { OBSTACLEAVOIDANCE_STATE* bmState = MemoryPool.Allocate(); bmState->dps.clear(); bmState->ps.clear(); bmState->vs.clear(); bmState->acs.clear(); bmState->dt1s.clear(); bmState->dt2s.clear(); bmState->dts.clear(); bmState->ts.clear(); bmState->ms.clear(); bmState->os.clear(); bmState->rs.clear(); bmState->r_cums.clear(); bmState->segDifficulties.clear(); bmState->curSegI = 0; // Set agent position (segment i) bmState->curSubsegJ=0; // Set agent position (subsegment j) bmState->p=0; // Set initial number of collisions bmState->ps.push_back(0); bmState->t=0; // Set initial time bmState->ts.push_back(0); bmState->r_cums.push_back(0); // Set initial cumulative reward int rnd; for (int i = 0; i < nSeg; ++i) // Randomly set segment difficulties { rnd=Random(nDifficultyValues); bmState->segDifficulties.push_back(rnd); } return bmState; } STATE* OBSTACLEAVOIDANCE::CreateStartStateFixedValues(std::vector<int> values) const { OBSTACLEAVOIDANCE_STATE* bmState = MemoryPool.Allocate(); bmState->dps.clear(); bmState->ps.clear(); bmState->vs.clear(); bmState->acs.clear(); bmState->dt1s.clear(); bmState->dt2s.clear(); bmState->dts.clear(); bmState->ts.clear(); bmState->ms.clear(); bmState->os.clear(); bmState->rs.clear(); bmState->r_cums.clear(); bmState->segDifficulties.clear(); bmState->curSegI = 0; // Set agent position (segment i) bmState->curSubsegJ=0; // Set agent position (subsegment j) bmState->p=0; // Set initial number of collisions bmState->ps.push_back(0); bmState->t=0; // Set initial time bmState->ts.push_back(0); bmState->r_cums.push_back(0); // Set initial cumulative reward int rnd; for (int i = 0; i < nSeg; ++i) // Randomly set segment difficulties { bmState->segDifficulties.push_back(values[i]); } return bmState; } STATE* OBSTACLEAVOIDANCE::CreateStartState(std::vector<double*>* stateVarRelationships) const { OBSTACLEAVOIDANCE_STATE* bmState = MemoryPool.Allocate(); return bmState; } STATE* OBSTACLEAVOIDANCE::CreateStartState(vector<STATE*>* allParticles, vector<double> allParticleCumProbs) const { OBSTACLEAVOIDANCE_STATE* bmState = MemoryPool.Allocate(); bmState->dps.clear(); bmState->ps.clear(); bmState->vs.clear(); bmState->acs.clear(); bmState->dt1s.clear(); bmState->dt2s.clear(); bmState->dts.clear(); bmState->ts.clear(); bmState->ms.clear(); bmState->os.clear(); bmState->rs.clear(); bmState->r_cums.clear(); bmState->segDifficulties.clear(); bmState->curSegI = 0; // Set agent position (segment i) bmState->curSubsegJ=0; // Set agent position (subsegment j) bmState->p=0; // Set initial number of collisions bmState->ps.push_back(0); bmState->t=0; // Set initial time bmState->ts.push_back(0); bmState->r_cums.push_back(0); // Set initial cumulative reward // Select a particle from allParticles with probability from allParticleProb double rnd=RandomDouble(0,0.9999999999); int partI=0; // Particle index double cumProbTmp=0.0; while(cumProbTmp<=rnd){ partI++; cumProbTmp=allParticleCumProbs[partI]; } partI--; const OBSTACLEAVOIDANCE_STATE& bmParticle = safe_cast<const OBSTACLEAVOIDANCE_STATE&>(*((*allParticles)[partI])); for (int i = 0; i < nSeg; i++) // Set each segment difficulty to that of the particle { bmState->segDifficulties.push_back(bmParticle.segDifficulties[i]); } return bmState; } void OBSTACLEAVOIDANCE::FreeState(STATE* state) const { OBSTACLEAVOIDANCE_STATE* bmState = safe_cast<OBSTACLEAVOIDANCE_STATE*>(state); MemoryPool.Free(bmState); } bool OBSTACLEAVOIDANCE::Step(STATE& state, int action, int& observation, double& reward, const BELIEF_STATE& beliefState) const { OBSTACLEAVOIDANCE_STATE& bmState = safe_cast<OBSTACLEAVOIDANCE_STATE&>(state); bmState.acs.push_back(action); // In history // Compute next indices int nextCurSegI; int nextCurSubsegJ; if((bmState.curSegI==(nSeg-1)) && (bmState.curSubsegJ==(nSubSegs[bmState.curSegI]-1))){ // Last step, end state nextCurSegI=bmState.curSegI; nextCurSubsegJ=bmState.curSubsegJ+1; } else{ if(bmState.curSubsegJ<(nSubSegs[bmState.curSegI]-1)){ nextCurSegI=bmState.curSegI; nextCurSubsegJ=bmState.curSubsegJ+1; } else{ nextCurSegI=bmState.curSegI+1; nextCurSubsegJ=0; } } bmState.v=action; // In state <-------- VELOCITY (3) bmState.vs.push_back(action); // In history double pdp_0, pdp_1; // 0: no collision, 1: yes collision // Model if((action==0) && (bmState.segDifficulties[bmState.curSegI]==0)){ // Low difficulty pdp_1=0.0; // 0.0 } if((action==0) && (bmState.segDifficulties[bmState.curSegI]==1)){ // Medium difficulty pdp_1=0.0; // 0.0 } if((action==0) && (bmState.segDifficulties[bmState.curSegI]==2)){ // High difficulty pdp_1=0.028; // 0.028 } if((action==1) && (bmState.segDifficulties[bmState.curSegI]==0)){ // Low difficulty pdp_1=0.0; // 0.0 } if((action==1) && (bmState.segDifficulties[bmState.curSegI]==1)){ // Medium difficulty pdp_1=0.056; // 0.056 } if((action==1) && (bmState.segDifficulties[bmState.curSegI]==2)){ // High difficulty pdp_1=0.11; // 0.11 } if((action==2) && (bmState.segDifficulties[bmState.curSegI]==0)){ // Low difficulty pdp_1=0.0; // 0.0 } if((action==2) && (bmState.segDifficulties[bmState.curSegI]==1)){ // Medium difficulty pdp_1=0.14; // 0.14 } if((action==2) && (bmState.segDifficulties[bmState.curSegI]==2)){ // High difficulty pdp_1=0.25; // 0.25 } pdp_0=1-pdp_1; double rnd=RandomDouble(0,0.9999999999); int dp=-1; if(rnd<pdp_0){ // No collision dp=0; } if(rnd>=pdp_0 && rnd<pdp_0+pdp_1){ // Yes collision dp=1; } bmState.dp=dp; bmState.dps.push_back(dp); // In history bmState.p=bmState.p+dp; bmState.ps.push_back(bmState.p); // From velocity, length and collisions compute the time to traverse the subsegment double dt, dt1, dt2; dt1=(nVelocityValues-bmState.v)*subSegLengths[bmState.curSegI][bmState.curSubsegJ]; bmState.dt1s.push_back(dt1); bmState.dt1=dt1; dt2=dp*collisionPenaltyTime; bmState.dt2s.push_back(dt2); bmState.dt2=dt2; dt=dt1+dt2; bmState.dts.push_back(dt); bmState.dt=dt; bmState.t=bmState.t+dt1+dt2; bmState.ts.push_back(bmState.t); double pm_0, pm_1; // 0: low number of times in which angular velocity used, 1: high number of times in which angular velocity used // Enrico rettangolo exp 2 autonomous robots (angular velocity) /*if(bmState.segDifficulties[bmState.curSegI]==0){ // Low difficulty pm_1=0.17; // 0.083 } if(bmState.segDifficulties[bmState.curSegI]==1){ // Medium difficulty pm_1=0.24; // 0.23 } if(bmState.segDifficulties[bmState.curSegI]==2){ // High difficulty pm_1=0.53; // 0.45 }*/ // Enrico ice exp 3 (angular velocity) if(bmState.segDifficulties[bmState.curSegI]==0){ // Low difficulty pm_1=0.083; // 0.083 } if(bmState.segDifficulties[bmState.curSegI]==1){ // Medium difficulty pm_1=0.3; // 0.3 } if(bmState.segDifficulties[bmState.curSegI]==2){ // High difficulty pm_1=0.3; // 0.3 } pm_0=1-pm_1; rnd=RandomDouble(0,0.9999999999); int m=-1; if(rnd<pm_0){ // low number of times in which angular velocity used m=0; } else m=1; bmState.m=m; // In state <------------------------- bmState.ms.push_back(m); // In history double po_0, po_1; // Model (occupancy) (Autonomous robots) if(bmState.segDifficulties[bmState.curSegI]==0){ // Low difficulty po_1=0.65; // 0.44 } if(bmState.segDifficulties[bmState.curSegI]==1){ // Medium difficulty po_1=0.83; // 0.79 } if(bmState.segDifficulties[bmState.curSegI]==2){ // High difficulty po_1=0.93; // 0.86 } po_0=1-po_1; rnd=RandomDouble(0,0.9999999999); int o=-1; if(rnd<po_0){ // low number of times in which angular velocity used o=0; } else o=1; bmState.o=o; // In state <------------------------- bmState.os.push_back(o); // In history observation=m + 2*o; // Reward reward=-dt; bmState.r=reward; bmState.rs.push_back(reward); bmState.r_cum=bmState.r_cum+reward; bmState.r_cums.push_back(bmState.r_cum); // Save current distance state-belief (only for data analysis) double dist=0; // Total distance real state <-> belief int hammingDist=0; // Hamming distance between single state and belief int res=0; if(beliefState.GetNumSamples()!=0){ // Not fake belief, used to identify simulation steps std::unordered_map<int, int> nParticlesPerState; int stateId; int stateTmp; for (int i = 0; i < beliefState.GetNumSamples(); i++){ // Compute map nParticlesPerState: state -> nParticles const STATE* state = beliefState.GetSample(i); const OBSTACLEAVOIDANCE_STATE& particleState = safe_cast<const OBSTACLEAVOIDANCE_STATE&>(*state); // Compute state id stateId=0; for (int j = 0; j<nSeg; j++) // For each segment difficulty { stateId+=particleState.segDifficulties[j]*(pow(nDifficultyValues,nSeg-j-1)); } // If it is not in nParticlesPerState then add it and initialize to 1 if (nParticlesPerState.find(stateId) == nParticlesPerState.end()) nParticlesPerState[stateId]= 1; else nParticlesPerState[stateId]++; } // Compute distance as weighted sum of hamming distance between particle state and real state (where weight is belief probability) for (auto s = nParticlesPerState.begin(); s != nParticlesPerState.end(); ++s ){ // For each state in the belief stateTmp=s->first; // stateId hammingDist=0; for(int i = nSeg-1; i>=0; i--)// Compute Hamming distance between real state and particle s { res=stateTmp%nDifficultyValues; stateTmp=stateTmp/nDifficultyValues; hammingDist=hammingDist+std::abs(bmState.segDifficulties[i]-res); // Hamming distance between real state } dist=dist + ((double)s->second/beliefState.GetNumSamples())*hammingDist; } bmState.dist_state_beliefs.push_back(dist); } if((bmState.curSegI==(nSeg-1)) && (bmState.curSubsegJ==(nSubSegs[bmState.curSegI])-1)) { return true; // True means terminal state } else{ // Update position, to be ready for next step bmState.curSegI=nextCurSegI; bmState.curSubsegJ=nextCurSubsegJ; return false; // True means non-terminal state } } // TO BE IMPLEMENTED bool OBSTACLEAVOIDANCE::LocalMove(STATE& state, const HISTORY& history, int stepObs, const STATUS& status) const { return true; } // Puts in legal a set of legal actions that can be taken from state void OBSTACLEAVOIDANCE::GenerateLegal(const STATE& state, const HISTORY& history, vector<int>& legal, const STATUS& status) const { legal.push_back(0); legal.push_back(1); legal.push_back(2); } void OBSTACLEAVOIDANCE::GeneratePreferred(const STATE& state, const HISTORY& history, vector<int>& actions, const STATUS& status) const { actions.push_back(0); actions.push_back(1); actions.push_back(2); } // Display methods ------------------------- void OBSTACLEAVOIDANCE::DisplayBeliefs(const BELIEF_STATE& beliefState, // Displays all states in beliefState std::ostream& ostr) const { cout << "OBSTACLEAVOIDANCE::DisplayBeliefs start" << endl; for (int i = 0; i < beliefState.GetNumSamples(); i++){ const STATE* s = beliefState.GetSample(i); DisplayState(*s,cout); } cout << "OBSTACLEAVOIDANCE::DisplayBeliefs end" << endl; } void OBSTACLEAVOIDANCE::DisplayBeliefIds(const BELIEF_STATE& beliefState, // Displays all states in beliefState std::ostream& ostr) const { cout << "OBSTACLEAVOIDANCE::DisplayBeliefIds: ["; for (int i = 0; i < beliefState.GetNumSamples(); i++){ const STATE* s = beliefState.GetSample(i); DisplayStateId(*s, cout);cout <<"; "; } cout << "OBSTACLEAVOIDANCE::DisplayBeliefs end" << endl; } void OBSTACLEAVOIDANCE::DisplayBeliefDistribution(const BELIEF_STATE& beliefState, std::ostream& ostr) const { std::unordered_map<int, int> dist; int id; for (int i = 0; i < beliefState.GetNumSamples(); i++){ const STATE* state = beliefState.GetSample(i); const OBSTACLEAVOIDANCE_STATE& bmState = safe_cast<const OBSTACLEAVOIDANCE_STATE&>(*state); id=0; for (int j = 0; j<nSeg; j++) // For each segment difficulty { id+=bmState.segDifficulties[j]*(pow(3,nSeg-j-1)); } // If it is not in dist then add it and initialize to 1 if (dist.find(id) == dist.end()) dist[id]= 1; else dist[id]++; } for (auto it = dist.begin(); it != dist.end(); ++it ){ // For each state in the belief ostr << it->first << ":" << it->second << ", "; } } void OBSTACLEAVOIDANCE::DisplayState(const STATE& state, std::ostream& ostr) const { const OBSTACLEAVOIDANCE_STATE& bmState = safe_cast<const OBSTACLEAVOIDANCE_STATE&>(state); ostr << endl; // Display segment difficulties ostr << "## STATE ############" << endl; ostr << "Difficulties: "; for (int i = 0; i < nSeg; i++) ostr << i << ":" << bmState.segDifficulties[i] << ", "; ostr << endl; // Display agent's position ostr << "Position: i:" << bmState.curSegI << ", j:" << bmState.curSubsegJ << endl; // 1. Display delta battery voltage in last subsegment ostr << "dp: " << bmState.dp << endl; // 2. Display voltage ostr << "p: " << bmState.p << endl; // 3. Display Velocity in the last subsegment ostr << "v: " << bmState.v << endl; // 5a. Delta time due to normal navigation in last subsegment ostr << "dt1: " << bmState.dt1 << endl; // 5b. Delta time due to collisions in last subsegment ostr << "dt2: " << bmState.dt2 << endl; // 5. Delta time in last subsegment ostr << "dt: " << bmState.dt << endl; // 6. Display time ostr << "t: " << bmState.t << endl; // 7. Avg ang velocity ostr << "m: " << bmState.m << endl; // 8. Occupancy ostr << "o: " << bmState.o << endl; // 9. Reward ostr << "r: " << bmState.r << endl; // 10. Display cumulative reward ostr << "r_cum: " << bmState.r_cum << endl; ostr << "#######################" << endl<< endl; } void OBSTACLEAVOIDANCE::DisplayObservation(const STATE& state, int observation, std::ostream& ostr) const // Prints the observation { switch (observation) { case 0: // observation=E_NONE -> Nothing observed (action!=sampling) ostr << "Observed dp=0, dt1=1" << endl; break; case 1: // observation=E_NONE -> Nothing observed (action!=sampling) ostr << "Observed dp=0, dt1=2" << endl; break; case 2: // observation=E_NONE -> Nothing observed (action!=sampling) ostr << "Observed dp=0, dt1=3" << endl; break; case 3: // observation=E_NONE -> Nothing observed (action!=sampling) ostr << "Observed dp=1, dt1=1" << endl; break; case 4: // observation=E_NONE -> Nothing observed (action!=sampling) ostr << "Observed dp=1, dt1=2" << endl; break; case 5: // observation=E_NONE -> Nothing observed (action!=sampling) ostr << "Observed dp=1, dt1=3" << endl; break; } } void OBSTACLEAVOIDANCE::DisplayAction(int action, std::ostream& ostr) const // Prints the action performed { if (action == 0) ostr << "Action: Low power (0)" << endl; if (action == 1) ostr << "Action: Medium power (1)" << endl; if (action == 2) ostr << "Action: High power (2)" << endl; } double OBSTACLEAVOIDANCE::JointProb(const STATE& state) const // Displays the STATE (grid with agent and rocks) { // not implemented yet return 1.0; } void OBSTACLEAVOIDANCE::DisplayStateId(const STATE& state, std::ostream& ostr) const // Displays an id from rock values { const OBSTACLEAVOIDANCE_STATE& bmState = safe_cast<const OBSTACLEAVOIDANCE_STATE&>(state); int id=0; string s="State id: "; for (int i = 0; i<nSeg; i++) // For each segment difficulty { id+=bmState.segDifficulties[i]*(pow(nDifficultyValues,nSeg-i-1)); s=s+to_string(bmState.segDifficulties[i]); if(i!=(nSeg-1)){ s=s+"-"; } } cout << s << "(" << id << ")"; } void OBSTACLEAVOIDANCE::DisplayStateHist(const STATE& state, const char* fileName) const // Displays an id from rock values { const OBSTACLEAVOIDANCE_STATE& bmState = safe_cast<const OBSTACLEAVOIDANCE_STATE&>(state); std::ofstream outFile; outFile.open(fileName, std::ofstream::out | std::ofstream::app); string s; s="Step"; int step=0; for (int i = 0; i<nSeg; i++) // For each segment { for (int j = 0; j<nSubSegs[i]; j++) // For each subsegment { s=s + ", " + to_string(step); step=step+1; } } outFile << s << endl; s="Segments"; for (int i = 0; i<nSeg; i++) // For each segment { for (int j = 0; j<nSubSegs[i]; j++) // For each subsegment { s=s + ", " + to_string(i); } } outFile << s << endl; s="SubSegments"; for (int i = 0; i<nSeg; i++) // For each segment { for (int j = 0; j<nSubSegs[i]; j++) // For each subsegment { s=s + ", " + to_string(j); } } outFile << s << endl; s="Lengths"; for (int i = 0; i<nSeg; i++) // For each segment { for (int j = 0; j<nSubSegs[i]; j++) // For each subsegment { s=s + ", " + to_string(subSegLengths[i][j]); } } outFile << s << endl; int stateId=0; for (int i = 0; i<nSeg; i++) // For each segment difficulty { stateId+=bmState.segDifficulties[i]*(pow(3,nSeg-i-1)); } s="Difficulties ("+ to_string(stateId)+")"; for (int i = 0; i<nSeg; i++) // For each segment { for (int j = 0; j<nSubSegs[i]; j++) // For each subsegment { s=s + ", " + to_string(bmState.segDifficulties[i]); } } outFile << s << endl; s="dps"; for (int i = 0; i<bmState.dps.size(); i++) // For each segment difficulty { s=s + ", " + to_string(bmState.dps[i]); } outFile << s << endl; // Battery voltage at the end of the last subsegment (2) s="p"; for (int i = 0; i<bmState.ps.size(); i++) // For each segment difficulty { s=s + ", " + to_string(bmState.ps[i]); } outFile << s << endl; // Velocity in the last subsegment (3) s="v"; for (int i = 0; i<bmState.vs.size(); i++) // For each segment difficulty { s=s + ", " + to_string(bmState.vs[i]); } outFile << s << endl; // Actions (4) s="acs"; for (int i = 0; i<bmState.acs.size(); i++) // For each segment difficulty { s=s + ", " + to_string(bmState.acs[i]); } outFile << s << endl; // Delta time in last segment (5a) s="dt1s"; for (int i = 0; i<bmState.dt1s.size(); i++) // For each segment difficulty { s=s + ", " + to_string(bmState.dt1s[i]); } outFile << s << endl; // Delta time in last segment (5b) s="dt2s"; for (int i = 0; i<bmState.dt2s.size(); i++) // For each segment difficulty { s=s + ", " + to_string(bmState.dt2s[i]); } outFile << s << endl; // Delta time in last segment (5) s="dts"; for (int i = 0; i<bmState.dts.size(); i++) // For each segment difficulty { s=s + ", " + to_string(bmState.dts[i]); } outFile << s << endl; // Time from the beginning (cumulative) (6) s="ts"; for (int i = 0; i<bmState.ts.size(); i++) // For each segment difficulty { s=s + ", " + to_string(bmState.ts[i]); } outFile << s << endl; // Average angular velocity (m) s="ms"; for (int i = 0; i<bmState.ms.size(); i++) // For each segment difficulty { s=s + ", " + to_string(bmState.ms[i]); } outFile << s << endl; // Occupancy (o) s="os"; for (int i = 0; i<bmState.os.size(); i++) // For each segment difficulty { s=s + ", " + to_string(bmState.os[i]); } outFile << s << endl; // Reward last subsegment (7) s="rs"; for (int i = 0; i<bmState.rs.size(); i++) // For each segment difficulty { s=s + ", " + to_string(bmState.rs[i]); } outFile << s << endl; // Cumulative reward (8) s="r_cums"; for (int i = 0; i<bmState.r_cums.size(); i++) // For each segment difficulty { s=s + ", " + to_string(bmState.r_cums[i]); } outFile << s << endl; // Cumulative reward (8) s="dist_state_bel"; for (int i = 0; i<bmState.dist_state_beliefs.size(); i++) // For each segment difficulty { s=s + ", " + to_string(bmState.dist_state_beliefs[i]); } outFile << s << endl<< endl; outFile.close(); } vector<double*>* OBSTACLEAVOIDANCE::CreateStateRelKnowledge(const STATE& state, int nConnComp, double relProbab) const { cout << "In CreateStateRelKnowledge" << endl; const OBSTACLEAVOIDANCE_STATE& oaState = safe_cast<const OBSTACLEAVOIDANCE_STATE&>(state); // Vector of knowledge vector<double*>* stateVarRelationships=new vector<double*>(); // Vector of all possible edges () vector<double*>* allStateVarRelationships=new vector<double*>(); for (int i = 0; i<oaState.segDifficulties.size()-1; i++) { for (int j = i+1; j<oaState.segDifficulties.size(); j++) { if(oaState.segDifficulties[i]==oaState.segDifficulties[j]){ allStateVarRelationships->push_back(new double[3]{(double)i, (double)j,relProbab}); } } } // Check how many connected components there are int nTrueConnComp=oaState.segDifficulties.size(); // N edge in stateVarRelationships int edgeI=-1; vector<vector<int>*>* connComps; while(nTrueConnComp>nConnComp){ edgeI=Random(allStateVarRelationships->size());// Get random edge // If the edge is not in the knowledge stateVarRelationships->push_back((*allStateVarRelationships)[edgeI]); // Add the edge to the knowledge allStateVarRelationships->erase(allStateVarRelationships->begin()+edgeI); // Check how many connected components there are connComps=computeConnComp(stateVarRelationships,oaState.segDifficulties.size()); nTrueConnComp=connComps->size(); } cout << "StateRelKnowledge computed. Connected components:" << endl; printConnectedComponents(connComps); return stateVarRelationships; } bool OBSTACLEAVOIDANCE::LocalMove(STATE& state, const HISTORY& history, int stepObs, const STATUS& status, std::vector<double*>* stateVarRelationships) const { // TO BE IMPLEMENTED return true; } void OBSTACLEAVOIDANCE::PropagateChange(STATE& state, int changedVariable, std::vector<double*>* stateVarRelationships, vector<int>* alreadyExploredVarIndices) const { // TO BE IMPLEMENTED } // Notice: in case of prob=1 changes could be simply propagated in all the connected component void OBSTACLEAVOIDANCE::PropagateChangeToConnectedComponent(STATE& state, int changedVariable, int newVal, std::vector<double*>* stateVarRelationships) const { // TO BE IMPLEMENTED } vector<double*> OBSTACLEAVOIDANCE::FindUnexploredAdjacentVariableIndices(int currentVarIndex, std::vector<double*>* stateVarRelationships, vector<int>* alreadyExploredVarIndices) const { int nRels=stateVarRelationships->size(); vector<double*> adjIs; // TO BE IMPLEMENTED return adjIs; } double OBSTACLEAVOIDANCE::ComputeParticleProbability(STATE& particle, std::vector<double*>* stateVarRelationships) const { OBSTACLEAVOIDANCE_STATE& oastate = safe_cast<OBSTACLEAVOIDANCE_STATE&>(particle); // State double probab=1; int var0, var1, seg0Val, seg1Val; double potentialEqualValues, potentialDifferentValues, potential; for(std::vector<double*>::iterator it = stateVarRelationships->begin() ; it != stateVarRelationships->end(); ++it){ var0=(*it)[0]; // First segment var1=(*it)[1]; // Second segment potentialEqualValues=(*it)[2]/nDifficultyValues; potentialDifferentValues=(1.0-(*it)[2])/6; // Apply the constraint to the state and compute the related potential seg0Val=oastate.segDifficulties[var0]; seg1Val=oastate.segDifficulties[var1]; if(seg0Val==seg1Val){ // They are equal potential=potentialEqualValues; } else{ // They are different potential=potentialDifferentValues; } probab=probab*potential; } return probab; }
33.04733
179
0.608718
[ "vector", "model" ]
707744d05b5db6fe5762e653682bd03f665d21a1
28,586
cpp
C++
gmsv_extra/Garry's Mod/LUA/CLuaInterface.cpp
11Lee1/gmsv_extra
294dbc1e31eca6f086605767e0495cf64348bd85
[ "Apache-2.0" ]
9
2019-04-18T21:17:30.000Z
2021-03-02T08:57:06.000Z
gmsv_extra/Garry's Mod/LUA/CLuaInterface.cpp
11Lee1/gmsv_extra
294dbc1e31eca6f086605767e0495cf64348bd85
[ "Apache-2.0" ]
2
2019-04-21T18:16:47.000Z
2019-11-15T12:34:02.000Z
gmsv_extra/Garry's Mod/LUA/CLuaInterface.cpp
11Lee1/gmsv_extra
294dbc1e31eca6f086605767e0495cf64348bd85
[ "Apache-2.0" ]
1
2019-10-03T07:03:05.000Z
2019-10-03T07:03:05.000Z
#include "Interface.h" #include "../../interfaces.h" #include "../../Source SDK/server/baseentity.h" #include "../../Source SDK/eiface.h" #include "../GLUA/CLuaGameCallback.h" #include "../Exports/exports.h" CBaseEntity* CLuaInterface::GetEntity(int iStackPos) { if (!g_pInterfaces->g_Lua) return nullptr; GarrysMod::Lua::UserData* userdata = nullptr; if (!this->IsType(iStackPos, GarrysMod::Lua::Type::ENTITY) || (userdata = this->GetUserdata(iStackPos), !userdata) || !(*(void**)userdata)) { this->Error("Tried to use a NULL Entity!"); return nullptr; } int entindex = (**(unsigned int**)userdata) & ENT_ENTRY_MASK; if (entindex >= 0xFFFF) return nullptr; return (CBaseEntity*)g_pInterfaces->EngineServer()->PEntityOfEntIndex(entindex)->GetUnknown(); } void CLuaInterface::PushEntity(CBaseEntity* Entity) { if (g_pInterfaces->g_Lua && Entity) { Entity->PushEntity(); } } int CLuaInterface::Top() { typedef int(*lua_gettopFn)(lua_State*); static lua_gettopFn lua_gettop = nullptr; if (!lua_gettop) lua_gettop = (lua_gettopFn)exports::lua_shared::lua_gettop; return lua_gettop(this->m_LuaState); } void CLuaInterface::Push(int iStackPos) { typedef void(*lua_pushvalueFn)(lua_State*, int); static lua_pushvalueFn lua_pushvalue = nullptr; if (!lua_pushvalue) lua_pushvalue = (lua_pushvalueFn)exports::lua_shared::lua_pushvalue; lua_pushvalue(this->m_LuaState, iStackPos); } void CLuaInterface::Pop(int iAmt) { typedef void(*lua_settopFn)(lua_State*, int); static lua_settopFn lua_settop = nullptr; if (!lua_settop) lua_settop = (lua_settopFn)exports::lua_shared::lua_settop; lua_settop(this->m_LuaState, iAmt); } void CLuaInterface::GetTable(int iStackPos) { typedef void(*lua_gettableFn)(lua_State*, int); static lua_gettableFn lua_gettable = nullptr; if (!lua_gettable) lua_gettable = (lua_gettableFn)exports::lua_shared::lua_gettable; lua_gettable(this->m_LuaState, iStackPos); } void CLuaInterface::GetField(int iStackPos, char const* strName) { typedef void(*lua_getfieldFn)(lua_State*, int, char const*); static lua_getfieldFn lua_getfield = nullptr; if (!lua_getfield) lua_getfield = (lua_getfieldFn)exports::lua_shared::lua_getfield; lua_getfield(this->m_LuaState, iStackPos, strName); } void CLuaInterface::SetField(int iStackPos, char const* strName) { typedef void(*lua_setfieldFn)(lua_State*, int, char const*); static lua_setfieldFn lua_setfield = nullptr; if (!lua_setfield) lua_setfield = (lua_setfieldFn)exports::lua_shared::lua_setfield; lua_setfield(this->m_LuaState, iStackPos, strName); } void CLuaInterface::CreateTable() { typedef void(*lua_createtableFn)(lua_State*, int, int); static lua_createtableFn lua_createtable = nullptr; if (!lua_createtable) lua_createtable = (lua_createtableFn)exports::lua_shared::lua_createtable; lua_createtable(this->m_LuaState, 0, 0); } void CLuaInterface::SetTable(int i) { typedef void(*lua_settableFn)(lua_State*, int); static lua_settableFn lua_settable = nullptr; if (!lua_settable) lua_settable = (lua_settableFn)exports::lua_shared::lua_settable; lua_settable(this->m_LuaState, i); } void CLuaInterface::SetMetaTable(int i) { typedef void(*lua_setmetatableFn)(lua_State*, int); static lua_setmetatableFn lua_setmetatable = nullptr; if (!lua_setmetatable) lua_setmetatable = (lua_setmetatableFn)exports::lua_shared::lua_setmetatable; lua_setmetatable(this->m_LuaState, i); } bool CLuaInterface::GetMetaTable(int i) { typedef unsigned int(*lua_getmetatableFn)(lua_State*, int); static lua_getmetatableFn lua_getmetatable = nullptr; if (!lua_getmetatable) lua_getmetatable = (lua_getmetatableFn)exports::lua_shared::lua_getmetatable; return lua_getmetatable(this->m_LuaState, i) != 0; } void CLuaInterface::Call(int iArgs, int iResults) { typedef void(*lua_callFn)(lua_State*, int, int); static lua_callFn lua_call = nullptr; if (!lua_call) lua_call = (lua_callFn)exports::lua_shared::lua_call; lua_call(this->m_LuaState, iArgs, iResults); this->SetState(this->m_LuaState); // 200 } int CLuaInterface::PCall(int iArgs, int iResults, int iErrorFunc) { typedef int(*lua_pcallFn)(lua_State*, int, int, int); static lua_pcallFn lua_pcall = nullptr; if (!lua_pcall) lua_pcall = (lua_pcallFn)exports::lua_shared::lua_pcall; int returnvalue = lua_pcall(this->m_LuaState, iArgs, iResults, iErrorFunc); this->SetState(this->m_LuaState); return returnvalue; } int CLuaInterface::Equal(int iA, int iB) { typedef int(*lua_equalFn)(lua_State*, int, int); static lua_equalFn lua_equal = nullptr; if (!lua_equal) lua_equal = (lua_equalFn)exports::lua_shared::lua_equal; return lua_equal(this->m_LuaState, iA, iB); } int CLuaInterface::RawEqual(int iA, int iB) { typedef int(*lua_rawequalFn)(lua_State*, int, int); static lua_rawequalFn lua_rawequal = nullptr; if (!lua_rawequal) lua_rawequal = (lua_rawequalFn)exports::lua_shared::lua_rawequal; return lua_rawequal(this->m_LuaState, iA, iB); } void CLuaInterface::Insert(int iStackPos) { typedef void(*lua_insertFn)(lua_State*, int); static lua_insertFn lua_insert = nullptr; if (!lua_insert) lua_insert = (lua_insertFn)exports::lua_shared::lua_insert; lua_insert(this->m_LuaState, iStackPos); } void CLuaInterface::Remove(int iStackPos) { typedef void(*lua_removeFn)(lua_State*, int); static lua_removeFn lua_remove = nullptr; if (!lua_remove) lua_remove = (lua_removeFn)exports::lua_shared::lua_remove; lua_remove(this->m_LuaState, iStackPos); } int CLuaInterface::Next(int iStackPos) { typedef int(*lua_nextFn)(lua_State*, int); static lua_nextFn lua_next = nullptr; if (!lua_next) lua_next = (lua_nextFn)exports::lua_shared::lua_next; return lua_next(this->m_LuaState, iStackPos); } GarrysMod::Lua::UserData* CLuaInterface::NewUserdata(unsigned int iSize) { typedef void* (*lua_newuserdataFn)(lua_State*, int); static lua_newuserdataFn lua_newuserdata = nullptr; if (!lua_newuserdata) lua_newuserdata = (lua_newuserdataFn)exports::lua_shared::lua_newuserdata; return (GarrysMod::Lua::UserData*)lua_newuserdata(this->m_LuaState, iSize); } void CLuaInterface::ThrowError(char const* strError) { typedef void(*luaL_errorFn)(lua_State*, char const*, char const*); static luaL_errorFn luaL_error = nullptr; if (!luaL_error) luaL_error = (luaL_errorFn)exports::lua_shared::luaL_error; luaL_error(this->m_LuaState, "%s", strError); } void CLuaInterface::CheckType(int iStackPos, int iType) { int type = this->GetType(iStackPos); if (type != iType) { char const* TypeName = this->GetTypeName(type); this->TypeError(TypeName, 0); } } void CLuaInterface::ArgError(int iArgNum, const char* strMessage) { typedef void(*luaL_argerrorFn)(lua_State*, int, char const*); static luaL_argerrorFn luaL_argerror = nullptr; if (!luaL_argerror) luaL_argerror = (luaL_argerrorFn)exports::lua_shared::luaL_argerror; luaL_argerror(this->m_LuaState, iArgNum, strMessage); } void CLuaInterface::RawGet(int iStackPos) { typedef void(*lua_rawgetFn)(lua_State*, int); static lua_rawgetFn lua_rawget = nullptr; if (!lua_rawget) lua_rawget = (lua_rawgetFn)exports::lua_shared::lua_rawget; lua_rawget(this->m_LuaState, iStackPos); } void CLuaInterface::RawSet(int iStackPos) { typedef void(*lua_rawsetFn)(lua_State*, int); static lua_rawsetFn lua_rawset = nullptr; if (!lua_rawset) lua_rawset = (lua_rawsetFn)exports::lua_shared::lua_rawset; lua_rawset(this->m_LuaState, iStackPos); } char const* CLuaInterface::GetString(int iStackPos, unsigned int* iOutLen) { typedef char const* (*lua_tolstringFn)(lua_State*, int, unsigned int*); static lua_tolstringFn lua_tolstring = nullptr; if (!lua_tolstring) lua_tolstring = (lua_tolstringFn)exports::lua_shared::lua_tolstring; return lua_tolstring(this->m_LuaState, iStackPos, iOutLen); } double CLuaInterface::GetNumber(int iStackPos) { typedef double(*lua_tonumberFn)(lua_State*, int); static lua_tonumberFn lua_tonumber = nullptr; if (!lua_tonumber) lua_tonumber = (lua_tonumberFn)exports::lua_shared::lua_tonumber; return lua_tonumber(this->m_LuaState, iStackPos); } bool CLuaInterface::GetBool(int iStackPos) { typedef bool(*lua_tobooleanFn)(lua_State*, int); static lua_tobooleanFn lua_toboolean = nullptr; if (!lua_toboolean) lua_toboolean = (lua_tobooleanFn)exports::lua_shared::lua_toboolean; return lua_toboolean(this->m_LuaState, iStackPos) != 0; } GarrysMod::Lua::CFunc CLuaInterface::GetCFunction(int iStackPos) { typedef GarrysMod::Lua::CFunc(*lua_tocfunctionFn)(lua_State*, int); static lua_tocfunctionFn lua_tocfunction = nullptr; if (!lua_tocfunction) lua_tocfunction = (lua_tocfunctionFn)exports::lua_shared::lua_tocfunction; return lua_tocfunction(this->m_LuaState, iStackPos); } GarrysMod::Lua::UserData* CLuaInterface::GetUserdata(int iStackPos) { typedef GarrysMod::Lua::UserData* (*lua_touserdataFn)(lua_State*, int); static lua_touserdataFn lua_touserdata = nullptr; if (!lua_touserdata) lua_touserdata = (lua_touserdataFn)exports::lua_shared::lua_touserdata; return lua_touserdata(this->m_LuaState, iStackPos); } void CLuaInterface::PushNil() { typedef void(*lua_pushnilFn)(lua_State*); static lua_pushnilFn lua_pushnil = nullptr; if (!lua_pushnil) lua_pushnil = (lua_pushnilFn)exports::lua_shared::lua_pushnil; lua_pushnil(this->m_LuaState); } void CLuaInterface::PushString(char const* val, unsigned int iLen) { typedef void(*lua_pushlstringFn)(lua_State*, char const*, unsigned int); static lua_pushlstringFn lua_pushlstring = nullptr; if (!lua_pushlstring) lua_pushlstring = (lua_pushlstringFn)exports::lua_shared::lua_pushlstring; typedef void(*lua_pushstringFn)(lua_State*, char const*); static lua_pushstringFn lua_pushstring = nullptr; if (!lua_pushstring) lua_pushstring = (lua_pushstringFn)exports::lua_shared::lua_pushstring; if (iLen) lua_pushlstring(this->m_LuaState, val, iLen); else lua_pushstring(this->m_LuaState, val); } void CLuaInterface::PushNumber(double val) { typedef void(*lua_pushnumberFn)(lua_State*, double); static lua_pushnumberFn lua_pushnumber = nullptr; if (!lua_pushnumber) lua_pushnumber = (lua_pushnumberFn)exports::lua_shared::lua_pushnumber; lua_pushnumber(this->m_LuaState, val); } void CLuaInterface::PushBool(bool val) { typedef void(*lua_pushboolFn)(lua_State*, bool); static lua_pushboolFn lua_pushbool = nullptr; if (!lua_pushbool) lua_pushbool = (lua_pushboolFn)exports::lua_shared::lua_pushboolean; lua_pushbool(this->m_LuaState, val); } void CLuaInterface::PushCFunction(GarrysMod::Lua::CFunc val) { typedef void(*lua_pushcclosureFn)(lua_State*, GarrysMod::Lua::CFunc val, int); static lua_pushcclosureFn lua_pushcclosure = nullptr; if (!lua_pushcclosure) lua_pushcclosure = (lua_pushcclosureFn)exports::lua_shared::lua_pushcclosure; lua_pushcclosure(this->m_LuaState, val, 0); } void CLuaInterface::PushCClosure(GarrysMod::Lua::CFunc val, int iVars) { typedef void(*lua_pushcclosureFn)(lua_State*, GarrysMod::Lua::CFunc val, int); static lua_pushcclosureFn lua_pushcclosure = nullptr; if (!lua_pushcclosure) lua_pushcclosure = (lua_pushcclosureFn)exports::lua_shared::lua_pushcclosure; lua_pushcclosure(this->m_LuaState, val, iVars); } void CLuaInterface::PushUserdata(GarrysMod::Lua::UserData* userdata) { typedef void(*lua_pushlightuserdataFn)(lua_State*, GarrysMod::Lua::UserData*); static lua_pushlightuserdataFn lua_pushlightuserdata = nullptr; if (!lua_pushlightuserdata) lua_pushlightuserdata = (lua_pushlightuserdataFn)exports::lua_shared::lua_pushlightuserdata; lua_pushlightuserdata(this->m_LuaState, userdata); } int CLuaInterface::ReferenceCreate() { typedef int(*luaL_refFn)(lua_State*, int); static luaL_refFn luaL_ref = nullptr; if (!luaL_ref) luaL_ref = (luaL_refFn)exports::lua_shared::luaL_ref; return luaL_ref(this->m_LuaState, -10000); } void CLuaInterface::ReferenceFree(int i) { typedef void(*luaL_unrefFn)(lua_State*, int, int); static luaL_unrefFn luaL_unref = nullptr; if (!luaL_unref) luaL_unref = (luaL_unrefFn)exports::lua_shared::luaL_unref; luaL_unref(this->m_LuaState, -10000, i); } void CLuaInterface::ReferencePush(int i) { typedef void(*lua_rawgetiFn)(lua_State*, int, int); static lua_rawgetiFn lua_rawgeti = nullptr; if (!lua_rawgeti) lua_rawgeti = (lua_rawgetiFn)exports::lua_shared::lua_rawgeti; lua_rawgeti(this->m_LuaState, -10000, i); } void CLuaInterface::PushSpecial(int iType) { typedef void(*lua_pushvalueFn)(lua_State*, int); static lua_pushvalueFn lua_pushvalue = nullptr; if (!lua_pushvalue) lua_pushvalue = (lua_pushvalueFn)exports::lua_shared::lua_pushvalue; if (iType) { if (iType == 1) lua_pushvalue(this->m_LuaState, -10001); else if (iType - 1 == 1) lua_pushvalue(this->m_LuaState, -10000); else this->PushNil(); } else lua_pushvalue(this->m_LuaState, -10002); } bool CLuaInterface::IsType(int iStackPos, int iType) { typedef int(*lua_typeFn)(lua_State*, int); static lua_typeFn lua_type = nullptr; if (!lua_type) lua_type = (lua_typeFn)exports::lua_shared::lua_type; int type = lua_type(this->m_LuaState, iStackPos); if (type == iType) return true; else if (type != 7 || iType <= 7) return false; else this->GetUserdata(iStackPos)->type == iType; } int CLuaInterface::GetType(int iStackpos) { typedef int(*lua_typeFn)(lua_State*, int); static lua_typeFn lua_type = nullptr; if (!lua_type) lua_type = (lua_typeFn)exports::lua_shared::lua_type; int returntype = 0; switch (lua_type(this->m_LuaState,iStackpos)) { case GarrysMod::Lua::Type::BOOL: returntype = GarrysMod::Lua::Type::BOOL; break; case GarrysMod::Lua::Type::LIGHTUSERDATA: returntype = GarrysMod::Lua::Type::LIGHTUSERDATA; break; case GarrysMod::Lua::Type::NUMBER: returntype = GarrysMod::Lua::Type::NUMBER; break; case GarrysMod::Lua::Type::STRING: returntype = GarrysMod::Lua::Type::STRING; break; case GarrysMod::Lua::Type::TABLE: returntype = GarrysMod::Lua::Type::TABLE; break; case GarrysMod::Lua::Type::FUNCTION: returntype = GarrysMod::Lua::Type::FUNCTION; break; case GarrysMod::Lua::Type::USERDATA: { GarrysMod::Lua::UserData* udata = this->GetUserdata(iStackpos); if (udata && (udata->type >= 9)) returntype = udata->type; else returntype = GarrysMod::Lua::Type::USERDATA; } break; case GarrysMod::Lua::Type::THREAD: returntype = GarrysMod::Lua::Type::THREAD; break; default: returntype = GarrysMod::Lua::Type::NIL; break; } return returntype; } char const* CLuaInterface::GetTypeName(int iType) { if (iType > 0x2A) return "none"; else return (char const*)GarrysMod::Lua::Type::Name[iType]; } void CLuaInterface::CreateMetaTableType(char const* strName, int iType) { typedef int(*luaL_newmetatable_typeFn)(lua_State*, char const*, int); static luaL_newmetatable_typeFn luaL_newmetatable_type = nullptr; if (!luaL_newmetatable_type) luaL_newmetatable_type = (luaL_newmetatable_typeFn)exports::lua_shared::luaL_newmetatable_type; int val = luaL_newmetatable_type(this->m_LuaState, strName, iType); if (val && iType <= 0xFE) { GarrysMod::Lua::CLuaObject* pObj = this->m_MetaTables[iType]; if (!pObj) { pObj = this->CreateObject(); this->m_MetaTables[iType] = pObj; } pObj->SetFromStack(-1); } } char const* CLuaInterface::CheckString(int iStackPos) { typedef char const* (*luaL_checklstringFn)(lua_State*, int, int); static luaL_checklstringFn luaL_checklstring = nullptr; if (!luaL_checklstring) luaL_checklstring = (luaL_checklstringFn)exports::lua_shared::luaL_checklstring; return luaL_checklstring(this->m_LuaState, iStackPos, 0); } double CLuaInterface::CheckNumber(int iStackPos) { typedef double(*luaL_checknumberFn)(lua_State*, int); static luaL_checknumberFn luaL_checknumber = nullptr; if (!luaL_checknumber) luaL_checknumber = (luaL_checknumberFn)exports::lua_shared::luaL_checknumber; return luaL_checknumber(this->m_LuaState, iStackPos); } // ILuaInterface overrides int CLuaInterface::ObjLen(int iStackPos) { typedef int(*lua_objlenFn)(lua_State*, int); static lua_objlenFn lua_objlen = nullptr; if (!lua_objlen) lua_objlen = (lua_objlenFn)exports::lua_shared::lua_objlen; return lua_objlen(this->m_LuaState, iStackPos); } QAngle CLuaInterface::GetAngle(int iStackPos) { GarrysMod::Lua::UserData* udata = this->GetUserdata(iStackPos); if (!udata || !udata->data || udata->type != GarrysMod::Lua::Type::ANGLE) return QAngle(0, 0, 0); return *(QAngle*)udata->data; } Vector CLuaInterface::GetVector(int iStackPos) { GarrysMod::Lua::UserData* udata = this->GetUserdata(iStackPos); if (!udata || !udata->data || udata->type != GarrysMod::Lua::Type::VECTOR) return Vector(0, 0, 0); return *(Vector*)udata->data; } void CLuaInterface::PushAngle(QAngle const& angle) { GarrysMod::Lua::UserData* udata = this->NewUserdata(20); udata->type = GarrysMod::Lua::Type::ANGLE; *(unsigned int*)udata->data = (unsigned int)udata->data + 8; if (this->PushMetaTable(GarrysMod::Lua::Type::ANGLE)) this->SetMetaTable(-2); *(QAngle*)udata->data = angle; } void CLuaInterface::PushVector(Vector const& vec) { GarrysMod::Lua::UserData* udata = this->NewUserdata(20); udata->type = GarrysMod::Lua::Type::VECTOR; *(unsigned int*)udata->data = (unsigned int)udata->data + 8; if (this->PushMetaTable(GarrysMod::Lua::Type::VECTOR)) this->SetMetaTable(-2); *(Vector*)udata->data = vec; } void CLuaInterface::SetState(lua_State* state) { this->m_LuaState = state; } void CLuaInterface::CreateMetaTable(char const* szName) { typedef int(*luaL_newmetatable_typeFn)(lua_State*, char const*, int); static luaL_newmetatable_typeFn luaL_newmetatable_type = nullptr; if (!luaL_newmetatable_type) luaL_newmetatable_type = (luaL_newmetatable_typeFn)exports::lua_shared::luaL_newmetatable_type; int numtables = this->m_iNumMetaTables; if (luaL_newmetatable_type(this->m_LuaState, szName, numtables)) { GarrysMod::Lua::CLuaObject* pObj = this->m_MetaTables[numtables]; if (!pObj) { pObj = this->CreateObject(); this->m_MetaTables[numtables] = pObj; } pObj->SetFromStack(-1); this->m_iNumMetaTables++; } } bool CLuaInterface::PushMetaTable(int iType) { if (iType <= 0xFE && this->m_MetaTables[iType] != 0) { this->m_MetaTables[iType]->Push(); return true; } else return false; } void CLuaInterface::PushUserType(void* userdata, int iType) { GarrysMod::Lua::UserData* udata = this->NewUserdata(8); udata->type = iType; udata->data = userdata; bool success = this->PushMetaTable(iType); if (success) this->SetMetaTable(-2); } void* CLuaInterface::SetUserType(int iStackPos, void* data) { GarrysMod::Lua::UserData* udata = this->GetUserdata(iStackPos); if (udata) udata->data = data; return !udata->data ? nullptr : udata->data; } char CLuaInterface::Init(ILuaCallback*, bool) { // not now lol. return 0; } int CLuaInterface::Shutdown() { // not now. return 0; } int CLuaInterface::Cycle() { // not now. return 0; } GarrysMod::Lua::CLuaObject* CLuaInterface::Global() { return this->m_Global; } GarrysMod::Lua::CLuaObject* CLuaInterface::Lua_GetObject(int iStackPos) { GarrysMod::Lua::CLuaObject* tempobj = this->NewTemporaryObject(); tempobj->SetFromStack(iStackPos); return tempobj; // ? } void CLuaInterface::PushLuaObject(GarrysMod::Lua::ILuaObject* pObj) { if (pObj) pObj->Push(); else this->PushNil(); } void CLuaInterface::PushLuaFunction(GarrysMod::Lua::CFunc Func) { typedef void(*lua_pushcclosureFn)(lua_State*, GarrysMod::Lua::CFunc, int); static lua_pushcclosureFn lua_pushcclosure = nullptr; if (!lua_pushcclosure) lua_pushcclosure = (lua_pushcclosureFn)exports::lua_shared::lua_pushcclosure; lua_pushcclosure(this->m_LuaState, Func, 0); } int CLuaInterface::LuaError(char const* message, int args) { typedef int(*luaL_argerrorFn)(lua_State*, int, char const*); static luaL_argerrorFn luaL_argerror = nullptr; if (!luaL_argerror) luaL_argerror = (luaL_argerrorFn)exports::lua_shared::luaL_argerror; if (args == -1) return this->ErrorNoHalt("%s", message); else return luaL_argerror(this->m_LuaState, args, message); } int CLuaInterface::TypeError(char const* message, int narg) { typedef int(*luaL_typerrorFn)(lua_State*, int, char const*); static luaL_typerrorFn luaL_typerror = nullptr; if (!luaL_typerror) luaL_typerror = (luaL_typerrorFn)exports::lua_shared::luaL_typerror; return luaL_typerror(this->m_LuaState, narg, message); } bool CLuaInterface::CallInternal(int iStackPos, int iNumReturnValues) { if (this->GetType(iStackPos) != 6) printf("Lua tried to call non functions\n"); if (iNumReturnValues > 4) printf("[CLuaInterface::Call] Expecting more returns than possible\n"); this->m_ProtectedFunctionReturns[0] = nullptr; this->m_ProtectedFunctionReturns[1] = nullptr; this->m_ProtectedFunctionReturns[2] = nullptr; this->m_ProtectedFunctionReturns[3] = nullptr; for (int i = 0; i < iNumReturnValues; i++) { GarrysMod::Lua::CLuaObject* tempobj = this->NewTemporaryObject(); this->m_ProtectedFunctionReturns[i] = tempobj; } if (this->CallFunctionProtected(iStackPos, iNumReturnValues, false)) { for (int i = 0; i < iNumReturnValues;) { if (!this->m_ProtectedFunctionReturns[i]) { this->m_ProtectedFunctionReturns[i] = this->NewTemporaryObject(); } this->m_ProtectedFunctionReturns[i]->SetFromStack(~i++); } return true; } else { printf("erorr using call internal\n"); return false; } return false; } bool CLuaInterface::CallInternalNoReturns(int iStackPos) { if (this->CallFunctionProtected(iStackPos, 0, 0)) return 1; else { printf("failed calling \"CallInternalNoReturns\""); return 0; } return 0; } bool CLuaInterface::CallInternalGetBool(int iStackPos) { if (this->CallFunctionProtected(iStackPos, 1, 0)) { int rettype = this->GetType(-1); if (rettype == GarrysMod::Lua::Type::BOOL) { bool bRet = this->GetBool(-1); this->Pop(1); } else { this->Pop(1); return false; } } else { printf("failed calling \"CallInternalGetBool\""); return false; } return false; } char const* CLuaInterface::CallInternalGetString(int iStackPos) { if (this->CallFunctionProtected(iStackPos, 1, 0)) { int rettype = this->GetType(-1); if (rettype == GarrysMod::Lua::Type::STRING) { char const* szRet = this->GetString(-1, 0); this->Pop(1); return szRet; } else { return nullptr; } } else { printf("failed calling \"CallInternalGetString\""); return nullptr; } return nullptr; } bool CLuaInterface::CallInternalGet(int iStackPos, GarrysMod::Lua::ILuaObject* pObj) { if (this->CallFunctionProtected(iStackPos, 1, 0)) { pObj->SetFromStack(-1); this->Pop(1); } else { printf("failed calling \"CallInternalGet\""); return false; } return false; } void CLuaInterface::NewGlobalTable(char const* szName) { CreateTable(); SetField(-10002, szName); } GarrysMod::Lua::CLuaObject* CLuaInterface::NewTemporaryObject() { this->m_iCurrentTempObject++; if (this->m_iCurrentTempObject >= 32) this->m_iCurrentTempObject = 0; if (this->m_TempObjects[this->m_iCurrentTempObject]) this->m_TempObjects[this->m_iCurrentTempObject]->UnReference(); else this->m_TempObjects[this->m_iCurrentTempObject] = this->CreateObject(); return this->m_TempObjects[this->m_iCurrentTempObject]; } bool CLuaInterface::isUserData(int iStackPos) { typedef int(*lua_typeFn)(lua_State*, int); static lua_typeFn lua_type = nullptr; if (!lua_type) lua_type = (lua_typeFn)exports::lua_shared::lua_type; return lua_type(this->m_LuaState, iStackPos) == GarrysMod::Lua::Type::USERDATA; } GarrysMod::Lua::ILuaObject* CLuaInterface::GetMetaTableObject(int iType) { typedef unsigned int(*lua_getmetatableFn)(lua_State*, int); static lua_getmetatableFn lua_getmetatable = nullptr; if (!lua_getmetatable) lua_getmetatable = (lua_getmetatableFn)exports::lua_shared::lua_getmetatable; if (lua_getmetatable(this->m_LuaState, iType)) { GarrysMod::Lua::ILuaObject* ret = this->NewTemporaryObject(); ret->SetFromStack(-1); this->Pop(1); return ret; } else { return nullptr; } return nullptr; } GarrysMod::Lua::ILuaObject* CLuaInterface::GetMetaTableObject(char const* szName, int iType) { this->GetField(-10000,szName); if (this->GetType(-1) != GarrysMod::Lua::Type::TABLE) { this->Pop(1); if (iType == -1) { return nullptr; } this->CreateMetaTableType(szName, iType); } GarrysMod::Lua::ILuaObject* ret = this->NewTemporaryObject(); ret->SetFromStack(-1); this->Pop(1); return ret; } GarrysMod::Lua::CLuaObject* CLuaInterface::GetReturn(int index) { if (index >= 4) printf("Tried to get return higher than max\n"); GarrysMod::Lua::CLuaObject* ret = this->m_ProtectedFunctionReturns[index]; if (!ret) printf("Error: Calling GetReturn on an invalid return! Check code!!\n"); return ret; } bool CLuaInterface::IsServer() { return this->m_cLuaState == GarrysMod::Lua::Server; } bool CLuaInterface::IsClient() { return this->m_cLuaState == GarrysMod::Lua::Client; } bool CLuaInterface::IsMenu() { return this->m_cLuaState == GarrysMod::Lua::Menu; } void CLuaInterface::DestroyObject(GarrysMod::Lua::ILuaObject* pObj) { this->m_pLuaCallBack->DestroyLuaObject(pObj); } GarrysMod::Lua::CLuaObject* CLuaInterface::CreateObject() { return this->m_pLuaCallBack->CreateLuaObject(); } void CLuaInterface::SetMember(GarrysMod::Lua::ILuaObject* pObj0, const char* szName, GarrysMod::Lua::ILuaObject* pObj1) { if (pObj0->IsTable()) { pObj0->Push(); this->PushString(szName, 0); if (pObj1) pObj1->Push(); else this->PushNil(); this->SetTable(-3); this->Pop(1); } } void CLuaInterface::SetMember(GarrysMod::Lua::ILuaObject* pObj, const char* szName) { if (pObj->IsTable()) { pObj->Push(); this->PushString(szName, 0); this->Push(-3); this->SetTable(-3); this->Pop(2); } } void CLuaInterface::SetMember(GarrysMod::Lua::ILuaObject* pObj0, float val, GarrysMod::Lua::ILuaObject* pObj1) { pObj0->Push(); this->PushNumber(val); if (pObj1) pObj1->Push(); else this->PushNil(); this->SetTable(-3); this->Pop(1); } void CLuaInterface::SetMember(GarrysMod::Lua::ILuaObject* pObj, float val) { pObj->Push(); this->PushNumber(val); this->Push(-3); this->SetTable(-3); this->Pop(2); } void CLuaInterface::SetMember(GarrysMod::Lua::ILuaObject* pObj0, GarrysMod::Lua::ILuaObject* pObj1, GarrysMod::Lua::ILuaObject* pObj2) { if (pObj0->IsTable()) { pObj0->Push(); pObj1->Push(); if (pObj2) pObj2->Push(); else this->PushNil(); this->SetTable(-3); this->Pop(1); } } GarrysMod::Lua::CLuaObject* CLuaInterface::GetNewTable() { this->CreateTable(); GarrysMod::Lua::CLuaObject* ret = this->Lua_GetObject(-1); this->Pop(1); return ret; } void CLuaInterface::SetType(unsigned char type) { this->m_cLuaState = type; } void CLuaInterface::PushLong(long val) { this->PushNumber(val); } int CLuaInterface::GetFlags(int iStackPos) { // finish me return 0; } bool CLuaInterface::FindOnObjectsMetaTable(int iStackPos, int dunno) { typedef int(*lua_typeFn)(lua_State*, int); static lua_typeFn lua_type = nullptr; if (!lua_type) lua_type = (lua_typeFn)exports::lua_shared::lua_type; if (!this->GetMetaTable(iStackPos)) return false; this->Push(dunno); this->GetTable(-2); if (!lua_type(this->m_LuaState,-1)) { this->Pop(1); return false; } return true; } bool CLuaInterface::FindObjectsOnMetaTable(int iStackPos, int dunno) { typedef int(*lua_typeFn)(lua_State*, int); static lua_typeFn lua_type = nullptr; if (!lua_type) lua_type = (lua_typeFn)exports::lua_shared::lua_type; this->Push(iStackPos); this->Push(dunno); this->GetTable(-2); return lua_type(this->m_LuaState, -1) != 0; } void CLuaInterface::SetMemberFast(GarrysMod::Lua::ILuaObject* pObj, int dunno, int dunno1) { pObj->Push(); this->Push(dunno); this->Push(dunno1); this->SetTable(-3); this->Pop(1); } int CLuaInterface::RunString(const char* szDunno0, const char* szDunno1, const char* szDunno2, bool bDunno0, bool bDunno1) { return this->RunStringEx(szDunno0, szDunno1, szDunno2, bDunno0, bDunno1, true, true); } bool CLuaInterface::IsEqual(GarrysMod::Lua::ILuaObject* pObj0, GarrysMod::Lua::ILuaObject* pObj1) { if (pObj0 && pObj1 && pObj0->GetType() == pObj1->GetType()) { pObj0->Push(); pObj1->Push(); bool retval = this->Equal(-1, -2) != 0; this->Pop(2); return retval; } else return false; return false; } void CLuaInterface::Error(char const* szError) { this->ThrowError(szError); } //this is all I'm willing to do
29.050813
142
0.737424
[ "vector" ]
707cf18222d47446167a19d1fda96bf18943316a
5,652
cpp
C++
player/render/RGBGLRender.cpp
lewis-v/KeepPlayer
c6c999fd9416a088277ec71ec5de73461e2e159f
[ "Apache-2.0" ]
1
2020-10-17T11:54:13.000Z
2020-10-17T11:54:13.000Z
player/render/RGBGLRender.cpp
lewis-v/KeepPlayer
c6c999fd9416a088277ec71ec5de73461e2e159f
[ "Apache-2.0" ]
null
null
null
player/render/RGBGLRender.cpp
lewis-v/KeepPlayer
c6c999fd9416a088277ec71ec5de73461e2e159f
[ "Apache-2.0" ]
null
null
null
// // Created by lewis-v on 2020/11/1. // #include <map> #include <string> #include "RGBGLRender.h" #include "../base/Macros.h" #include "../base/ImageParseUtil.h" NS_KP_BEGIN static GLfloat _vertices[] = {-1.f, 1.f, -1.f, -1.f, 1.f, 1.f, 1.f, -1.f}; static const GLfloat texCoords[] = {0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, 1.0f}; RGBGLRender::RGBGLRender() { if (!initProgram()) { return; } if (!parseVertexAttribs()) { return; } glGenTextures(1, &texture); GLUtil::checkGLError("glGenTextures"); glBindTexture(GL_TEXTURE_2D, texture); GLUtil::checkGLError("glBindTexture 1"); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); GLUtil::checkGLError("glTexParameteri"); } RGBGLRender::~RGBGLRender() { glDeleteProgram(_program); } void RGBGLRender::render(AVFrame *frame, int width, int height) { glUseProgram(_program); //设置定点缓存指针 glVertexAttribPointer(static_cast<GLuint>(vertAttributePositionLocation), 2, GL_FLOAT, GL_FALSE, 0, _vertices); glEnableVertexAttribArray(static_cast<GLuint>(vertAttributePositionLocation)); //纹理坐标对应 //设置纹理缓存指针,varying变量会被插值传入片元着色器 glVertexAttribPointer(static_cast<GLuint>(vertAttributeTexCoordLocation), 2, GL_FLOAT, GL_FALSE, 0, texCoords); glEnableVertexAttribArray(static_cast<GLuint>(vertAttributeTexCoordLocation)); logI("width:%D height:%d", width, height); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, static_cast<GLuint>(texture)); GLUtil::checkGLError("rgb glBindTexture"); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, frame->width, frame->height, 0, GL_RGB, GL_UNSIGNED_BYTE, frame->data[0]); GLUtil::checkGLError("rgb glTexImage2D"); glUniform1i(rgbTextureLocation, 0); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); GLUtil::checkGLError("rgb draw"); } bool RGBGLRender::initProgram() { GLuint vertShader = 0; GLuint fragShader = 0; //初始化普通的画图片的定点着色器和片元着色器 const char *vert = R"( precision mediump float; attribute vec2 a_Position; attribute vec2 a_TextureCoordinates; varying vec2 v_TextureCoordinates; void main() { gl_Position = vec4(a_Position, 0,1); v_TextureCoordinates = a_TextureCoordinates; } )"; if (!compileShader(vertShader, GL_VERTEX_SHADER, vert)) { logE("RenderTexture: ERROR: Failed to compile vertex shader"); return false; } logI("vertData finish"); const char *frag = R"( precision mediump float; uniform sampler2D tex_rgb; varying vec2 v_TextureCoordinates; void main() { vec4 rgba = texture2D(tex_rgb, v_TextureCoordinates); gl_FragColor = vec4(rgba.rgb, 1); } )"; if (!compileShader(fragShader, GL_FRAGMENT_SHADER, frag)) { logE("RenderTexture: ERROR: Failed to compile fragment shader"); glDeleteShader(vertShader); return false; } logI("fragData finish"); // create program _program = glCreateProgram(); if (!_program) { glDeleteShader(vertShader); glDeleteShader(fragShader); return false; } //将shader关联到程序中 glAttachShader(_program, vertShader); GLUtil::checkGLError("glAttachShader v"); glAttachShader(_program, fragShader); GLUtil::checkGLError("glAttachShader f"); glLinkProgram(_program); GLUtil::checkGLError("linkProgram"); glDeleteShader(vertShader); glDeleteShader(fragShader); GLint status = 0; glGetProgramiv(_program, GL_LINK_STATUS, &status); if (GL_FALSE == status) { logE("RenderTexture: ERROR: %s: failed to link program status:%d", __FUNCTION__, status); glDeleteProgram(_program); _program = 0; return false; } //这里会获取程序中参数对应的id,之后参数传递需要通过这些id来传递 if (!parseVertexAttribs()) { logE("parseVertexAttribs: ERROR: %s", __FUNCTION__); return false; } return true; } bool RGBGLRender::parseVertexAttribs() { vertAttributePositionLocation = glGetAttribLocation(_program, "a_Position"); if (-1 == vertAttributePositionLocation) { logE("RGBRender: %s: can not find vertex attribute of a_Position", __FUNCTION__); return false; } vertAttributeTexCoordLocation = glGetAttribLocation(_program, "a_TextureCoordinates"); if (-1 == vertAttributeTexCoordLocation) { logE("RGBRender: %s %d: can not find vertex uniform of a_TextureCoordinates", __FUNCTION__, __LINE__); return false; } rgbTextureLocation = glGetUniformLocation(_program, "tex_rgb"); if (-1 == rgbTextureLocation) { logE("RGBRender: %s %d: can not find vertex uniform of tex_rgb", __FUNCTION__, __LINE__); return false; } return true; } NS_KP_END
31.054945
94
0.584572
[ "render" ]
7084caa4829e78edd14aac2b2f20dd8e35bf73d1
3,783
cc
C++
chaps/token_manager_client.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
4
2020-07-24T06:54:16.000Z
2021-06-16T17:13:53.000Z
chaps/token_manager_client.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2021-04-02T17:35:07.000Z
2021-04-02T17:35:07.000Z
chaps/token_manager_client.cc
strassek/chromiumos-platform2
12c953f41f48b8a6b0bd1c181d09bdb1de38325c
[ "BSD-3-Clause" ]
1
2020-11-04T22:31:45.000Z
2020-11-04T22:31:45.000Z
// Copyright (c) 2012 The Chromium OS Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chaps/token_manager_client.h" #include <base/logging.h> #include <brillo/secure_blob.h> #include "chaps/chaps_proxy.h" #include "chaps/chaps_utility.h" using base::FilePath; using brillo::SecureBlob; using std::string; using std::vector; namespace chaps { TokenManagerClient::TokenManagerClient() {} TokenManagerClient::~TokenManagerClient() {} bool TokenManagerClient::GetTokenList(const SecureBlob& isolate_credential, vector<string>* result) { if (!Connect()) { LOG(ERROR) << __func__ << ": Failed to connect to the Chaps daemon."; return false; } vector<uint64_t> slots; if (proxy_->GetSlotList(isolate_credential, true, &slots) != CKR_OK) { LOG(ERROR) << __func__ << ": GetSlotList failed."; return false; } vector<string> temp_result; for (size_t i = 0; i < slots.size(); ++i) { FilePath path; if (!GetTokenPath(isolate_credential, slots[i], &path)) { LOG(ERROR) << __func__ << ": GetTokenPath failed."; return false; } temp_result.push_back(path.value()); } result->swap(temp_result); return true; } bool TokenManagerClient::OpenIsolate(SecureBlob* isolate_credential, bool* new_isolate_created) { if (!Connect()) { LOG(ERROR) << __func__ << ": Failed to connect to the Chaps daemon."; return false; } return proxy_->OpenIsolate(isolate_credential, new_isolate_created); } void TokenManagerClient::CloseIsolate(const SecureBlob& isolate_credential) { if (!Connect()) { LOG(ERROR) << __func__ << ": Failed to connect to the Chaps daemon."; return; } proxy_->CloseIsolate(isolate_credential); } bool TokenManagerClient::LoadToken(const SecureBlob& isolate_credential, const FilePath& path, const SecureBlob& auth_data, const string& label, int* slot_id) { if (!Connect()) { LOG(ERROR) << __func__ << ": Failed to connect to the Chaps daemon."; return false; } bool result = proxy_->LoadToken(isolate_credential, path.value(), auth_data, label, PreservedValue<int, uint64_t>(slot_id)); return result; } void TokenManagerClient::UnloadToken(const SecureBlob& isolate_credential, const FilePath& path) { if (!Connect()) { LOG(ERROR) << __func__ << ": Failed to connect to the Chaps daemon."; return; } proxy_->UnloadToken(isolate_credential, path.value()); } void TokenManagerClient::ChangeTokenAuthData(const FilePath& path, const SecureBlob& old_auth_data, const SecureBlob& new_auth_data) { if (!Connect()) { LOG(ERROR) << __func__ << ": Failed to connect to the Chaps daemon."; return; } proxy_->ChangeTokenAuthData(path.value(), old_auth_data, new_auth_data); } bool TokenManagerClient::GetTokenPath(const SecureBlob& isolate_credential, int slot_id, FilePath* path) { if (!Connect()) { LOG(ERROR) << __func__ << ": Failed to connect to the Chaps daemon."; return false; } string tmp; bool result = proxy_->GetTokenPath(isolate_credential, slot_id, &tmp); *path = FilePath(tmp); return result; } bool TokenManagerClient::Connect() { if (!proxy_) proxy_ = ChapsProxyImpl::Create(false /* shadow_at_exit */); return proxy_.get() != nullptr; } } // namespace chaps
31.008197
79
0.621993
[ "vector" ]
708540db38ad574befa340d43aa211118bf56f98
2,025
cpp
C++
dirname/dirname.cpp
maidis/coreutils-cpp
835416947df7e5f7ad51c0eaca8aed2fb9e27ce5
[ "BSL-1.0" ]
3
2021-03-20T10:08:37.000Z
2021-08-15T15:15:58.000Z
dirname/dirname.cpp
maidis/coreutils-cpp
835416947df7e5f7ad51c0eaca8aed2fb9e27ce5
[ "BSL-1.0" ]
2
2021-03-23T21:12:07.000Z
2022-01-06T15:37:12.000Z
dirname/dirname.cpp
maidis/coreutils-cpp
835416947df7e5f7ad51c0eaca8aed2fb9e27ce5
[ "BSL-1.0" ]
1
2021-03-20T09:59:15.000Z
2021-03-20T09:59:15.000Z
#include <iostream> #include <filesystem> #include <vector> namespace fs = std::filesystem; int main(int argc, char *argv[]) { if (argc == 2 && argv[1] == std::string("--help")) { std::cout << R"(Usage: dirname [OPTION] NAME... Output each NAME with its last non-slash component and trailing slashes removed; if NAME contains no /'s, output '.' (meaning the current directory). -z, --zero end each output line with NUL, not newline --help display this help and exit --version output version information and exit Examples: dirname /usr/bin/ -> "/usr" dirname dir1/str dir2/str -> "dir1" followed by "dir2" dirname stdio.h -> ".")" << '\n'; return 0; } else if (argc == 1) { std::cout << "dirname: missing operand\n"; std::cout << "Try 'dirname --help' for more information.\n"; return 0; } else { std::vector<std::string> all_args; all_args.assign(argv + 1, argv + argc); std::string sprtr = "\n"; auto it = all_args.begin(); while (it != all_args.end()) { if (*it == "-z" || *it == "--zero") { sprtr = ""; it = all_args.erase(it); } else { ++it; } } for (auto a : all_args) { std::string str{a}; while ((str.back() == '/') || (str.back() == '\\')) { str.erase(str.size()-1); } fs::path p{str}; //std::filesystem::canonical(p); // https://stackoverflow.com/questions/36941934/parent-path-with-or-without-trailing-slash if (p.lexically_normal().parent_path().string() == "") { std::cout << "." << sprtr; } else { std::cout << p.lexically_normal().parent_path().string() << sprtr; } } } }
27
102
0.470617
[ "vector" ]
7087e78e97f3fb233d7db4262983d304b446247e
3,083
hpp
C++
boost/boost/geometry/geometries/adapted/c_array.hpp
tonystone/geofeatures
25aca530a9140b3f259e9ee0833c93522e83a697
[ "BSL-1.0", "Apache-2.0" ]
24
2015-08-25T05:35:37.000Z
2020-10-24T14:21:59.000Z
boost/boost/geometry/geometries/adapted/c_array.hpp
tonystone/geofeatures
25aca530a9140b3f259e9ee0833c93522e83a697
[ "BSL-1.0", "Apache-2.0" ]
97
2015-08-25T16:11:16.000Z
2019-03-17T00:54:32.000Z
boost/boost/geometry/geometries/adapted/c_array.hpp
tonystone/geofeatures
25aca530a9140b3f259e9ee0833c93522e83a697
[ "BSL-1.0", "Apache-2.0" ]
9
2015-08-26T03:11:38.000Z
2018-03-21T07:16:29.000Z
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2008-2012 Bruno Lalande, Paris, France. // Copyright (c) 2007-2012 Barend Gehrels, Amsterdam, the Netherlands. // Copyright (c) 2009-2012 Mateusz Loskot, London, UK. // Parts of Boost.Geometry are redesigned from Geodan's Geographic Library // (geolib/GGL), copyright (c) 1995-2010 Geodan, Amsterdam, the Netherlands. // Use, modification and distribution is subject to 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) #ifndef BOOST_GEOMETRY_GEOMETRIES_ADAPTED_C_ARRAY_HPP #define BOOST_GEOMETRY_GEOMETRIES_ADAPTED_C_ARRAY_HPP #include <cstddef> #include <boost/type_traits/is_arithmetic.hpp> #include <boost/geometry/core/access.hpp> #include <boost/geometry/core/cs.hpp> #include <boost/geometry/core/coordinate_dimension.hpp> #include <boost/geometry/core/coordinate_type.hpp> #include <boost/geometry/core/tags.hpp> namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry { #ifndef DOXYGEN_NO_TRAITS_SPECIALIZATIONS namespace traits { #ifndef DOXYGEN_NO_DETAIL namespace detail { // Create class and specialization to indicate the tag // for normal cases and the case that the type of the c-array is arithmetic template <bool> struct c_array_tag { typedef geometry_not_recognized_tag type; }; template <> struct c_array_tag<true> { typedef point_tag type; }; } // namespace detail #endif // DOXYGEN_NO_DETAIL // Assign the point-tag, preventing arrays of points getting a point-tag template <typename CoordinateType, std::size_t DimensionCount> struct tag<CoordinateType[DimensionCount]> : detail::c_array_tag<geofeatures_boost::is_arithmetic<CoordinateType>::value> {}; template <typename CoordinateType, std::size_t DimensionCount> struct coordinate_type<CoordinateType[DimensionCount]> { typedef CoordinateType type; }; template <typename CoordinateType, std::size_t DimensionCount> struct dimension<CoordinateType[DimensionCount]>: geofeatures_boost::mpl::int_<DimensionCount> {}; template <typename CoordinateType, std::size_t DimensionCount, std::size_t Dimension> struct access<CoordinateType[DimensionCount], Dimension> { static inline CoordinateType get(CoordinateType const p[DimensionCount]) { return p[Dimension]; } static inline void set(CoordinateType p[DimensionCount], CoordinateType const& value) { p[Dimension] = value; } }; } // namespace traits #endif // DOXYGEN_NO_TRAITS_SPECIALIZATIONS }} // namespace geofeatures_boost::geometry #define BOOST_GEOMETRY_REGISTER_C_ARRAY_CS(CoordinateSystem) \ namespace geofeatures_boost {} namespace boost = geofeatures_boost; namespace geofeatures_boost { namespace geometry { namespace traits { \ template <typename T, std::size_t N> \ struct coordinate_system<T[N]> \ { \ typedef CoordinateSystem type; \ }; \ }}} #endif // BOOST_GEOMETRY_GEOMETRIES_ADAPTED_C_ARRAY_HPP
27.526786
143
0.767434
[ "geometry" ]
70880d101fdbe0cd703ea3d5456d516924bcd12c
12,177
cpp
C++
libpvkernel/src/core/PVRecentItemsManager.cpp
inendi-inspector/inspector
9b9a00222d8a73cb0817ca56790ee9155db61cc4
[ "MIT" ]
null
null
null
libpvkernel/src/core/PVRecentItemsManager.cpp
inendi-inspector/inspector
9b9a00222d8a73cb0817ca56790ee9155db61cc4
[ "MIT" ]
null
null
null
libpvkernel/src/core/PVRecentItemsManager.cpp
inendi-inspector/inspector
9b9a00222d8a73cb0817ca56790ee9155db61cc4
[ "MIT" ]
null
null
null
// // MIT License // // © ESI Group, 2015 // // 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 <pvkernel/rush/PVFormat.h> // for PVFormat #include <pvkernel/rush/PVInputDescription.h> // for PVInputDescription #include <pvkernel/rush/PVInputType.h> // for PVInputType, etc #include <pvkernel/rush/PVSourceCreator.h> // for PVSourceCreator, etc #include <pvkernel/rush/PVSourceCreatorFactory.h> #include <pvkernel/rush/PVSourceDescription.h> // for PVSourceDescription #include <pvkernel/core/PVConfig.h> #include <pvkernel/core/PVRecentItemsManager.h> #include "pvkernel/core/PVClassLibrary.h" // for LIB_CLASS, etc #include "pvkernel/core/PVOrderedMap.h" #include "pvkernel/core/PVRegistrableClass.h" #include <pvbase/general.h> #include <cassert> // for assert #include <cstdint> // for uint64_t #include <algorithm> // for min #include <memory> // for __shared_ptr, shared_ptr #include <utility> // for pair #include <QDateTime> #include <QDir> #include <QFile> #include <QFileInfo> #include <QList> #include <QSettings> #include <QString> #include <QStringList> #define RECENTS_FILENAME "recents.ini" constexpr const char* ITEM_SUBKEY_SOURCE_CREATOR_NAME = "__sc_name"; constexpr const char* ITEM_SUBKEY_FORMAT_NAME = "__format_name"; constexpr const char* ITEM_SUBKEY_FORMAT_PATH = "__format_path"; constexpr const char* ITEM_SUBKEY_INPUTS = "inputs"; void PVCore::PVRecentItemsManager::add_source(PVRush::PVSourceCreator_p source_creator_p, const PVRush::PVInputType::list_inputs& inputs, const PVRush::PVFormat& format) { _recents_settings.beginGroup(_recents_items_keys[SOURCES]); // Look for the timestamp to replace uint64_t source_timestamp = get_source_timestamp_to_replace( PVRush::PVSourceDescription(inputs, source_creator_p, format)); if (source_timestamp) { _recents_settings.remove(QString::number(source_timestamp)); } // Set source description information in it. _recents_settings.beginGroup(QString::number(QDateTime::currentDateTime().toMSecsSinceEpoch())); _recents_settings.setValue(ITEM_SUBKEY_SOURCE_CREATOR_NAME, source_creator_p->registered_name()); _recents_settings.setValue(ITEM_SUBKEY_FORMAT_NAME, format.get_format_name()); _recents_settings.setValue(ITEM_SUBKEY_FORMAT_PATH, format.get_full_path()); _recents_settings.beginWriteArray(ITEM_SUBKEY_INPUTS); int inputs_index = 0; for (auto input : inputs) { _recents_settings.setArrayIndex(inputs_index++); input->save_to_qsettings(_recents_settings); } _recents_settings.endArray(); _recents_settings.endGroup(); _recents_settings.endGroup(); _recents_settings.sync(); _add_item[Category::SOURCES].emit(); } void PVCore::PVRecentItemsManager::clear(Category category, QList<int> indexes) { if (category == Category::SOURCES) { _recents_settings.beginGroup(_recents_items_keys[Category::SOURCES]); QStringList sources = _recents_settings.childGroups(); for (int i = sources.length(); i-- > 0;) { _recents_settings.beginGroup(sources.at(i)); if (indexes.isEmpty() || indexes.contains(sources.length() - i - 1)) { _recents_settings.endGroup(); _recents_settings.remove(sources.at(i)); } else { _recents_settings.endGroup(); } } _recents_settings.endGroup(); } else { QString item_key = _recents_items_keys.value(category); QStringList in_list = _recents_settings.value(item_key).toStringList(); QStringList out_list; int index = 0; for (const QString& s : in_list) { if (!indexes.contains(index)) { out_list << s; } index++; } _recents_settings.setValue(item_key, indexes.isEmpty() ? QStringList() : out_list); } _recents_settings.sync(); } template <PVCore::Category category> typename PVCore::list_type<category>::type PVCore::PVRecentItemsManager::items_list() const { QStringList v = _recents_settings.value(_recents_items_keys[category]).toStringList(); std::vector<std::string> res(v.size()); std::transform(v.begin(), v.end(), res.begin(), std::mem_fun_ref(&QString::toStdString)); return res; } void PVCore::PVRecentItemsManager::remove_missing_files(Category category) { QStringList string_list = _recents_settings.value(_recents_items_keys[category]).toStringList(); QStringList out_string_list; for (QString s : string_list) { if (QFile::exists(s)) { out_string_list << s; } } _recents_settings.setValue(_recents_items_keys[category], out_string_list); _recents_settings.sync(); } void PVCore::PVRecentItemsManager::remove_invalid_source() { _recents_settings.beginGroup(_recents_items_keys[SOURCES]); QStringList sources = _recents_settings.childGroups(); for (QString source : sources) { _recents_settings.beginGroup(source); try { PVCore::PVSerializedSource ss(deserialize_source_description()); PVRush::PVSourceDescription src_desc(ss); _recents_settings.endGroup(); } catch (PVRush::BadInputDescription const& e) { _recents_settings.endGroup(); _recents_settings.remove(source); } catch (PVCore::InvalidPlugin const& e) { _recents_settings.endGroup(); _recents_settings.remove(source); } catch (PVRush::PVInvalidFile const& e) { _recents_settings.endGroup(); _recents_settings.remove(source); } } _recents_settings.endGroup(); _recents_settings.sync(); } std::vector<PVCore::PVSerializedSource> PVCore::PVRecentItemsManager::sources_description_list() { std::vector<PVCore::PVSerializedSource> res; _recents_settings.beginGroup(_recents_items_keys[SOURCES]); QStringList sources = _recents_settings.childGroups(); for (int i = sources.length(); i-- > 0;) { QString source = sources.at(i); _recents_settings.beginGroup(source); try { res.emplace_back(deserialize_source_description()); } catch (PVRush::BadInputDescription const& e) { // Input description is invalid } catch (PVCore::InvalidPlugin const& e) { // If the plugin is incorrect, skip this file } catch (PVRush::PVInvalidFile const& e) { // If a format can't be found, skip this source. } _recents_settings.endGroup(); } _recents_settings.endGroup(); return res; } void PVCore::PVRecentItemsManager::clear_missing_files() { remove_invalid_source(); remove_missing_files(Category::PROJECTS); remove_missing_files(Category::USED_FORMATS); remove_missing_files(Category::EDITED_FORMATS); } uint64_t PVCore::PVRecentItemsManager::get_source_timestamp_to_replace( const PVRush::PVSourceDescription& source_description) { QStringList sources = _recents_settings.childGroups(); uint64_t older_timestamp = QDateTime::currentDateTime().toMSecsSinceEpoch(); for (QString source_timestamp : sources) { older_timestamp = std::min(older_timestamp, (uint64_t)source_timestamp.toULong()); _recents_settings.beginGroup(source_timestamp); try { PVRush::PVSourceDescription src_desc(deserialize_source_description()); if (source_description == src_desc) { _recents_settings.endGroup(); return source_timestamp.toULong(); } } catch (PVRush::BadInputDescription const& e) { // If any input is invalid, it can't be the searched as a source to replace. } catch (PVCore::InvalidPlugin const& e) { // If the plugin is invalid, it can't be the searched as a source to replace. } catch (PVRush::PVInvalidFile const& e) { // If the format is invalid, it can't be the searched as a source to replace. } _recents_settings.endGroup(); } if (sources.size() < _max_recent_items) { return 0; } return older_timestamp; } PVCore::PVSerializedSource PVCore::PVRecentItemsManager::deserialize_source_description() { // source creator PVCore::PVSerializedSource seri_src{ {}, _recents_settings.value(ITEM_SUBKEY_SOURCE_CREATOR_NAME).toString().toStdString(), _recents_settings.value(ITEM_SUBKEY_FORMAT_NAME).toString().toStdString(), _recents_settings.value(ITEM_SUBKEY_FORMAT_PATH).toString().toStdString()}; // get inputs data PVRush::PVSourceCreator_p src_creator_p = LIB_CLASS(PVRush::PVSourceCreator)::get().get_class_by_name( QString::fromStdString(seri_src.sc_name)); PVRush::PVInputType_p input_type_p = src_creator_p->supported_type_lib(); uint64_t nb_inputs = _recents_settings.beginReadArray(ITEM_SUBKEY_INPUTS); try { for (uint64_t j = 0; j < nb_inputs; ++j) { _recents_settings.setArrayIndex(j); seri_src.input_desc.emplace_back( input_type_p->load_input_descr_from_qsettings(_recents_settings)); } _recents_settings.endArray(); } catch (...) { _recents_settings.endArray(); throw; } return seri_src; } static QString get_recent_items_file() { QFileInfo fi(QString::fromStdString(PVCore::PVConfig::user_dir()) + QDir::separator() + RECENTS_FILENAME); if (fi.exists() == false) { fi.dir().mkpath(fi.path()); QFileInfo sys_fi(RECENTS_FILENAME); if (sys_fi.exists()) { QFile::copy(sys_fi.filePath(), fi.filePath()); } } return fi.filePath(); } PVCore::PVRecentItemsManager::PVRecentItemsManager() : _recents_settings(get_recent_items_file(), QSettings::IniFormat) { clear_missing_files(); } std::tuple<QString, QStringList> PVCore::PVRecentItemsManager::get_string_from_entry(QString const& string) const { return std::make_tuple(string, QStringList() << string); } std::tuple<QString, QStringList> PVCore::PVRecentItemsManager::get_string_from_entry( PVCore::PVSerializedSource const& src_desc) const { QString long_string; QStringList filenames; if (src_desc.input_desc.size() == 1) { PVRush::PVSourceDescription input(src_desc); QString source_path = input.get_inputs()[0]->human_name(); long_string = source_path + " [" + QString::fromStdString(src_desc.format_name) + "]"; filenames << source_path; } else { PVRush::PVSourceDescription desc(src_desc); for (auto const& input : desc.get_inputs()) { filenames << input->human_name(); } long_string = "[" + QString::fromStdString(src_desc.format_name) + "]\n" + filenames.join("\n"); } return std::make_tuple(long_string, filenames); } std::tuple<QString, QStringList> PVCore::PVRecentItemsManager::get_string_from_entry(PVRush::PVFormat const& format) const { QString long_string = QString("%1 (%2)").arg(format.get_format_name()).arg(format.get_full_path()); QStringList filenames; filenames << format.get_full_path(); return std::make_tuple(long_string, filenames); } namespace PVCore { template <> typename list_type<Category::PROJECTS>::type PVRecentItemsManager::get_list<Category::PROJECTS>() { return items_list<Category::PROJECTS>(); } template <> typename list_type<Category::USED_FORMATS>::type PVRecentItemsManager::get_list<Category::USED_FORMATS>() { return items_list<Category::USED_FORMATS>(); } template <> typename list_type<Category::EDITED_FORMATS>::type PVRecentItemsManager::get_list<Category::EDITED_FORMATS>() { return items_list<Category::EDITED_FORMATS>(); } template <> typename list_type<Category::SOURCES>::type PVRecentItemsManager::get_list<Category::SOURCES>() { return sources_description_list(); } } // namespace PVCore
32.385638
97
0.746654
[ "vector", "transform" ]
708cc142c7b30f28cb428b3fbfca96dbc398aa01
10,236
cpp
C++
tuw_multi_robot_router/src/segment_expander.cpp
sgermanserrano/tuw_multi_robot
97fba5f6d896f20d95445dfa719b4512296dffc0
[ "BSD-3-Clause" ]
146
2018-07-21T09:50:13.000Z
2022-03-31T22:49:01.000Z
tuw_multi_robot_router/src/segment_expander.cpp
sgermanserrano/tuw_multi_robot
97fba5f6d896f20d95445dfa719b4512296dffc0
[ "BSD-3-Clause" ]
34
2018-09-28T09:54:23.000Z
2022-03-10T08:05:01.000Z
tuw_multi_robot_router/src/segment_expander.cpp
sgermanserrano/tuw_multi_robot
97fba5f6d896f20d95445dfa719b4512296dffc0
[ "BSD-3-Clause" ]
79
2018-01-27T23:25:26.000Z
2022-03-31T22:51:36.000Z
/* * Copyright (c) 2017, <copyright holder> <email> * 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 <copyright holder> <email> ''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> <email> 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 <tuw_global_router/segment_expander.h> #include <tuw_global_router/route_coordinator.h> #include <iostream> #define TIME_OVERLAP (1) namespace multi_robot_router { SegmentExpander::SegmentExpander(const CollisionResolverType _cRes) : avr_(TIME_OVERLAP), btr_(TIME_OVERLAP), er_() { setCollisionResolver(_cRes); } void SegmentExpander::setCollisionResolver(const CollisionResolverType _cRes) { crType_ = _cRes; if (_cRes == CollisionResolverType::backtracking) { collision_resolution_ = &btr_; } else if (_cRes == CollisionResolverType::avoidance) { collision_resolution_ = &avr_; } else //if(_cRes == CollisionResolverType::none) { collision_resolution_ = &er_; } } SegmentExpander::CollisionResolverType SegmentExpander::getCollisionResolver() const { return crType_; } void SegmentExpander::reset() { collisions_robots_.clear(); startSegments_.clear(); } void SegmentExpander::addStartExpansionCandidate(Vertex &_start, Vertex &_current, Vertex &_next, Vertex &_end) { if (_current.potential == -1) return; if (_next.potential >= 0) return; int32_t collision = -1; if (route_querry_->checkSegment(_next, _current.potential - TIME_OVERLAP, _current.potential + pCalc_.CalculatePotential(_next) + TIME_OVERLAP, diameter_, collision)) { float pot = _current.potential + pCalc_.CalculatePotential(_next); float h = hx_.calcHeuristic(_next, _end); float weight = pot + h; _next.weight = weight; _next.potential = pot; _next.predecessor_ = &_current; _next.successor_ = &_start; _next.collision = -1; seg_queue_.push(&_next); } } void SegmentExpander::addExpansoionCandidate(Vertex &_current, Vertex &_next, Vertex &_end) { if (_current.potential == -1) return; if (_next.potential >= 0) return; int32_t collision; if (!route_querry_->checkSegment(_next, _current.potential - TIME_OVERLAP, _current.potential + pCalc_.CalculatePotential(_next) + TIME_OVERLAP, diameter_, collision)) { if (collision != -1) { std::vector<std::reference_wrapper<Vertex>> resolutions = collision_resolution_->resolve(_current, _next, collision); for (Vertex &res : resolutions) { float h = hx_.calcHeuristic(res, _end); res.weight = res.potential + h; if (res.getSegment().getSegmentId() == _end.getSegment().getSegmentId()) //Should not happen but safety first :D { res.weight = 0; } seg_queue_.push(&res); } } return; } float pot = _current.potential + pCalc_.CalculatePotential(_next); float h = hx_.calcHeuristic(_next, _end); float weight = pot + h; _next.weight = weight; _next.potential = pot; if (_next.getSegment().getSegmentId() == _end.getSegment().getSegmentId()) _next.weight = 0; _next.predecessor_ = &_current; _next.collision = -1; seg_queue_.push(&_next); } bool SegmentExpander::calculatePotentials(const RouteCoordinatorWrapper *_p, Vertex &_start, Vertex &_end, const uint32_t _maxIterations, const uint32_t _diameter) { route_querry_ = _p; collisions_robots_.clear(); collision_resolution_->resetSession(_p, &pCalc_, _diameter); diameter_ = _diameter; Vertex *foundEnd = expandVoronoi(_start, _end, _maxIterations); if (foundEnd == NULL) return false; //Save actual planning status from parallel ends :D if (&_end != foundEnd) _end.updateVertex(*foundEnd); return (foundEnd->getSegment().getSegmentId() == _end.getSegment().getSegmentId()); } void SegmentExpander::resolveStartCollision(Vertex &_start, Vertex &_end) { int collision = -1; _start.collision = -1; _start.predecessor_ = NULL; _start.potential = -1; clearpq(seg_queue_); //If the robot wants to stay on its pose we have to add a additional segment to enable avoiding higher prioritized robots if (_start.getSegment().getSegmentId() == _end.getSegment().getSegmentId() && !route_querry_->checkSegment(_start, 0, -1, diameter_, collision) && collision != -1) { // Force the robot to move away from the segment startSegments_.emplace_back(std::make_unique<Vertex>(_start)); Vertex &start = *(startSegments_.back().get()); start.predecessor_ = NULL; start.potential = pCalc_.CalculatePotential(start); start.collision = -1; const std::vector<std::reference_wrapper<Vertex>> &n_succ = start.getPlanningSuccessors(); for (Vertex &v : n_succ) { //One to move back to start startSegments_.emplace_back(std::make_unique<Vertex>(v)); addStartExpansionCandidate(_start, start, *(startSegments_.back().get()), _end); //One to expand Normal (Not working because we are blocking our own path) //TODO find fix //All adjacent vertices to start are allready expanded. Hence there is no way back to start //addExpansoionCandidate(start, v, _end); } const std::vector<std::reference_wrapper<Vertex>> &n_pred = start.getPlanningPredecessors(); for (Vertex &v : n_pred) { //One to move back to start startSegments_.emplace_back(std::make_unique<Vertex>(v)); addStartExpansionCandidate(_start, start, *(startSegments_.back().get()), _end); //One to expand Normal (Not working well because we are blocking our own path) //TODO find fix //All adjacent vertices to start are allready expanded. Hence there is no way back to start //addExpansoionCandidate(start, v, _end); } } else { _start.collision = -1; _start.predecessor_ = NULL; _start.potential = pCalc_.CalculatePotential(_start); clearpq(seg_queue_); int32_t collision = -1; if (route_querry_->checkSegment(_start, 0, _start.potential + TIME_OVERLAP, diameter_, collision)) { seg_queue_.push(&_start); } else if (collision != -1) { collision_resolution_->saveCollision(collision); } } } bool SegmentExpander::containsVertex(const Vertex &_v, const std::vector<std::reference_wrapper<Vertex>> &_list) const { for (const Vertex &v : _list) { if (_v.getSegment().getSegmentId() == v.getSegment().getSegmentId()) return true; } return false; } void SegmentExpander::setSpeed(const float &_speed) { pCalc_.SetMultiplier(_speed); } Vertex *SegmentExpander::expandVoronoi(Vertex &_start, Vertex &_end, const uint32_t _cycles) { startSegments_.clear(); uint32_t cycle = 0; //For having a high startpotential resolveStartCollision(_start, _end); Vertex *current = NULL; while (!(seg_queue_.empty()) && (cycle < _cycles) && (current == NULL || _end.getSegment().getSegmentId() != current->getSegment().getSegmentId())) { if (seg_queue_.empty()) return NULL; current = seg_queue_.top(); seg_queue_.pop(); //The segment expander is forced to expand to the successor (generated by the collision resolution) if (current->successor_ != NULL) { addExpansoionCandidate(*current, *(current->successor_), _end); } else { const std::vector<std::reference_wrapper<Vertex>> &n_succ = current->getPlanningSuccessors(); if (current->predecessor_ == NULL || !containsVertex(*(current->predecessor_), n_succ)) { for (Vertex &v : n_succ) { addExpansoionCandidate(*current, v, _end); } } const std::vector<std::reference_wrapper<Vertex>> &n_pred = current->getPlanningPredecessors(); if (current->predecessor_ == NULL || !containsVertex(*(current->predecessor_), n_pred)) { for (Vertex &v : n_pred) { addExpansoionCandidate(*current, v, _end); } } } cycle++; } if (current == NULL || current->getSegment().getSegmentId() != _end.getSegment().getSegmentId()) return NULL; return current; } const std::vector<uint32_t> &SegmentExpander::getRobotCollisions() const { return collision_resolution_->getRobotCollisions(); } } // namespace multi_robot_router
33.671053
171
0.652208
[ "vector" ]
708ea3b6829e2da876bd4c5888306f89d893d020
27,132
cpp
C++
tools/dc/src/fe.cpp
nonlocalmodels/NLMech
1f7c73438277daf215e38f57aa5bf49e0679987a
[ "BSL-1.0" ]
7
2020-10-25T12:46:40.000Z
2021-11-22T09:03:56.000Z
tools/dc/src/fe.cpp
nonlocalmodels/NLMech
1f7c73438277daf215e38f57aa5bf49e0679987a
[ "BSL-1.0" ]
24
2020-09-04T00:16:38.000Z
2021-07-20T18:44:49.000Z
tools/dc/src/fe.cpp
PeriHPX/PeriHPX
93b2861574cfe3bb071f27d8805fa79c295716b3
[ "BSL-1.0" ]
1
2020-10-25T12:53:52.000Z
2020-10-25T12:53:52.000Z
//////////////////////////////////////////////////////////////////////////////// // Copyright (c) 2019 Prashant K. Jha // Copyright (c) 2019 Patrick Diehl // // 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) //////////////////////////////////////////////////////////////////////////////// #include <fe/triElem.h> #include <util/feElementDefs.h> #include "dcInclude.h" #include "fe/mesh.h" #include "inp/decks/meshDeck.h" #include "rw/reader.h" #include "rw/writer.h" #include "util/compare.h" #include "util/matrix.h" #include "util/point.h" #include "util/transfomation.h" #include "util/utilGeom.h" static int init = -1; /*! @brief Local namespace */ namespace fe { /*! @brief Data structure to hold simulation data in one place */ struct SimData { /*! * @brief Constructor */ SimData() : d_isFd(true), d_mesh_p(nullptr), d_h(0.), d_Nt(1), d_dt(0.), d_dtOut(1){}; /*! @brief Is this finite difference simulation */ bool d_isFd; /*! @brief Mesh filename */ std::string d_filename; /*! @brief Pointer to mesh data */ fe::Mesh *d_mesh_p; /*! @brief Current position of all nodes */ std::vector<util::Point3> d_y; /*! @brief Current displacement of all nodes */ std::vector<util::Point3> d_u; /*! @brief Mesh size */ double d_h; /*! @brief Number of time steps */ size_t d_Nt; /*! @brief Size of time steps */ double d_dt; /*! @brief Output frequency */ size_t d_dtOut; }; struct DataCompare { /*! * @brief Constructor */ DataCompare() : d_isFd(true), d_numQuads(1), d_diffAtCurrent(true), d_read12(true){}; /*! @brief Is this finite difference simulation */ bool d_isFd; /*! @brief Number of quadrature points */ size_t d_numQuads; /*! @brief Compute L2 difference at current configuration */ bool d_diffAtCurrent; /*! @brief Path for simulation 1 data */ std::string d_path1; /*! @brief Path for simulation 2 data */ std::string d_path2; /*! @brief Path for output of file */ std::string d_pathOut; /*! @brief Tag for output of file */ std::string d_filenameOut; /*! @brief Is this run for reading 1 and 2 tags in input file */ bool d_read12; }; /*! @brief Read input files * * @param sim_1 Simulation 1 data * @param sim_2 Simulation 2 data * @param dc Data comparison options * @param config YAML input file */ void readInputFile(SimData *sim_1, SimData *sim_2, DataCompare *dc, YAML::Node config) { // // if read_12 = true // // read Data_1 and Data_2 and provide output filename for // error between Data_1 and Data_2 // // if read_12 = false // // read Data_2 and Data_3 and provide output filename for // error between Data_2 and Data_3 // dc->d_pathOut = config["Output"]["Path"].as<std::string>(); dc->d_filenameOut = dc->d_pathOut + "/"; if (config["Output"]["File"]) dc->d_filenameOut += config["Output"]["File"].as<std::string>(); else dc->d_filenameOut += "dc"; // below tag is counter intuitive but should not be changed // as the python scripts understand error files based on below tags bool triple_data = false; if (config["Triple_Data"]) triple_data = config["Triple_Data"].as<bool>(); // append tags only if triple_data is true if (triple_data) { if (dc->d_read12) dc->d_filenameOut += "_23.out"; else dc->d_filenameOut += "_12.out"; } else dc->d_filenameOut += ".out"; // string name for data 1 and 2 (in case of read_12 is false data 1 is Data_2 // and data 2 is Data_3) std::string data_1; std::string data_2; if (dc->d_read12) { data_1 = "Data_1"; data_2 = "Data_2"; } else { data_1 = "Data_2"; data_2 = "Data_3"; } // check if data is provided if (!config[data_1]) { std::cerr << "Input file does not contain information about data = " << data_1 << "\n"; exit(1); } if (!config[data_2]) { std::cerr << "Input file does not contain information about data = " << data_2 << "\n"; exit(1); } // is this fd simulation comparison dc->d_isFd = false; // if (config["Diff_Find_Current"]) dc->d_diffAtCurrent = config["Diff_Find_Current"].as<bool>(); else dc->d_diffAtCurrent = true; if (config["Num_Quads"]) dc->d_numQuads = config["Num_Quads"].as<size_t>(); else dc->d_numQuads = 4; // check if time is provided globally bool time_global = false; if (config["Final_Time"]) { time_global = true; auto time = config["Final_Time"].as<double>(); sim_1->d_Nt = config["Time_Steps"].as<size_t>(); sim_2->d_Nt = sim_1->d_Nt; sim_1->d_dt = time / double(sim_1->d_Nt); sim_2->d_dt = sim_1->d_dt; sim_1->d_dtOut = config["Output_Interval"].as<size_t>(); sim_2->d_dtOut = sim_1->d_dtOut; } // check if horizon is provided bool horizon_global = false; double horizon = 0.0; if (config["Horizon"]) { horizon_global = true; horizon = config["Horizon"].as<double>(); // compute mesh size of fine mesh by reading the ratio auto r = config[data_1]["Horizon_Factor_m_value"].as<size_t>(); sim_1->d_h = horizon / double(r); // coarse mesh r = config[data_2]["Horizon_Factor_m_value"].as<size_t>(); sim_2->d_h = horizon / double(r); } // read data 1 if (!horizon_global) { sim_1->d_h = config[data_1]["Mesh_Size"].as<double>(); } if (!time_global) { sim_1->d_Nt = config[data_1]["Time_Steps"].as<size_t>(); auto d = config[data_1]["Final_Time"].as<double>(); sim_1->d_dt = d / double(sim_1->d_Nt); sim_1->d_dtOut = config[data_1]["Output_Interval"].as<size_t>(); } dc->d_path1 = config[data_1]["Path"].as<std::string>(); // check if mesh file name is provided if (config[data_1]["Mesh_Filename"]) sim_1->d_filename = config[data_1]["Mesh_Filename"].as<std::string>(); // read data 2 if (!horizon_global) { sim_2->d_h = config[data_2]["Mesh_Size"].as<double>(); } if (!time_global) { sim_2->d_Nt = config[data_2]["Time_Steps"].as<size_t>(); auto d = config[data_2]["Final_Time"].as<double>(); sim_2->d_dt = d / double(sim_2->d_Nt); sim_2->d_dtOut = config[data_2]["Output_Interval"].as<size_t>(); } dc->d_path2 = config[data_2]["Path"].as<std::string>(); // check if mesh file name is provided if (config[data_1]["Mesh_Filename"]) sim_1->d_filename = config[data_1]["Mesh_Filename"].as<std::string>(); } /*! @brief Computes displacement of coarse mesh at quadrature point of fine mesh * * @param x1 Quadrature point in element of mesh 1 * @param e1 Element id in mesh 1 * @param q Quadrature id * @param sim1 Simulation 1 data * @param sim2 Simulation 2 data * @param dc Collection of user-specified input data * @param read_counter Read counter used in bypassing the calculation of * element id in mesh 2 (if specified in the input file) * @param e2 Element id containing x1 in mesh 2 * @return u Displacement at the quad point */ util::Point3 getDisplacementAtQuadPoint( const util::Point3 &x1, const size_t &e1, const size_t &q, const SimData *sim1, const SimData *sim2, const DataCompare *dc, const size_t &read_counter, size_t &e2) { // get the pointer to mesh 2 const auto mesh2 = sim2->d_mesh_p; // // find the node which is closest to x1. Use reference // configuration of node. // // Note that x1 here is quadrature point which is again in // reference configuration. // // Therefore, we can save the node id and element id for // reuse for each quadrature point of each element. // // see if we need to compute the element id which contains // point x1 or reuse previous computed id bool compute_el_id = !(!dc->d_diffAtCurrent and read_counter > 2); size_t el_id = 0; if (compute_el_id) { static int debug_counter = 0; static bool debug_el_ids = false; std::string filename = dc->d_pathOut + "/debug_find_elem.txt"; static FILE *fout = NULL; if (debug_el_ids) fout = fopen(filename.c_str(), "w"); // double h = sim2->d_h; // loop over node and find the node which is closest to the point int i_found = -1; double check = std::sqrt(2.) * 0.5 * h + 0.01 * h; double dist = 10.0 * h; for (size_t i = 0; i < mesh2->getNumNodes(); i++) { auto diff = x1 - mesh2->getNode(i); if (util::compare::definitelyLessThan(diff.length(), dist)) { dist = diff.length(); i_found = i; } } if (i_found == -1) { std::cerr << "Node closer to x = " << x1.printStr() << " not found." << " h = " << h << ", dist = " << dist << ", check = " << check << std::endl; exit(1); } // if (dist > check) { // std::cerr<< // "Node closer to x = ["<<x.x<<","<<x.y<< // "] not found. h = "<< // h<<", dist = "<< // dist<<" check = "<< // check<<".\n"; // exit(1); // } // now that we have found the node closest to xi // we loop over the elements sharing the node // // We look at the intersection of line xi \to xnode and line between two // other nodes in triangle // // If distance of intersection point and xi is smaller than the // distance of intersection point and xnode than xi will be // inside. // // At the same time we also test if line between xnode and // point xi is parallel to any of the edge of // element auto xi = mesh2->getNode(i_found); auto yi = sim2->d_y[i_found]; auto i_elems = mesh2->getElementConnectivity(i_found); int e_found = -1; for (unsigned long e_id : i_elems) { auto e_nodes = mesh2->getElementConnectivity(e_id); // find the local id of node i_found in element el int i_loc = -1; for (size_t j = 0; j < e_nodes.size(); j++) if (e_nodes[j] == i_found) i_loc = j; if (i_loc == -1) { std::cerr << "Error: Check element node connectivity.\n"; exit(1); } // find the nodes order acw starting from i_found auto node_list = util::transformation::cyclicOrderACW(i_loc, e_nodes.size()); // get the angle between two lines // // // // x' // + // \ | / // \ | / // \|/ // o i = i_found // /|\ // / | \ // L1 / | \ L2 // / |L0 \ // / x \ // / \ // o o // i+1 i-1 // // Line 1: (x_i, x_i+1) // Line 2: (x_i, x_i-1) // // Line 0: (x_i, x) // // Angle theta_12: angle between Line 1 and Line 2 // Angle theta_01: angle between Line 1 and Line 0 // Angle theta_02: angle between Line 2 and Line 0 // // If theta_12 >= theta_01 and theta_12 >= theta_02 // ---> Then Line 0 lies between Line 1 and Line 2 // ---> There are two possibilities // ---> Case 1: x is indeed in the interior of // element formed by i,i+1,i+2,...,i-1 // ---> Case 2: x is in the location x' // Note that x' also satisifies the similar angular // condition // // ---> We eliminate Case 2, by looking at the area // of triangle T0 : (x, x_i+1, x_i-1) // triangle T1 : (xi, x_i+1, x_i-1) // // If x inside the triangle then Area(T0) < Area(T1) // // get the ids of nodes auto i = node_list[0]; auto ip1 = node_list[1]; auto im1 = node_list[node_list.size() - 1]; xi = mesh2->getNode(e_nodes[i]); auto xip1 = mesh2->getNode(e_nodes[ip1]); auto xim1 = mesh2->getNode(e_nodes[im1]); double theta_12 = (xip1 - xi).angle(xim1 - xi); double theta_01 = (xip1 - xi).angle(x1 - xi); double theta_02 = (x1 - xi).angle(xim1 - xi); std::vector<util::Point3> nodes = {x1, xip1, xim1}; if (theta_01 <= 1.0E-4 or theta_02 <= 1.0E-4 or theta_01 >= M_PI - 1.0E-4 or theta_02 >= M_PI - 1.0E-4) { // Line 0 is either parallel to Line 1 or Line 2 // we now eliminate the other possibility double area_T0 = std::abs(util::geometry::getTriangleArea(nodes)); double area_T1 = std::abs(util::geometry::getTriangleArea(nodes)); if (area_T0 <= area_T1) { // we have found the element // write the global id e_found = int(e_id); } } // proceed ahead only if condition is met if (util::compare::definitelyLessThan(theta_01 - theta_12, 0.0) and util::compare::definitelyLessThan(theta_02 - theta_12, 0.0)) { // we now eliminate the other possibility double area_T0 = std::abs(util::geometry::getTriangleArea(nodes)); double area_T1 = std::abs(util::geometry::getTriangleArea(nodes)); if (util::compare::definitelyLessThan(area_T0 - area_T1, 0.0) or util::compare::essentiallyEqual(area_T0 - area_T1, 0.0)) { // we have found the element // write the global id e_found = int(e_id); } } if (e_found != -1) break; } if (e_found == -1) { std::cerr << "Error: Can not locate element in the mesh for point.\n"; std::cerr << " x = " << x1.printStr() << ", x_node = " << xi.printStr() << ", dist = " << dist << ", h = " << h << "\n"; std::cerr << "Element id in mesh 1 = " << e1 << "\n"; for (size_t j = 0; j < i_elems.size(); j++) { std::cerr << "Element " << j + 1 << ": global id = " << i_elems[j] << "; nodes = "; std::vector<size_t> jel_nodes = mesh2->getElementConnectivity(i_elems[j]); for (unsigned long jel_node : jel_nodes) { std::cerr << "(id = " << jel_node << ", x = " << mesh2->getNode(jel_node).printStr() << ")"; } std::cerr << std::endl; } exit(1); } else { // write debug output if (debug_counter % 10 == 0 and debug_counter < 500 and debug_el_ids) { std::vector<size_t> jel_nodes = mesh2->getElementConnectivity(i_elems[e_found]); fprintf(fout, "----------------------\n"); fprintf(fout, "x = [%s]; xnode = [%s]; dist = %6.8e; h = " "%6.8e;\n", x1.printStr().c_str(), xi.printStr().c_str(), dist, h); fprintf(fout, "element = %lu; x1 = [%s]; x2 = [%s]; x3 = " "[%s];\n", i_elems[e_found], mesh2->getNode(jel_nodes[0]).printStr().c_str(), mesh2->getNode(jel_nodes[1]).printStr().c_str(), mesh2->getNode(jel_nodes[2]).printStr().c_str()); } } debug_counter++; if (debug_counter == 500 and debug_el_ids) fclose(fout); // el_id = size_t(e_found); // we have found the element id. See if we need to // add it to list for future reuse if (read_counter == 1) e2 = el_id; // check if this is not the first call to this function if (read_counter > 1 and e2 != el_id) { std::cout << "Error: stored element in mesh 2 = " << e2 << " and computed element in mesh 2 = " << el_id << " not matching, read_counter = " << read_counter << "\n"; if (read_counter > 2) exit(1); } } else { el_id = e2; } // // now that we have found the element, we compute the shape function // at the point x and then finally compute displacement at point x // auto jel_nodes = mesh2->getElementConnectivity(el_id); std::vector<double> shapes; std::vector<util::Point3> nodes_d; std::vector<util::Point3> ys_d; for (unsigned long jel_node : jel_nodes) { nodes_d.push_back(mesh2->getNode(jel_node)); ys_d.push_back(sim2->d_y[jel_node]); } // currently we only support triangle element to compute shape function at // any arbitrary point on element if (mesh2->getElementType() == util::vtk_type_triangle) { auto tri = fe::TriElem(1); shapes = tri.getShapes(x1, nodes_d); } else { std::cerr << "Error: Can not compute shape function at arbitrary point " "for quadrilateral elements\n"; exit(1); } auto u = util::Point3(); for (size_t j = 0; j < jel_nodes.size(); j++) for (size_t dof = 0; dof < 3; dof++) u[dof] += shapes[j] * (ys_d[j][dof] - nodes_d[j][dof]); return u; } /*! @brief Computes displacement of coarse mesh at quadrature point of fine mesh * * @param x1 Node in mesh 1 * @param e1 Element id in mesh 1 * @param q Quadrature id * @param sim1 Simulation 1 data * @param sim2 Simulation 2 data * @param dc Collection of user-specified input data */ util::Point3 getDisplacementAtQuadPointCurrentSimple( const util::Point3 &x1, const size_t &e1, const size_t &q, const SimData *sim1, const SimData *sim2, const DataCompare *dc) { // get the pointer to mesh 2 const auto mesh2 = sim2->d_mesh_p; // // find the node which is closest to y. Use current // configuration of node. // // Note that y here is quadrature point's current position // size_t el_id = 0; static int debug_counter = 0; static bool debug_el_ids = false; std::string filename = dc->d_pathOut + "/debug_find_elem.txt"; FILE *fout = nullptr; if (debug_el_ids) fout = fopen(filename.c_str(), "w"); // double h = sim2->d_h; // loop over node and find the node which is closest to the point int i_found = -1; double check = std::sqrt(2.) * 0.5 * h + 0.01 * h; double dist = 10.0 * h; for (size_t i = 0; i < mesh2->getNumNodes(); i++) { auto diff = x1 - (sim2->d_y[i] + mesh2->getNode(i)); if (util::compare::definitelyLessThan(diff.length(), dist)) { dist = diff.length(); i_found = i; } } if (i_found == -1) { std::cerr << "Node closer to x1 = " << x1.printStr() << " not found. h = " << h << ", dist = " << dist << " check = " << check << ".\n"; exit(1); } // return displacement of the node that we found return sim2->d_y[i_found] - mesh2->getNode(i_found); } // // compute error // void compute(bool read_12, const YAML::Node &config) { // create various data auto sim1 = SimData(); auto sim2 = SimData(); auto dc = DataCompare(); dc.d_diffAtCurrent = true; // read file fe::readInputFile(&sim1, &sim2, &dc, config); // create output file stream FILE *file_out = fopen(dc.d_filenameOut.c_str(), "w"); // write header // fprintf(file_out, "Time L2_Error Sup_Error\n"); if (read_12) std::cout << "*** set 1-2 ***\n"; else std::cout << "\n*** set 2-3 ***\n"; // // data for mesh 1 (fine mesh) // std::vector<std::vector<fe::QuadData>> qd_data1; // // Data to store elements searched in first call. These elements are in // mesh 2 and contain the quadrature points of mesh 1 elements. // std::vector<std::vector<size_t>> els_cm_of_qpts; // loop over time (assuming dt is same for both files) size_t read_counter = 1; for (size_t k = 0; k <= sim1.d_Nt; k++) { double tk1 = double(k) * sim1.d_dt; double l2 = 0.; // to hold l2 norm of error double sup = 0.; // to hold sup norm of error size_t dt_check = k % sim1.d_dtOut; // in first call, create mesh data for both simulation 1 and 2 if (dt_check == 0 && read_counter == 1) { { // mesh for simulation 1 // do we read mesh from mesh file provided in the input yaml or we read // mesh from the first simulation output file? if (sim1.d_filename.empty()) sim1.d_filename = dc.d_path1 + "/output_" + std::to_string(read_counter - 1) + ".vtu"; // create mesh deck auto mdeck = inp::MeshDeck(); mdeck.d_dim = 2; mdeck.d_h = sim1.d_h; mdeck.d_filename = sim1.d_filename; if (dc.d_isFd) mdeck.d_spatialDiscretization = "finite_difference"; else mdeck.d_spatialDiscretization = "finite_element"; // create mesh sim1.d_mesh_p = new fe::Mesh(&mdeck); } { // mesh for simulation 2 // do we read mesh from mesh file provided in the input yaml or we read // mesh from the first simulation output file? if (sim2.d_filename.empty()) sim2.d_filename = dc.d_path2 + "/output_" + std::to_string(read_counter - 1) + ".vtu"; // create mesh deck auto mdeck = inp::MeshDeck(); mdeck.d_dim = 2; mdeck.d_h = sim2.d_h; mdeck.d_filename = sim2.d_filename; if (dc.d_isFd) mdeck.d_spatialDiscretization = "finite_difference"; else mdeck.d_spatialDiscretization = "finite_element"; // create mesh sim2.d_mesh_p = new fe::Mesh(&mdeck); } } // we compare data in this step if (dt_check == 0) { { // read data 1 std::string filename1 = dc.d_path1 + "/output_" + std::to_string(read_counter - 1) + ".vtu"; // read current position rw::reader::readVtuFileNodes(filename1, sim1.d_mesh_p->getDimension(), &sim1.d_y, false); // read displacement (if Tag displacement is not in simulation output // file, then displacement can be found by subtracting current // position of nodes with their reference position) if (!rw::reader::readVtuFilePointData(filename1, "Displacement", &sim1.d_u)) { sim1.d_u.resize(sim1.d_mesh_p->getNumNodes()); for (size_t i = 0; i < sim1.d_mesh_p->getNumNodes(); i++) sim1.d_u[i] = sim1.d_y[i] - sim1.d_mesh_p->getNode(i); } } { // read data 1 std::string filename2 = dc.d_path2 + "/output_" + std::to_string(read_counter - 1) + ".vtu"; // read current position rw::reader::readVtuFileNodes(filename2, sim2.d_mesh_p->getDimension(), &sim2.d_y, false); // read displacement (if Tag displacement is not in simulation output // file, then displacement can be found by subtracting current // position of nodes with their reference position) if (!rw::reader::readVtuFilePointData(filename2, "Displacement", &sim2.d_u)) { sim2.d_u.resize(sim2.d_mesh_p->getNumNodes()); for (size_t i = 0; i < sim2.d_mesh_p->getNumNodes(); i++) sim2.d_u[i] = sim2.d_y[i] - sim2.d_mesh_p->getNode(i); } } // resize dummy element list if (read_counter == 1 && !dc.d_isFd) { // els_fm is of the size of fine mesh qd_data1.resize(sim1.d_mesh_p->getNumElements()); // els_cm_of_qpts is also of the size of fine mesh els_cm_of_qpts.resize(sim1.d_mesh_p->getNumElements()); // allocate enough space to inner vector // Max number of quad points is 12 (increase this if needed) for (auto &els_cm_of_qpt : els_cm_of_qpts) els_cm_of_qpt = std::vector<size_t>(12, 0); } // get alias for mesh 1 and mesh 2 const auto mesh1 = sim1.d_mesh_p; // use hpx loop std::vector<double> l2_vec(mesh1->getNumElements(), 0.0); std::vector<double> sup_vec(mesh1->getNumElements(), 0.0); // loop over nodes in elements1 for (size_t e = 0; e < mesh1->getNumElements(); e++) { auto e_nodes = mesh1->getElementConnectivity(e); // compute quad points on copy of current element std::vector<fe::QuadData> e_quads; if (read_counter == 1) { // create node data for quad function std::vector<util::Point3> nodes_d; for (unsigned long n : e_nodes) { nodes_d.push_back(mesh1->getNode(n)); } // call quad function if (mesh1->getElementType() == util::vtk_type_triangle) { auto tri = fe::TriElem(dc.d_numQuads); e_quads = tri.getQuadPoints(nodes_d); } else { std::cerr << "Error: Only triangle element is supported in data " "comparison" << std::endl; exit(1); } // created temp_el with quad data so now push it to // dummy list for reuse next time qd_data1[e] = e_quads; // resize inner size of els_cm_of_qpts if (els_cm_of_qpts[e].size() != e_quads.size()) els_cm_of_qpts[e] = std::vector<size_t>(e_quads.size(), 0); } else e_quads = qd_data1[e]; // loop over quad points for (size_t q = 0; q < e_quads.size(); q++) { auto xq = e_quads[q].d_p; // get displacement and current position of quad point auto uq1 = util::Point3(); auto yq = xq; for (size_t i = 0; i < e_nodes.size(); i++) { size_t n = e_nodes[i]; auto xi = mesh1->getNode(n); auto yi = sim1.d_y[n]; for (size_t dof = 0; dof < 3; dof++) uq1[dof] += (yi[dof] - xi[dof]) * e_quads[q].d_shapes[i]; } yq += uq1; // get element id of coarse mesh size_t el_in_cm = els_cm_of_qpts[e][q]; // get displacement of mesh 2 at xq auto uq2 = util::Point3(); uq2 = getDisplacementAtQuadPoint(xq, e, q, &sim1, &sim2, &dc, read_counter, el_in_cm); // if this is first reading than store element // id for reuse in next reading if (read_counter == 1) els_cm_of_qpts[e][q] = el_in_cm; // compute difference of displacement auto du = uq1 - uq2; // compute l2 error l2 += du.length() * du.length() * e_quads[q].d_w; // compute sup norm if (util::compare::definitelyGreaterThan(du.length(), sup)) sup = du.length(); } } // l2 = std::sqrt(l2); // write error to the file fprintf(file_out, "%8.6e %8.6e %8.6e\n", tk1, l2, sup); // write to the screen printf("Time = %8.6e, L2 error = %8.6e, Sup error = %8.6e\n", tk1, l2, sup); // read_counter++; } } fclose(file_out); } } // namespace fe // // main function // void dc::fe(YAML::Node config) { // check if three sets of data are provided bool triple_data = false; if (config["Triple_Data"]) triple_data = config["Triple_Data"].as<bool>(); bool read_12 = true; fe::compute(read_12, config); read_12 = false; if (triple_data) fe::compute(read_12, config); }
31.008
80
0.569365
[ "mesh", "geometry", "shape", "vector" ]
70935cb5d549ddbafa0c073cc712c605beb331b1
2,807
cpp
C++
scm_gl_core/src/scm/gl_core/constants.cpp
Nyran/schism
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
[ "BSD-3-Clause" ]
10
2015-09-17T06:01:03.000Z
2019-10-23T07:10:20.000Z
scm_gl_core/src/scm/gl_core/constants.cpp
Nyran/schism
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
[ "BSD-3-Clause" ]
5
2015-01-06T14:11:32.000Z
2016-12-12T10:26:53.000Z
scm_gl_core/src/scm/gl_core/constants.cpp
Nyran/schism
c2cdb8884e3e6714a3b291f0f754220b7f5cbc7b
[ "BSD-3-Clause" ]
15
2015-01-29T20:56:13.000Z
2020-07-02T19:03:20.000Z
// Copyright (c) 2012 Christopher Lux <christopherlux@gmail.com> // Distributed under the Modified BSD License, see license.txt. #include "constants.h" #include <cassert> namespace scm { namespace gl { // debugging ////////////////////////////////////////////////////////////////////////////////////// const char* debug_source_string(debug_source s) { assert(DEBUG_SOURCE_API <= s && s < DEBUG_SOURCE_COUNT); switch (s) { case DEBUG_SOURCE_API: return ("api");break; case DEBUG_SOURCE_WINDOW_SYSTEM: return ("window system");break; case DEBUG_SOURCE_SHADER_COMPILER: return ("shader compiler");break; case DEBUG_SOURCE_THIRD_PARTY: return ("third party");break; case DEBUG_SOURCE_APPLICATION: return ("application");break; case DEBUG_SOURCE_OTHER: return ("other");break; default: break; } return ("unknown debug_source"); } const char* debug_type_string(debug_type s) { assert(DEBUG_TYPE_ERROR <= s && s < DEBUG_TYPE_COUNT); switch (s) { case DEBUG_TYPE_ERROR: return ("error");break; case DEBUG_TYPE_DEPRECATED_BEHAVIOR: return ("deprecated behavior");break; case DEBUG_TYPE_UNDEFINED_BEHAVIOR: return ("undefined behavior");break; case DEBUG_TYPE_PORTABILITY: return ("portability");break; case DEBUG_TYPE_PERFORMANCE: return ("performance");break; case DEBUG_TYPE_OTHER: return ("other");break; default: break; } return ("unknown debug_type"); } const char* debug_severity_string(debug_severity s) { assert(DEBUG_SEVERITY_HIGH <= s && s < DEBUG_SEVERITY_COUNT); switch (s) { case DEBUG_SEVERITY_HIGH: return ("high");break; case DEBUG_SEVERITY_MEDIUM: return ("medium");break; case DEBUG_SEVERITY_LOW: return ("low");break; default: break; } return ("unknown debug_severity"); } // shader ///////////////////////////////////////////////////////////////////////////////////////// const char* shader_stage_string(shader_stage s) { assert(STAGE_VERTEX_SHADER <= s && s < SHADER_STAGE_COUNT); switch (s) { case STAGE_VERTEX_SHADER: return ("vertex shader");break; case STAGE_GEOMETRY_SHADER: return ("geometry shader");break; case STAGE_FRAGMENT_SHADER: return ("fragment shader");break; #if SCM_GL_CORE_OPENGL_CORE_VERSION >= SCM_GL_CORE_OPENGL_CORE_VERSION_400 case STAGE_TESS_EVALUATION_SHADER: return ("tesselation evaluation shader");break; case STAGE_TESS_CONTROL_SHADER: return ("tesselation control shader");break; #endif // SCM_GL_CORE_OPENGL_CORE_VERSION >= SCM_GL_CORE_OPENGL_CORE_VERSION_400 default: break; } return ("unknown shader_stage"); } } // namespace gl } // namespace scm
31.188889
99
0.646242
[ "geometry" ]
7093ecbd805160877c7e224c54538bb614e77fbb
8,891
cpp
C++
manager.cpp
lmcad-unicamp/oi-dbt
509b8ee4ffe8c2f5c758e3308db8ab6988ee44a7
[ "MIT" ]
5
2020-08-26T17:58:15.000Z
2021-12-25T12:10:22.000Z
manager.cpp
OpenISA/dbt-openisa
509b8ee4ffe8c2f5c758e3308db8ab6988ee44a7
[ "MIT" ]
null
null
null
manager.cpp
OpenISA/dbt-openisa
509b8ee4ffe8c2f5c758e3308db8ab6988ee44a7
[ "MIT" ]
5
2017-07-25T21:57:58.000Z
2019-04-28T22:42:50.000Z
#include <manager.hpp> #include <OIPrinter.hpp> #include <fstream> #include <vector> #include "llvm/IR/Verifier.h" #include "llvm/Support/raw_ostream.h" #include "timer.hpp" #include "llvm/Transforms/Utils/Cloning.h" #include "llvm/Support/SourceMgr.h" #include "llvm/IRReader/IRReader.h" using namespace dbt; bool hasAddr(const OIInstList& OIRegion, uint32_t Addr) { for (auto Pair : OIRegion) if (Pair[0] == Addr) return true; return false; } llvm::Module* Manager::loadRegionFromFile(std::string Path) { llvm::SMDiagnostic error; auto M = llvm::parseIRFile(RegionPath+Path, error, TheContext).release(); if (M) return M; else return nullptr; } bool compInst(std::array<uint32_t, 2> A, std::array<uint32_t, 2> B) { return (A[0]<B[0]); } void Manager::loadRegionsFromFiles() { std::ifstream infile(RegionPath + "regions.order"); std::string line; std::cout << "Loading Regions from " << RegionPath << "regions.order\n"; while (std::getline(infile, line)) { uint32_t Entry = std::stoi(line); if (!IsToLoadBCFormat) { std::ifstream infile(RegionPath + "r"+std::to_string(Entry)+".oi"); std::string line; OIInstList Insts; while (std::getline(infile, line)) { std::istringstream iss(line); uint32_t Addrs, Opcode; if (!(iss >> Addrs >> Opcode)) { break; } Insts.push_back({Addrs, Opcode}); } addOIRegion(Entry, Insts); } else { addOIRegion(Entry, {{Entry, 0}}); } } // If doing whole compilation, merge all regions in one if (IsToDoWholeCompilation) { OIInstList OIAll; std::set<uint32_t> UniqInsts; for (auto OIR : OIRegions) { for (auto I : OIR.second) { if (UniqInsts.count(I[0]) == 0) OIAll.push_back({I[0], I[1]}); UniqInsts.insert(I[0]); } } OIRegionsMtx.lock(); std::sort(OIAll.begin(), OIAll.end(), compInst); OIRegions.clear(); OIRegions[0] = OIAll; OIRegionsKey.insert(OIRegionsKey.begin(), 0); NumOfOIRegions = 1; cv.notify_all(); OIRegionsMtx.unlock(); } } static unsigned int ModuleId = 0; void Manager::runPipeline() { if (!IRE) { llvm::InitializeNativeTarget(); llvm::InitializeNativeTargetAsmPrinter(); llvm::InitializeNativeTargetAsmParser(); IRJIT = llvm::make_unique<llvm::orc::IRJIT>(); } PerfMapFile = new std::ofstream("/tmp/perf-"+std::to_string(getpid())+".map"); IRE = llvm::make_unique<IREmitter>(); IRO = llvm::make_unique<IROpt>(); while (isRunning) { uint32_t EntryAddress; OIInstList OIRegion; std::unique_lock<std::mutex> lk(NR); cv.wait(lk, [&]{ return getNumOfOIRegions() != 0; }); OIRegionsMtx.lock_shared(); EntryAddress = OIRegionsKey.front(); OIRegion = OIRegions[EntryAddress]; OIRegionsMtx.unlock_shared(); llvm::Module* Module = nullptr; unsigned Size = 1; unsigned OSize = 1; if (OIRegion.size() == 0) continue; if (IsToLoadRegions && IsToLoadBCFormat) Module = loadRegionFromFile("r"+std::to_string(EntryAddress)+".bc"); std::vector<uint32_t> EntryAddresses = {EntryAddress}; if (Module == nullptr) { if (!isRunning) return; CompiledOIRegionsMtx.lock(); CompiledOIRegions[EntryAddress] = OIRegion; CompiledOIRegionsMtx.unlock(); if (VerboseOutput) std::cerr << "Trying to compile: " << std::hex << EntryAddress << "..."; if (VerboseOutput) { std::cerr << "---------------------- Printing OIRegion (OpenISA instr.) --------------------" << std::endl; for (auto Pair : OIRegion) std::cerr << std::hex << Pair[0] << ":\t" << dbt::OIPrinter::getString(OIDecoder::decode(Pair[1])) << "\n"; std::cerr << "\n" << std::endl; } OICompiled += OIRegion.size(); Module = new llvm::Module(std::to_string(++ModuleId), TheContext); if (IsToDoWholeCompilation) { OIRegionsKey.erase(OIRegionsKey.begin()); EntryAddresses = OIRegionsKey; } if (VerboseOutput) std::cerr << "Generating IR for: " << std::hex << EntryAddress << "..."; IRE->generateRegionIR(EntryAddresses, OIRegion, DataMemOffset, TheMachine, IRJIT->getTargetMachine(), NativeRegions, Module); if (VerboseOutput) std::cerr << "OK" << std::endl; for (auto& F : *Module) for (auto& BB : F) Size += BB.size(); if (!isRunning) return; if (OptMode != OptPolitic::Custom) IRO->optimizeIRFunction(Module, IROpt::OptLevel::Basic, EntryAddress, 1, TheMachine.getBinPath()); else if (CustomOpts->count(EntryAddress) != 0) IRO->customOptimizeIRFunction(Module, (*CustomOpts)[EntryAddress]); if (VerboseOutput) Module->print(llvm::errs(), nullptr); for (auto& F : *Module) for (auto& BB : F) OSize += BB.size(); } // Remove a region if the first instruction is a return <- can cause infinity loops llvm::Function* LLVMRegion = Module->getFunction("r"+std::to_string(EntryAddress)); if (LLVMRegion == nullptr) { std::cerr << "Module->getFunction has returned empty!\n"; exit(1); } auto Inst = LLVMRegion->getEntryBlock().getFirstNonPHI(); bool IsRet = Inst->getOpcode() == llvm::Instruction::Ret; bool RetLoop = true; if (IsRet) { auto RetInst = llvm::dyn_cast<llvm::ReturnInst>(Inst); if (llvm::isa<llvm::ConstantInt>(RetInst->getReturnValue())) if (!llvm::dyn_cast<llvm::ConstantInt>(RetInst->getReturnValue())->equalsInt(EntryAddress)) RetLoop = false; } if (!IsRet || !RetLoop) { if (!isRunning) return; IRRegions[EntryAddress] = llvm::CloneModule(*Module).release(); IRRegionsKey.push_back(EntryAddress); NativeRegionsMtx.lock(); IRJIT->addModule(std::unique_ptr<llvm::Module>(Module)); if (VerboseOutput) llvm::errs() << ".. we've compiled (" << (float) OSize/Size << ")\n"; CompiledRegions += 1; LLVMCompiled += OSize; AvgOptCodeSize += (float) OSize/Size; auto Addr = IRJIT->findSymbol("r"+std::to_string(EntryAddress)).getAddress(); *PerfMapFile << std::hex << "0x" << *Addr << std::dec <<" " << IREmitter::getAssemblySize((const void*) *Addr) << " r" << EntryAddress << ".oi\n"; PerfMapFile->flush(); if (Addr) { for (auto EA : EntryAddresses) if (EA < NATIVE_REGION_SIZE) { NativeRegions[EA] = static_cast<intptr_t>(*Addr); } else { std::cerr << EntryAddress << " is out of NativeRegion entries range!\n"; } } else { std::cerr << EntryAddress << " was not successfully compiled!\n"; } NativeRegionsMtx.unlock(); if (VerboseOutput) { std::cerr << "Disassembly of Region: " << EntryAddress << ":" << std::endl; std::ostringstream buffer; size_t t = IREmitter::disassemble((const void*) *Addr, buffer); std::cerr << buffer.str().c_str() << std::endl; buffer.clear(); buffer.str(""); std::cerr << "Dumping Region: " << EntryAddress << ":" << std::endl; IREmitter::regionDump((const void*) *Addr, buffer, t); std::cerr << buffer.str().c_str() << std::endl; } } else if (VerboseOutput) { std::cerr << "Giving up " << std::hex << EntryAddress << " compilation as it starts with a return!\n"; delete Module; } OIRegionsMtx.lock(); OIRegions.erase(EntryAddress); NumOfOIRegions -= 1; OIRegionsKey.erase(OIRegionsKey.begin()); OIRegionsMtx.unlock(); if (IsToDoWholeCompilation) { isFinished = true; return; } } PerfMapFile->close(); isFinished = true; } bool Manager::addOIRegion(uint32_t EntryAddress, OIInstList OIRegion) { if (!isRegionEntry(EntryAddress) && OIRegions.count(EntryAddress) == 0) { OIRegionsMtx.lock(); OIRegionsKey.push_back(EntryAddress); OIRegions[EntryAddress] = OIRegion; OIRegionsMtx.unlock(); NumOfOIRegions += 1; cv.notify_all(); return true; } return false; } int32_t Manager::jumpToRegion(uint32_t EntryAddress) { uint32_t JumpTo = EntryAddress; int32_t* RegPtr = TheMachine.getRegisterPtr(); uint32_t* MemPtr = TheMachine.getMemoryPtr(); while (isNativeRegionEntry(JumpTo)) { JumpTo = ((uint32_t (*)(int32_t*, uint32_t*, uint32_t)) NativeRegions[JumpTo])(RegPtr, MemPtr, EntryAddress); } return JumpTo; } void Manager::reset() { while (NumOfOIRegions != 0); OIRegionsKey.clear(); OIRegions.clear(); CompiledOIRegions.clear(); TouchedEntries.clear(); NumOfOIRegions = 0; for (auto P : IRRegions) delete P.second; IRRegions.clear(); for (unsigned I = 0; I < NATIVE_REGION_SIZE; I++) NativeRegions[I] = 0; }
30.138983
152
0.613204
[ "vector" ]
7097b170d264179cc63a3de0e8493801872bbb1f
2,923
cpp
C++
src/main.cpp
laurencee9/GRGImage
5ed00d7b43a06aede1d980df669b8e7cfe258921
[ "MIT" ]
4
2018-03-28T22:48:00.000Z
2018-05-15T15:16:54.000Z
src/main.cpp
laurencee9/GRGImage
5ed00d7b43a06aede1d980df669b8e7cfe258921
[ "MIT" ]
null
null
null
src/main.cpp
laurencee9/GRGImage
5ed00d7b43a06aede1d980df669b8e7cfe258921
[ "MIT" ]
null
null
null
#define cimg_display 0 #include "CImg.h" #include "main.hpp" #include "grg.cpp" using namespace cimg_library; namespace po = boost::program_options; int main(int argc, char const *argv[]) { // Parameters int number_nodes, degree, neigh; double contrast; std::string imagePath, outputPath; bool transform=false; bool displayGray=false; bool GNU = false; bool CSV = false; po::options_description description("Options"); description.add_options() ("imagePath,i", po::value<std::string>(&imagePath),"Path to the image") ("outputPath,o", po::value<std::string>(&outputPath),"Path to the output file") ("number_nodes,N", po::value<int>(&number_nodes)->default_value(1000),"Number of nodes that will populate the image") ("degree,d", po::value<int>(&degree)->default_value(3),"Maximum degree of a node") ("contrast", po::value<double>(&contrast)->default_value(1.0),"Contrast parameter") ("neigh,n", po::value<int>(&neigh)->default_value(50),"Paramter controlling the maximum number of neighbor pixel that a node can connect to") ("help", "Get help") ("transform", "Transform the image to a network") ("displayGray", "Display the gray image used for geometry") ("CSV", "Save in csv format for d3.js") ("GNU", "Save in Gnuplot format"); po::variables_map var_map; po::store(po::parse_command_line(argc,argv,description), var_map); po::notify(var_map); if (var_map.count("help")>0 ) { std::clog << description; return EXIT_SUCCESS; } if (var_map.count("transform")>0){ transform = true; } if (var_map.count("displayGray")>0){ displayGray = true; } if (var_map.count("CSV")>0){ CSV = true; } if (var_map.count("GNU")>0){ GNU = true; } if (transform){ // Load the image const char *const imagePathChar = imagePath.c_str(); CImg<unsigned char> src(imagePathChar); matrix<int> nodes(src.width(), src.height()); matrix<int> grayScale(src.width(), src.height()); // Get the matrix of intensity int total_intensity = getIntensity(src, grayScale, contrast, displayGray); // Place nodes on spot int total_number_nodes = placeTheNodes(grayScale, nodes, (double)total_intensity, (double)number_nodes); std::clog<<"total_number_nodes: "<<total_number_nodes<<std::endl; // Add links matrix<int> edges(total_number_nodes*degree,4); int total_number_edges = addLinks(nodes, edges, degree, neigh); // Save network if (GNU){ saveNetworkGNU(src, edges, total_number_edges, outputPath+"_width"+std::to_string(src.width())+"_height"+std::to_string(src.height())+".dat"); } if (CSV){ saveNetworkCSV(src, edges, total_number_edges, outputPath+"_width"+std::to_string(src.width())+"_height"+std::to_string(src.height())+".csv"); } std::clog<<"total_number_edges: "<<total_number_edges<<std::endl; } return 0; }
27.064815
148
0.671228
[ "geometry", "transform" ]
70999db8eba5125aa6046a3a16b9804aa1c07eb8
2,913
cpp
C++
Doomenstein/Code/Game/MaterialSheet.cpp
yixuan-wei/Doomenstein
c1c80e5253a002d056b1990abf38e8c567c6e5ad
[ "MIT" ]
null
null
null
Doomenstein/Code/Game/MaterialSheet.cpp
yixuan-wei/Doomenstein
c1c80e5253a002d056b1990abf38e8c567c6e5ad
[ "MIT" ]
null
null
null
Doomenstein/Code/Game/MaterialSheet.cpp
yixuan-wei/Doomenstein
c1c80e5253a002d056b1990abf38e8c567c6e5ad
[ "MIT" ]
1
2021-03-12T01:23:26.000Z
2021-03-12T01:23:26.000Z
#include "Game/MaterialSheet.hpp" #include "Game/GameCommon.hpp" #include "Engine/Core/DevConsole.hpp" #include "Engine/Core/ErrorWarningAssert.hpp" #include "Engine/Renderer/RenderContext.hpp" #include "Engine/Renderer/SpriteSheet.hpp" #include "Engine/Math/AABB2.hpp" std::vector<MaterialSheet*> MaterialSheet::sMaterialSheets; ////////////////////////////////////////////////////////////////////////// void MaterialSheet::InitRenderAssets() { for (MaterialSheet* sheet : sMaterialSheets) { sheet->m_diffuseTex = g_theRenderer->CreateOrGetTextureFromFile(sheet->m_diffusePath.c_str()); //sprite sheet if (sheet->m_diffuseTex == nullptr) { g_theConsole->PrintError("fail to load diffuse texture, switch to White"); sheet->m_diffuseTex = g_theRenderer->CreateOrGetTextureFromFile("White"); } sheet->m_spriteSheet = new SpriteSheet(*sheet->m_diffuseTex, sheet->m_layout); } } ////////////////////////////////////////////////////////////////////////// MaterialSheet* MaterialSheet::GetMaterialSheetFromName(std::string const& name) { for (size_t i = 0; i < sMaterialSheets.size(); i++) { MaterialSheet* sheet = sMaterialSheets[i]; if (sheet->m_name == name) { return sheet; } } return nullptr; } ////////////////////////////////////////////////////////////////////////// MaterialSheet::MaterialSheet(XmlElement const& element) { m_name = ParseXmlAttribute(element, "name", ""); if (m_name.empty()) { g_theConsole->PrintError("MaterialSheet with NULL name"); return; } m_layout = ParseXmlAttribute(element, "layout", IntVec2(1,1)); XmlElement const* diffuse = element.FirstChildElement("Diffuse"); if (diffuse == nullptr) { g_theConsole->PrintError("MaterialSheet with no diffuse texture, set to white"); m_diffusePath = "White"; } else { m_diffusePath = ParseXmlAttribute(*diffuse, "image", "White"); if (diffuse->NextSiblingElement("Diffuse") != nullptr) { g_theConsole->PrintError(Stringf("Multiple Diffuse element in sheet %s", m_name.c_str())); } } MaterialSheet::sMaterialSheets.push_back(this); } ////////////////////////////////////////////////////////////////////////// AABB2 MaterialSheet::GetSpriteUVs(IntVec2 const& spriteCoords) const { if (spriteCoords.x < 0 || spriteCoords.x >= m_layout.x || spriteCoords.y < 0 || spriteCoords.y >= m_layout.y) { g_theConsole->PrintError(Stringf("Sprite Coords (%i, %i) invalid for MaterialSheet %s", spriteCoords.x, spriteCoords.y, m_name.c_str())); return AABB2(Vec2::ZERO, Vec2::ONE); } int index = spriteCoords.y*m_layout.x + spriteCoords.x; Vec2 uvMins, uvMaxs; m_spriteSheet->GetSpriteUVs(uvMins, uvMaxs, index); return AABB2(uvMins, uvMaxs); }
36.4125
102
0.599039
[ "vector" ]
709b5daf86c8067296f7b08af47a673de177de05
16,867
cp
C++
pipeLines/_legacy_archived/CD34.under_construction.cp
swvanderlaan/slideToolK
a07ecaaead93d49f44e649b3446c25117700b020
[ "MIT" ]
2
2021-01-19T07:45:53.000Z
2022-03-02T21:25:09.000Z
pipeLines/_legacy_archived/CD34.under_construction.cp
swvanderlaan/slideToolK
a07ecaaead93d49f44e649b3446c25117700b020
[ "MIT" ]
17
2021-08-31T11:42:25.000Z
2021-11-16T21:47:45.000Z
pipeLines/_legacy_archived/CD34.under_construction.cp
swvanderlaan/slideToolK
a07ecaaead93d49f44e649b3446c25117700b020
[ "MIT" ]
1
2021-05-04T10:16:00.000Z
2021-05-04T10:16:00.000Z
CellProfiler Pipeline: http://www.cellprofiler.org Version:1 SVNRevision:11710 LoadImages:[module_num:1|svn_version:\'Unknown\'|variable_revision_number:11|show_window:False|notes:\x5B\'1. Find Tissue area (green)\', \'2. Within Tissue area (green) Identify\x3A\', \' a. HE nuclei (blue)\', \' b. DAB area (yellow)\', \'3. Within DAB area (yellow) Identify\x3A\', \' a. DAB nuclei (red)\'\x5D] File type to be loaded:individual images File selection method:Text-Exact match Number of images in each group?:3 Type the text that the excluded images have in common:.counted Analyze all subfolders within the selected folder?:All Input image file location:Default Input Folder\x7CNone Check image sets for missing or duplicate files?:Yes Group images by metadata?:No Exclude certain files?:Yes Specify metadata fields to group by: Select subfolders to analyze: Image count:1 Text that these images have in common (case-sensitive):.tile.tissue.png Position of this image in each group:1 Extract metadata from where?:File name Regular expression that finds metadata in the file name:^(?P<NR>\x5B^.\x5D*)\\.(?P<STAIN>\x5B^.\x5D*).*\\.X(?P<X>\x5B0-9\x5D{1,4}).*\\.Y(?P<Y>\x5B0-9\x5D{1,4}) Type the regular expression that finds metadata in the subfolder path:.*\x5B\\\\/\x5D(?P<Date>.*)\x5B\\\\/\x5D(?P<Run>.*)$ Channel count:1 Group the movie frames?:No Grouping method:Interleaved Number of channels per group:3 Load the input as images or objects?:Images Name this loaded image:Original Name this loaded object:Nuclei Retain outlines of loaded objects?:No Name the outline image:NucleiOutlines Channel number:1 Rescale intensities?:Yes ColorToGray:[module_num:2|svn_version:\'Unknown\'|variable_revision_number:2|show_window:False|notes:\x5B\'Create gray channel, this is used to find tissue (green)\', \'Red is ussually a good channel for tissue.\', \'RGB should also be fine.\'\x5D] Select the input image:Original Conversion method:Combine Image type\x3A:Channels Name the output image:OriginalGray Relative weight of the red channel:1 Relative weight of the green channel:1 Relative weight of the blue channel:1 Convert red to gray?:Yes Name the output image:OrigRed Convert green to gray?:No Name the output image:OrigGreen Convert blue to gray?:No Name the output image:OrigBlue Channel count:1 Channel number\x3A:Red\x3A 1 Relative weight of the channel:1 Image name\x3A:Channel1 Morph:[module_num:3|svn_version:\'Unknown\'|variable_revision_number:2|show_window:False|notes:\x5B\'Invert created gray channel\'\x5D] Select the input image:OriginalGray Name the output image:Tissue_object Select the operation to perform:invert Number of times to repeat operation:Once Repetition number:2 Scale:3 UnmixColors:[module_num:4|svn_version:\'Unknown\'|variable_revision_number:2|show_window:False|notes:\x5B\'Split HE and DAB into separate channels\'\x5D] Stain count:2 Color image:Original Image name:Hematoxylin Stain:Hematoxylin Red absorbance:0.363092 Green absorbance:0.651435 Blue absorbance:0.666181 Image name:LPR Stain:Custom Red absorbance:0.0320406 Green absorbance:0.970037 Blue absorbance:0.240834 IdentifyPrimaryObjects:[module_num:5|svn_version:\'Unknown\'|variable_revision_number:8|show_window:False|notes:\x5B\x5D] Select the input image:Hematoxylin Name the primary objects to be identified:HE_object Typical diameter of objects, in pixel units (Min,Max):8,5000000 Discard objects outside the diameter range?:No Try to merge too small objects with nearby larger objects?:No Discard objects touching the border of the image?:No Select the thresholding method:Otsu Global Threshold correction factor:0 Lower and upper bounds on threshold:0.1,1.0 Approximate fraction of image covered by objects?:0.01 Method to distinguish clumped objects:None Method to draw dividing lines between clumped objects:Intensity Size of smoothing filter:10 Suppress local maxima that are closer than this minimum allowed distance:7 Speed up by using lower-resolution image to find local maxima?:Yes Name the outline image:HE_object_green Fill holes in identified objects?:Yes Automatically calculate size of smoothing filter?:Yes Automatically calculate minimum allowed distance between local maxima?:Yes Manual threshold:0.0 Select binary image:None Retain outlines of the identified objects?:Yes Automatically calculate the threshold using the Otsu method?:Yes Enter Laplacian of Gaussian threshold:0.5 Two-class or three-class thresholding?:Three classes Minimize the weighted variance or the entropy?:Weighted variance Assign pixels in the middle intensity class to the foreground or the background?:Foreground Automatically calculate the size of objects for the Laplacian of Gaussian filter?:Yes Enter LoG filter diameter:5 Handling of objects if excessive number of objects identified:Continue Maximum number of objects:500 Select the measurement to threshold with:None IdentifyPrimaryObjects:[module_num:6|svn_version:\'Unknown\'|variable_revision_number:8|show_window:False|notes:\x5B"Identify DAB positive area\'s (yellow)"\x5D] Select the input image:LPR Name the primary objects to be identified:LPR_object Typical diameter of objects, in pixel units (Min,Max):8,5000000 Discard objects outside the diameter range?:Yes Try to merge too small objects with nearby larger objects?:Yes Discard objects touching the border of the image?:No Select the thresholding method:Otsu Global Threshold correction factor:0 Lower and upper bounds on threshold:0.1,1.0 Approximate fraction of image covered by objects?:0.01 Method to distinguish clumped objects:None Method to draw dividing lines between clumped objects:Shape Size of smoothing filter:10 Suppress local maxima that are closer than this minimum allowed distance:7 Speed up by using lower-resolution image to find local maxima?:Yes Name the outline image:LPR_object_yellow Fill holes in identified objects?:Yes Automatically calculate size of smoothing filter?:Yes Automatically calculate minimum allowed distance between local maxima?:Yes Manual threshold:0.0 Select binary image:None Retain outlines of the identified objects?:Yes Automatically calculate the threshold using the Otsu method?:Yes Enter Laplacian of Gaussian threshold:0.5 Two-class or three-class thresholding?:Three classes Minimize the weighted variance or the entropy?:Weighted variance Assign pixels in the middle intensity class to the foreground or the background?:Foreground Automatically calculate the size of objects for the Laplacian of Gaussian filter?:Yes Enter LoG filter diameter:5 Handling of objects if excessive number of objects identified:Continue Maximum number of objects:500 Select the measurement to threshold with:None MaskImage:[module_num:7|svn_version:\'Unknown\'|variable_revision_number:3|show_window:False|notes:\x5B\'Only analyse Nuclei (red) in the previously defined DAB tissue (yellow)\'\x5D] Select the input image:LPR Name the output image:LPR_object_mask Use objects or an image as a mask?:Objects Select object for mask:LPR_object Select image for mask:DAB Invert the mask?:No MaskImage:[module_num:8|svn_version:\'Unknown\'|variable_revision_number:3|show_window:False|notes:\x5B\x5D] Select the input image:Hematoxylin Name the output image:HE_object_mask Use objects or an image as a mask?:Objects Select object for mask:HE_object Select image for mask:DAB Invert the mask?:No IdentifyPrimaryObjects:[module_num:9|svn_version:\'Unknown\'|variable_revision_number:8|show_window:False|notes:\x5B\'Find DAB positive nuclei (red) within masked image (green)\'\x5D] Select the input image:LPR_object_mask Name the primary objects to be identified:nuclei_LPR Typical diameter of objects, in pixel units (Min,Max):8,40 Discard objects outside the diameter range?:Yes Try to merge too small objects with nearby larger objects?:No Discard objects touching the border of the image?:No Select the thresholding method:Otsu Global Threshold correction factor:1 Lower and upper bounds on threshold:0.3,1.0 Approximate fraction of image covered by objects?:0.01 Method to distinguish clumped objects:Shape Method to draw dividing lines between clumped objects:Intensity Size of smoothing filter:10 Suppress local maxima that are closer than this minimum allowed distance:7 Speed up by using lower-resolution image to find local maxima?:Yes Name the outline image:nuclei_LPR_red Fill holes in identified objects?:Yes Automatically calculate size of smoothing filter?:Yes Automatically calculate minimum allowed distance between local maxima?:Yes Manual threshold:0.0 Select binary image:None Retain outlines of the identified objects?:Yes Automatically calculate the threshold using the Otsu method?:Yes Enter Laplacian of Gaussian threshold:0.5 Two-class or three-class thresholding?:Three classes Minimize the weighted variance or the entropy?:Entropy Assign pixels in the middle intensity class to the foreground or the background?:Foreground Automatically calculate the size of objects for the Laplacian of Gaussian filter?:Yes Enter LoG filter diameter:5 Handling of objects if excessive number of objects identified:Continue Maximum number of objects:500 Select the measurement to threshold with:None IdentifyPrimaryObjects:[module_num:10|svn_version:\'Unknown\'|variable_revision_number:8|show_window:False|notes:\x5B\'Find HE positive nuclei (blue) within masked image (green)\'\x5D] Select the input image:HE_object_mask Name the primary objects to be identified:nuclei_HE Typical diameter of objects, in pixel units (Min,Max):8,40 Discard objects outside the diameter range?:Yes Try to merge too small objects with nearby larger objects?:No Discard objects touching the border of the image?:No Select the thresholding method:Otsu Global Threshold correction factor:1 Lower and upper bounds on threshold:0.3,1.0 Approximate fraction of image covered by objects?:0.01 Method to distinguish clumped objects:Shape Method to draw dividing lines between clumped objects:Intensity Size of smoothing filter:10 Suppress local maxima that are closer than this minimum allowed distance:7 Speed up by using lower-resolution image to find local maxima?:Yes Name the outline image:nuclei_HE_blue Fill holes in identified objects?:Yes Automatically calculate size of smoothing filter?:Yes Automatically calculate minimum allowed distance between local maxima?:Yes Manual threshold:0.0 Select binary image:None Retain outlines of the identified objects?:Yes Automatically calculate the threshold using the Otsu method?:Yes Enter Laplacian of Gaussian threshold:0.5 Two-class or three-class thresholding?:Three classes Minimize the weighted variance or the entropy?:Entropy Assign pixels in the middle intensity class to the foreground or the background?:Foreground Automatically calculate the size of objects for the Laplacian of Gaussian filter?:Yes Enter LoG filter diameter:5 Handling of objects if excessive number of objects identified:Continue Maximum number of objects:500 Select the measurement to threshold with:None OverlayOutlines:[module_num:11|svn_version:\'Unknown\'|variable_revision_number:2|show_window:False|notes:\x5B\'The next outline is ontop of the previous one.\'\x5D] Display outlines on a blank image?:No Select image on which to display outlines:Original Name the output image:OrigOverlay Select outline display mode:Color Select method to determine brightness of outlines:Max of image Width of outlines:1 Select outlines to display:nuclei_HE_blue Select outline color:Blue Select outlines to display:LPR_object_yellow Select outline color:Yellow Select outlines to display:nuclei_LPR_red Select outline color:Red Select outlines to display:HE_object_green Select outline color:Green SaveImages:[module_num:12|svn_version:\'Unknown\'|variable_revision_number:7|show_window:False|notes:\x5B\'Save outlined images\', \'These image are usually not used for further analysis and can be stored in lossy JPEG if wanted.\'\x5D] Select the type of image to save:Image Select the image to save:OrigOverlay Select the objects to save:None Select the module display window to save:None Select method for constructing file names:From image filename Select image name for file prefix:Original Enter single file name:OrigBlue Do you want to add a suffix to the image file name?:Yes Text to append to the image name:.counted Select file format to use:png Output file location:Default Output Folder\x7CNone Image bit depth:8 Overwrite existing files without warning?:Yes Select how often to save:Every cycle Rescale the images? :No Save as grayscale or color image?:Grayscale Select colormap:Default Store file and path information to the saved image?:No Create subfolders in the output folder?:No MeasureImageAreaOccupied:[module_num:13|svn_version:\'Unknown\'|variable_revision_number:3|show_window:False|notes:\x5B\'Measure HE nuclei (blue) and DAB area (yellow) and red) area\'\x5D] Hidden:4 Measure the area occupied in a binary image, or in objects?:Binary Image Select objects to measure:None Retain a binary image of the object regions?:No Name the output binary image:Stain Select a binary image to measure:LPR_object_yellow Measure the area occupied in a binary image, or in objects?:Binary Image Select objects to measure:None Retain a binary image of the object regions?:No Name the output binary image:Stain Select a binary image to measure:nuclei_LPR_red Measure the area occupied in a binary image, or in objects?:Binary Image Select objects to measure:None Retain a binary image of the object regions?:No Name the output binary image:Stain Select a binary image to measure:nuclei_HE_blue Measure the area occupied in a binary image, or in objects?:Binary Image Select objects to measure:None Retain a binary image of the object regions?:No Name the output binary image:Stain Select a binary image to measure:HE_object_green ExportToDatabase:[module_num:14|svn_version:\'Unknown\'|variable_revision_number:20|show_window:False|notes:\x5B\'Export findings to database for further analysis\'\x5D] Database type:MySQL / CSV Database name:CellProfiler Add a prefix to table names?:No Table prefix: SQL file prefix:SQL_ Output file location:Default Output Folder\x7CNone Create a CellProfiler Analyst properties file?:No Database host:localhost Username:cp Password:Count! Name the SQLite database file:DefaultDB.db Calculate the per-image mean values of object measurements?:Yes Calculate the per-image median values of object measurements?:Yes Calculate the per-image standard deviation values of object measurements?:Yes Calculate the per-well mean values of object measurements?:Yes Calculate the per-well median values of object measurements?:Yes Calculate the per-well standard deviation values of object measurements?:Yes Export measurements for all objects to the database?:All Select the objects: Maximum # of characters in a column name:64 Create one table per object or a single object table?:Single object table Enter an image url prepend if you plan to access your files via http: Write image thumbnails directly to the database?:No Select the images you want to save thumbnails of: Auto-scale thumbnail pixel intensities?:Yes Select the plate type:None Select the plate metadata:None Select the well metadata:None Include information for all images, using default values?:No Hidden:1 Hidden:1 Hidden:0 Select an image to include:None Use the image name for the display?:No Image name:Channel1 Channel color:red Do you want to add group fields?:No Enter the name of the group: Enter the per-image columns which define the group, separated by commas:ImageNumber, Image_Metadata_Plate, Image_Metadata_Well Do you want to add filter fields?:No Automatically create a filter for each plate?:No
51.112121
314
0.760657
[ "object", "shape" ]
709dcc0e2ed3095da69c66c1ea1421b2a028bc94
12,061
hpp
C++
io/src/_key_value_serializer_common.hpp
vinders/pandora_toolbox
f32e301ebaa2b281a1ffc3d6d0c556091420520a
[ "MIT" ]
2
2020-11-19T03:23:35.000Z
2021-02-25T03:34:40.000Z
io/src/_key_value_serializer_common.hpp
vinders/pandora_toolbox
f32e301ebaa2b281a1ffc3d6d0c556091420520a
[ "MIT" ]
null
null
null
io/src/_key_value_serializer_common.hpp
vinders/pandora_toolbox
f32e301ebaa2b281a1ffc3d6d0c556091420520a
[ "MIT" ]
null
null
null
/******************************************************************************* MIT License Copyright (c) 2021 Romain Vinders 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 SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO 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. -------------------------------------------------------------------------------- Implementation included in key_value_serializer.cpp (grouped object improves compiler optimizations + reduces executable size) *******************************************************************************/ // includes: in key_value_serializer.cpp // -- text serialization helpers -- -------------------------------------------- // copy text value between quotes + escape quote characters (single-line) -- all text values / JSON keys void pandora::io::_copyEscapedTextInQuotes(const char* text, std::string& outBuffer) { outBuffer += '"'; if (text != nullptr) { const char* partBegin = text; for (const char* it = text; *it; ++it) { if ( *it == '"' || *it == '\\' || (unsigned char)*it < (unsigned char)0x20u) { if (it > partBegin) // don't add empty parts outBuffer += std::string(partBegin, it - partBegin); if ((unsigned char)*it >= (unsigned char)0x20u) { // value not skipped outBuffer += '\\'; outBuffer += *it; } else { switch (*it) { case '\n': outBuffer += '\\'; outBuffer += 'n'; break; case '\r': outBuffer += '\\'; outBuffer += 'r'; break; case '\a': outBuffer += '\\'; outBuffer += 'a'; break; case '\t': outBuffer += '\t'; break; default: break; } } partBegin = it + 1; } } if (*partBegin) outBuffer += partBegin; } outBuffer += '"'; } // --- // copy comment value behing prefix (mult-line allowed) void pandora::io::_copyComment(const char* comment, bool isInline, const char* commentPrefix, const std::string& indent, std::string& outBuffer) { if (comment == nullptr || *comment == 0) return; if (isInline) outBuffer += ' '; // add space between text and comment const char* lineBegin = comment; for (const char* it = comment; *it; ++it) { if (*it == '\n') { uint32_t skippedLastChar = (it > comment && *(it - 1) == '\r') ? 1 : 0; // remove CR before LF if (it - skippedLastChar > lineBegin) { // don't add empty lines if (lineBegin > comment) outBuffer += indent; outBuffer += commentPrefix; outBuffer += std::string(lineBegin, it - lineBegin - skippedLastChar); outBuffer += '\n'; } lineBegin = it + 1; } } if (*lineBegin) { if (lineBegin > comment) outBuffer += indent; outBuffer += commentPrefix; outBuffer += lineBegin; } } // -- number/bool deserialization helpers -- ----------------------------------- // read boolean value from serialized data const char* pandora::io::_readBoolean(const char* serialized, bool& outValue) noexcept { if (*serialized == 't') { if (*(++serialized) == 'r' && *(++serialized) == 'u' && *(++serialized) == 'e') { outValue = true; return serialized; } } else if (*serialized == 'f') { if (*(++serialized) == 'a' && *(++serialized) == 'l' && *(++serialized) == 's' && *(++serialized) == 'e') { outValue = false; return serialized; } } return nullptr; } // read number value from serialized data const char* pandora::io::_readNumber(const char* serialized, __Number& outValue, bool& outIsInteger) noexcept { bool isDecimalFound = false; bool isPositive = true; uint64_t integer = 0; uint64_t decimals = 0; uint64_t decimalWeight = 1uLL; const char* it = serialized; if (*it == '-') { isPositive = false; ++it; } else if (*it == '+') ++it; while (*it) { if (*it >= '0' && *it <= '9') { if (isDecimalFound) { decimals *= 10uLL; decimals += static_cast<uint64_t>(*it) - (uint64_t)'0'; decimalWeight *= 10uLL; } else { integer *= 10uLL; integer += static_cast<uint64_t>(*it) - (uint64_t)'0'; } } else if (*it == '.') { if (isDecimalFound) // already found -> end of number break; isDecimalFound = true; } else // other symbol -> end of number break; ++it; } outIsInteger = !isDecimalFound; if (outIsInteger) outValue.integer = isPositive ? static_cast<int32_t>(integer) : -static_cast<int32_t>(integer); else outValue.number = isPositive ? static_cast<double>(integer) + (double)decimals/(double)decimalWeight : -static_cast<double>(integer) - (double)decimals/(double)decimalWeight; return (it > serialized) ? --it : serialized; } // -- text deserialization helpers -- ------------------------------------------ // read escaped unicode character + encode it (UTF-8) static const char* __readUnicodeCharacter(const char* serialized, size_t minDigits, size_t maxDigits, char** buffer, size_t& inOutCurrentSize) { // get character code size_t codeLength = 0; uint32_t charCode = 0; for (const char* it = serialized + 1; codeLength < maxDigits; ++it, ++codeLength) { if (*it >= '0' && *it <= '9') { charCode <<= 4; charCode |= static_cast<uint32_t>(*it - '0'); } else if (*it >= 'A' && *it <= 'F') { charCode <<= 4; charCode |= static_cast<uint32_t>(*it + 10 - 'A'); } else if (*it >= 'a' && *it <= 'f') { charCode <<= 4; charCode |= static_cast<uint32_t>(*it + 10 - 'a'); } else // not hex code character break; } // invalid character code -> just copy initial character and do not affect position if (codeLength < minDigits) { *(*buffer) = *serialized; return serialized; } // convert char code to encoded data size_t charLength = pandora::io::Encoder::Utf8::encode(charCode, *buffer); assert(charLength > 0); --charLength; // compensate the fact that 'buffer' and 'inOutCurrentSize' will be incremented by caller *buffer += charLength; inOutCurrentSize += charLength; return serialized + codeLength; } // --- // read text between quotes + restore escaped characters -- text values/keys const char* pandora::io::_readText(const char* serialized, char** outValue, size_t& outSize) { char endSymbol = *serialized; ++serialized; size_t bufferSize = 64; char* buffer = (char*)malloc(bufferSize*sizeof(char)); char* bufferIt = buffer; if (buffer == nullptr) throw std::bad_alloc(); size_t currentSize = 0; while (*serialized) { // end of string if (*serialized == endSymbol) { // resize buffer to fit actual string *bufferIt = (char)0; if (currentSize + 1 < bufferSize) { if (currentSize > 0) { buffer = (char*)realloc(buffer, currentSize + 1); assert(buffer != nullptr); } else { free(buffer); buffer = nullptr; } } // output value outSize = currentSize; *outValue = buffer; return serialized; } if (*serialized == '\\') { if (*(++serialized) == 0) break; switch (*serialized) { case 'n': *bufferIt = '\n'; break; case 'r': *bufferIt = '\r'; break; case 't': *bufferIt = '\t'; break; case 'b': *bufferIt = '\b'; break; case 'a': *bufferIt = '\a'; break; case '0': *bufferIt = '\0'; break; case 'x': serialized = __readUnicodeCharacter(serialized, size_t{1u},size_t{4u}, &bufferIt, currentSize); break; case 'u': serialized = __readUnicodeCharacter(serialized, size_t{4u},size_t{4u}, &bufferIt, currentSize); break; case 'U': serialized = __readUnicodeCharacter(serialized, size_t{8u},size_t{8u}, &bufferIt, currentSize); break; default: *bufferIt = *serialized; break; } } else *bufferIt = *serialized; ++serialized; // adjust buffer size if needed ++currentSize; if (currentSize + _P_UTF8_MAX_CODE_SIZE >= bufferSize) { // enough slots for next iteration: char / ending / UTF-8 code bufferSize = bufferSize << 1; char* newBuffer = (char*)realloc(buffer, bufferSize); if (newBuffer == nullptr) { free(buffer); // if failed, old block still exists throw std::bad_alloc(); } buffer = newBuffer; bufferIt = &buffer[currentSize]; } else ++bufferIt; } // failure -> release buffer free(buffer); return nullptr; } // read text + restore escaped characters -- text values/keys const char* pandora::io::_readText(const char* serialized, char** outValue, size_t& outSize, bool allowEndOfData, char endSymbol1, char endSymbol2, char endSymbol3) { if (endSymbol2 == (char)-1) endSymbol2 = endSymbol1; if (endSymbol3 == (char)-1) endSymbol3 = endSymbol1; size_t bufferSize = 64; char* buffer = (char*)malloc(bufferSize*sizeof(char)); char* bufferIt = buffer; if (buffer == nullptr) throw std::bad_alloc(); size_t currentSize = 0; while (*serialized) { // end of string if (*serialized == endSymbol1 || *serialized == endSymbol2 || *serialized == endSymbol3) { if (currentSize == 0) { free(buffer); buffer = nullptr; } else *bufferIt = (char)0; outSize = currentSize; // no buffer resize: value must be trimmed -> too big anyway *outValue = buffer; return serialized; } if (*serialized == '\\') { if (*(++serialized) == 0) break; switch (*serialized) { case 'n': *bufferIt = '\n'; break; case 'r': *bufferIt = '\r'; break; case 't': *bufferIt = '\t'; break; case 'b': *bufferIt = '\b'; break; case 'a': *bufferIt = '\a'; break; case '0': *bufferIt = '\0'; break; case 'x': serialized = __readUnicodeCharacter(serialized, size_t{1u},size_t{4u}, &bufferIt, currentSize); break; case 'u': serialized = __readUnicodeCharacter(serialized, size_t{4u},size_t{4u}, &bufferIt, currentSize); break; case 'U': serialized = __readUnicodeCharacter(serialized, size_t{8u},size_t{8u}, &bufferIt, currentSize); break; default: *bufferIt = *serialized; break; } } else *bufferIt = *serialized; ++serialized; // adjust buffer size if needed ++currentSize; if (currentSize + _P_UTF8_MAX_CODE_SIZE >= bufferSize) { // enough slots for next iteration: char / ending / UTF-8 code bufferSize = bufferSize << 1; char* newBuffer = (char*)realloc(buffer, bufferSize); if (newBuffer == nullptr) { free(buffer); // if failed, old block still exists throw std::bad_alloc(); } buffer = newBuffer; bufferIt = &buffer[currentSize]; } else ++bufferIt; } if (!allowEndOfData) { // failure -> release buffer free(buffer); return nullptr; } else { if (currentSize == 0) { free(buffer); buffer = nullptr; } else *bufferIt = (char)0; outSize = currentSize; *outValue = buffer; return serialized; } }
33.689944
146
0.581875
[ "object" ]
709e51eb2ece92d14c3310b948f46972338e279d
6,932
cpp
C++
OverlordEngine/MeshFilter.cpp
Kair0z/StikBoldt-PC
5d978aa6b67e9f3a140136f2f0b766061e765c74
[ "MIT" ]
null
null
null
OverlordEngine/MeshFilter.cpp
Kair0z/StikBoldt-PC
5d978aa6b67e9f3a140136f2f0b766061e765c74
[ "MIT" ]
null
null
null
OverlordEngine/MeshFilter.cpp
Kair0z/StikBoldt-PC
5d978aa6b67e9f3a140136f2f0b766061e765c74
[ "MIT" ]
1
2021-09-23T06:21:53.000Z
2021-09-23T06:21:53.000Z
#include "stdafx.h" #include "MeshFilter.h" #include "Material.h" #include <algorithm> DirectX::XMFLOAT4 MeshFilter::m_DefaultColor = DirectX::XMFLOAT4(1,0,0,1); DirectX::XMFLOAT4 MeshFilter::m_DefaultFloat4 = DirectX::XMFLOAT4(0, 0, 0, 0); DirectX::XMFLOAT3 MeshFilter::m_DefaultFloat3 = DirectX::XMFLOAT3(0, 0, 0); DirectX::XMFLOAT2 MeshFilter::m_DefaultFloat2 = DirectX::XMFLOAT2(0, 0); MeshFilter::MeshFilter(): m_Positions(std::vector<DirectX::XMFLOAT3>()), m_Normals(std::vector<DirectX::XMFLOAT3>()), m_Tangents(std::vector<DirectX::XMFLOAT3>()), m_Binormals(std::vector<DirectX::XMFLOAT3>()), m_TexCoords(std::vector<DirectX::XMFLOAT2>()), m_Colors(std::vector<DirectX::XMFLOAT4>()), m_Indices(std::vector<DWORD>()), m_BlendIndices(std::vector<DirectX::XMFLOAT4>()), m_BlendWeights(std::vector<DirectX::XMFLOAT4>()), m_AnimationClips(std::vector<AnimationClip>()), m_pIndexBuffer(nullptr), m_VertexBuffers(std::vector<VertexBufferData>()), m_VertexCount(0), m_IndexCount(0), m_TexCoordCount(0), m_HasElement(static_cast<UINT>(ILSemantic::NONE)), m_HasAnimations(false), m_BoneCount(0) { } MeshFilter::~MeshFilter() { m_Positions.clear(); m_Normals.clear(); m_TexCoords.clear(); m_Colors.clear(); m_Indices.clear(); m_Tangents.clear(); m_Binormals.clear(); m_BlendIndices.clear(); m_BlendWeights.clear(); m_AnimationClips.clear(); for_each(m_VertexBuffers.begin(), m_VertexBuffers.end(), [](VertexBufferData& data) { data.Destroy(); }); m_VertexBuffers.clear(); SafeRelease(m_pIndexBuffer); } void MeshFilter::BuildIndexBuffer(const GameContext& gameContext) { if (m_pIndexBuffer != nullptr) return; D3D11_BUFFER_DESC bd = {}; bd.Usage = D3D11_USAGE_IMMUTABLE; bd.ByteWidth = sizeof(DWORD) * m_Indices.size(); bd.BindFlags = D3D11_BIND_INDEX_BUFFER; bd.CPUAccessFlags = 0; bd.MiscFlags = 0; D3D11_SUBRESOURCE_DATA initData; initData.pSysMem = m_Indices.data(); auto hr = gameContext.pDevice->CreateBuffer(&bd, &initData, &m_pIndexBuffer); Logger::LogHResult(hr, L"MeshFilter::BuildIndexBuffer()"); } int MeshFilter::GetVertexBufferId(UINT inputLayoutId) { for (UINT i = 0; i<m_VertexBuffers.size(); ++i) { if (m_VertexBuffers[i].InputLayoutID == inputLayoutId) return i; } return -1; } void MeshFilter::BuildVertexBuffer(const GameContext& gameContext, Material* pMaterial) { BuildVertexBuffer(gameContext, pMaterial->m_InputLayoutID, pMaterial->m_pInputLayoutSize, pMaterial->m_pInputLayoutDescriptions); } void MeshFilter::BuildVertexBuffer(const GameContext& gameContext, UINT inputLayoutID, UINT inputLayoutSize, const std::vector<ILDescription>& inputLayoutDescriptions) { //Check if VertexBufferInfo already exists with requested InputLayout if (GetVertexBufferId(inputLayoutID) >= 0) return; VertexBufferData data; data.VertexStride = inputLayoutSize; data.VertexCount = m_VertexCount; data.BufferSize = data.VertexStride * m_VertexCount; data.IndexCount = m_IndexCount; void *pDataLocation = malloc(data.BufferSize); if (pDataLocation == nullptr) { Logger::LogWarning(L"MeshFilter::BuildVertexBuffer() > Failed to allocate the required memory!"); return; } data.pDataStart = pDataLocation; data.InputLayoutID = inputLayoutID; for (UINT i = 0; i < m_VertexCount; ++i) { for (UINT j = 0; j < inputLayoutDescriptions.size(); ++j) { auto ilDescription = inputLayoutDescriptions[j]; if (i == 0 && !HasElement(ilDescription.SemanticType)) { std::wstring name = EffectHelper::GetIlSemanticName(ilDescription.SemanticType); Logger::LogFormat(LogLevel::Warning, L"MeshFilter::BuildVertexBuffer > Mesh \"%s\" has no vertex %s data, using a default value!", m_MeshName.c_str(), name.c_str()); } switch (ilDescription.SemanticType) { case ILSemantic::POSITION: memcpy(pDataLocation, HasElement(ilDescription.SemanticType)?&m_Positions[i]:&m_DefaultFloat3, ilDescription.Offset); break; case ILSemantic::NORMAL: memcpy(pDataLocation, HasElement(ilDescription.SemanticType) ? &m_Normals[i] : &m_DefaultFloat3, ilDescription.Offset); break; case ILSemantic::COLOR: memcpy(pDataLocation, HasElement(ilDescription.SemanticType) ? &m_Colors[i] : &m_DefaultColor, ilDescription.Offset); break; case ILSemantic::TEXCOORD: memcpy(pDataLocation, HasElement(ilDescription.SemanticType) ? &m_TexCoords[i] : &m_DefaultFloat2, ilDescription.Offset); break; case ILSemantic::TANGENT: memcpy(pDataLocation, HasElement(ilDescription.SemanticType) ? &m_Tangents[i] : &m_DefaultFloat3, ilDescription.Offset); break; case ILSemantic::BINORMAL: memcpy(pDataLocation, HasElement(ilDescription.SemanticType) ? &m_Binormals[i] : &m_DefaultFloat3, ilDescription.Offset); break; case ILSemantic::BLENDINDICES: memcpy(pDataLocation, HasElement(ilDescription.SemanticType) ? &m_BlendIndices[i] : &m_DefaultFloat4, ilDescription.Offset); break; case ILSemantic::BLENDWEIGHTS: memcpy(pDataLocation, HasElement(ilDescription.SemanticType) ? &m_BlendWeights[i] : &m_DefaultFloat4, ilDescription.Offset); break; default: Logger::LogError(L"MeshFilter::BuildVertexBuffer() > Unsupported SemanticType!"); break; } pDataLocation = (char *) pDataLocation + ilDescription.Offset; } } //fill a buffer description to copy the vertexdata into graphics memory D3D11_BUFFER_DESC bd = {}; bd.Usage = D3D11_USAGE_DEFAULT; bd.ByteWidth = data.BufferSize; bd.BindFlags = D3D11_BIND_VERTEX_BUFFER; bd.CPUAccessFlags = 0; bd.MiscFlags = 0; D3D11_SUBRESOURCE_DATA initData; initData.pSysMem = data.pDataStart; //create a ID3D10Buffer in graphics memory containing the vertex info gameContext.pDevice->CreateBuffer(&bd, &initData, &data.pVertexBuffer); m_VertexBuffers.push_back(data); } const VertexBufferData& MeshFilter::GetVertexBufferData(const GameContext& gameContext, Material* pMaterial) { int possibleBuffer = GetVertexBufferId(pMaterial->m_InputLayoutID); if (possibleBuffer < 0) { Logger::LogWarning(L"MeshFilter::GetVertexBufferInformation(...) => No VertexBufferInformation for this material found! Building matching VertexBufferInformation (Performance Issue)."); BuildVertexBuffer(gameContext, pMaterial); //Return last created vertexbufferinformation return m_VertexBuffers.back(); } return m_VertexBuffers[possibleBuffer]; } const VertexBufferData& MeshFilter::GetVertexBufferData(const GameContext& gameContext, UINT inputLayoutId) { UNREFERENCED_PARAMETER(gameContext); int possibleBuffer = GetVertexBufferId(inputLayoutId); if (possibleBuffer < 0) { Logger::LogError(L"MeshFilter::GetVertexBufferInformation(INPUTLAYOUT_ID) => No VertexBufferInformation for this InputLayoutID found! Initialize before retrieving."); //Return last created vertexbufferinformation return m_VertexBuffers.back(); } return m_VertexBuffers[possibleBuffer]; }
33.650485
187
0.755626
[ "mesh", "vector" ]
709fad5ba62b64736e47eb8c7e69eb15984b3bf3
14,362
cpp
C++
src/core/ActiveText.cpp
tedvalson/NovelTea
f731951f25936cb7f5ff23e543e0301c1b5bfe82
[ "MIT" ]
null
null
null
src/core/ActiveText.cpp
tedvalson/NovelTea
f731951f25936cb7f5ff23e543e0301c1b5bfe82
[ "MIT" ]
null
null
null
src/core/ActiveText.cpp
tedvalson/NovelTea
f731951f25936cb7f5ff23e543e0301c1b5bfe82
[ "MIT" ]
null
null
null
#include <NovelTea/ActiveText.hpp> #include <NovelTea/AssetManager.hpp> #include <NovelTea/Diff.hpp> #include <NovelTea/Game.hpp> #include <NovelTea/Object.hpp> #include <NovelTea/Room.hpp> #include <NovelTea/SaveData.hpp> #include <NovelTea/TextBlock.hpp> #include <NovelTea/TextFragment.hpp> namespace NovelTea { ActiveText::ActiveText() : m_size(1024.f, 1024.f) , m_lineSpacing(5.f) , m_alpha(255.f) , m_highlightFactor(1.f) , m_fontSizeMultiplier(1.f) , m_fadeAcrossPosition(1.f) , m_fadeLineIndex(0) , m_renderTexture(nullptr) { auto texture = AssetManager<sf::Texture>::get("images/fade.png"); texture->setSmooth(true); m_shape.setFillColor(sf::Color::Transparent); m_shapeFade.setTexture(texture.get(), true); m_shapeFade.setSize(sf::Vector2f(300.f, 40.f)); m_shapeFade.setOrigin(0.f, 40.f); m_shapeFade.setRotation(90.f); } void ActiveText::createRenderTexture() { m_shape.setSize(m_size); m_renderTexture = std::make_shared<sf::RenderTexture>(); m_renderTexture->create(m_size.x, 512); // TODO: Avoid fixed size m_sprite.setTexture(m_renderTexture->getTexture(), true); } void splitAndAppend(const std::string &text, const std::string &idName, std::vector<std::pair<std::string, std::string>> &pairs) { std::string buffer; for (auto &c : text) { if (c == ' ') { if (!buffer.empty()) pairs.emplace_back(buffer, idName); pairs.emplace_back("", ""); buffer.clear(); } else buffer += c; } if (!buffer.empty()) pairs.emplace_back(buffer, idName); } std::vector<std::pair<std::string, std::string>> getTextObjectPairs(const sf::String &s) { std::vector<std::pair<std::string, std::string>> v; size_t searchPos = 0, processedPos = 0, startPos; while ((startPos = s.find("[[", searchPos)) != sf::String::InvalidPos) { auto endPos = s.find("]]", startPos); auto midPos = s.find("|", startPos); if (endPos == sf::String::InvalidPos) break; // if there is no mid char "|" in between braces, skip it if (midPos == sf::String::InvalidPos || endPos < midPos) { searchPos = endPos + 2; continue; } auto idName = s.substring(midPos + 1, endPos - midPos - 1); auto text = s.substring(startPos + 2, midPos - startPos - 2); if (!GSave->exists<Object>(idName)) idName.clear(); if (startPos != processedPos) splitAndAppend(s.substring(processedPos, startPos - processedPos).toAnsiString(), "", v); splitAndAppend(text, idName, v); processedPos = searchPos = endPos + 2; } // Push remaining unprocessed string if (processedPos < s.getSize()) splitAndAppend(s.substring(processedPos), "", v); return v; } std::vector<std::pair<bool, std::string>> getNewTextPairs(const sf::String &s) { std::vector<std::pair<bool, std::string>> v; size_t searchPos = 0, processedPos = 0, startPos; while ((startPos = s.find("^[", searchPos)) != sf::String::InvalidPos) { auto endPos = s.find("]^", startPos); if (endPos == sf::String::InvalidPos) break; auto text = s.substring(startPos + 2, endPos - startPos - 2); if (startPos != processedPos) v.emplace_back(false, s.substring(processedPos, startPos - processedPos)); v.emplace_back(true, text); processedPos = searchPos = endPos + 2; } // Push remaining unprocessed string if (processedPos < s.getSize()) v.emplace_back(false, s.substring(processedPos)); return v; } json ActiveText::toJson() const { json j = sj::Array(); for (auto &block : m_textBlocks) j.append(block->toJson()); return j; } bool ActiveText::fromJson(const json &j) { m_textBlocks.clear(); m_needsUpdate = true; for (auto &jblock : j.ArrayRange()) { auto block = std::make_shared<TextBlock>(); if (block->fromJson(jblock)) m_textBlocks.push_back(block); } return true; } std::string ActiveText::toPlainText(const std::string &newline) const { std::string result; bool processedFirstBlock = false; for (auto &block : blocks()) { if (processedFirstBlock) result += newline; processedFirstBlock = true; for (auto &frag : block->fragments()) result += frag->getText(); } return result; } std::string ActiveText::objectFromPoint(const sf::Vector2f &point) const { for (auto &segment : m_segments) { if (!segment.objectIdName.empty()) { auto bounds = getTransform().transformRect(segment.bounds); if (bounds.contains(point)) return segment.objectIdName; } } return std::string(); } void ActiveText::setText(const std::string &text, const TextFormat &format) { m_textBlocks.clear(); auto lines = split(text); for (auto &line : lines) { auto block = std::make_shared<TextBlock>(); auto fragment = std::make_shared<TextFragment>(); fragment->setText(line); fragment->setTextFormat(format); block->addFragment(fragment); addBlock(block); } m_string = stripDiff(text); ensureUpdate(); } std::string ActiveText::getText() const { return m_string; } const std::vector<std::shared_ptr<TextBlock>> &ActiveText::blocks() const { return m_textBlocks; } void ActiveText::addBlock(std::shared_ptr<TextBlock> block, int index) { m_needsUpdate = true; m_string.clear(); if (index < 0) m_textBlocks.push_back(block); else m_textBlocks.insert(m_textBlocks.begin() + index, block); } void ActiveText::setSize(const sf::Vector2f &size) { m_needsUpdate = true; m_size = size; if (m_renderTexture) createRenderTexture(); } sf::Vector2f ActiveText::getSize() const { return m_size; } void ActiveText::setHighlightId(const std::string &id) { for (auto &segment : m_segments) { if (id.empty() || id != segment.objectIdName) { segment.text.setOutlineThickness(0.f); } else { segment.text.setOutlineColor(sf::Color(255, 255, 0, 140)); segment.text.setOutlineThickness(0.1f * segment.text.getCharacterSize()); } } } void ActiveText::refresh() { m_needsUpdate = true; } float ActiveText::getTextWidth() const { auto width = 0.f; for (auto &segment : m_segments) width += segment.text.getLocalBounds().width; return width; } sf::FloatRect ActiveText::getLocalBounds() const { ensureUpdate(); return m_bounds; } sf::FloatRect ActiveText::getGlobalBounds() const { ensureUpdate(); return getTransform().transformRect(m_bounds); } void ActiveText::setLineSpacing(float lineSpacing) { m_needsUpdate = true; m_lineSpacing = lineSpacing; } float ActiveText::getLineSpacing() const { return m_lineSpacing; } void ActiveText::setCursorStart(const sf::Vector2f &cursorPos) { m_needsUpdate = true; m_cursorStart = cursorPos; } const sf::Vector2f &ActiveText::getCursorEnd() const { ensureUpdate(); return m_cursorPos; } void ActiveText::setAlpha(float alpha) { m_alpha = alpha; applyAlpha(); } float ActiveText::getAlpha() const { return m_alpha; } void ActiveText::setHighlightFactor(float highlightFactor) { m_highlightFactor = highlightFactor; applyHighlightFactor(); } float ActiveText::getHighlightFactor() const { return m_highlightFactor; } void ActiveText::setFontSizeMultiplier(float fontSizeMultiplier) { m_needsUpdate = true; m_fontSizeMultiplier = fontSizeMultiplier; } float ActiveText::getFontSizeMultiplier() const { return m_fontSizeMultiplier; } void ActiveText::setFadeAcrossPosition(float position) { ensureUpdate(); m_fadeAcrossPosition = position; if (position == 1.f) { if (m_renderTexture) m_renderTexture = nullptr; } else { if (!m_renderTexture) createRenderTexture(); auto fadeLength = getFadeAcrossLength(); auto pos = m_fadeAcrossPosition * fadeLength; auto p = 0.f; m_fadeLineIndex = 0; for (auto &line : m_linePositions) { p += line.x + m_shapeFade.getSize().y; if (p > pos) { m_shape.setPosition(line.x - p + pos, line.y); m_shapeFade.setPosition(m_shape.getPosition()); m_shape.move(m_shapeFade.getSize().y, 0.f); break; } m_fadeLineIndex++; } } } float ActiveText::getFadeAcrossPosition() const { return m_fadeAcrossPosition; } float ActiveText::getFadeAcrossLength() const { ensureUpdate(); auto len = 0.f; for (auto &linePos : m_linePositions) len += linePos.x + m_shapeFade.getSize().y; return len; } std::vector<ActiveText::Segment> &ActiveText::getSegments() { ensureUpdate(); return m_segments; } void ActiveText::setValues(int tweenType, float *newValues) { switch (tweenType) { case HIGHLIGHTS: setHighlightFactor(newValues[0]); break; case FADEACROSS: setFadeAcrossPosition(newValues[0]); break; default: Hideable::setValues(tweenType, newValues); } } int ActiveText::getValues(int tweenType, float *returnValues) { switch (tweenType) { case HIGHLIGHTS: returnValues[0] = getHighlightFactor(); return 1; case FADEACROSS: returnValues[0] = getFadeAcrossPosition(); return 1; default: return Hideable::getValues(tweenType, returnValues); } } void ActiveText::applyAlpha() const { sf::Color color; const float *newValues = &m_alpha; // Hack for the macro below for (auto &segment : m_segments) { SET_ALPHA(segment.text.getFillColor, segment.text.setFillColor, 255.f); } } void ActiveText::applyHighlightFactor() const { for (auto &segment : m_segments) { if (!segment.objectIdName.empty()) { sf::Color color; if (segment.objectExists) color = sf::Color(0, 0, m_highlightFactor * 200, m_alpha); else color = sf::Color(m_highlightFactor * 155, 0, m_highlightFactor * 255, m_alpha); segment.text.setFillColor(color); } } } void ActiveText::draw(sf::RenderTarget &target, sf::RenderStates states) const { ensureUpdate(); if (m_segments.empty()) return; states.transform *= getTransform(); if (m_renderTexture) { auto posY = m_segments[0].text.getPosition().y; auto lineIndex = 0; m_renderTexture->clear(sf::Color::Transparent); for (auto &segment : m_segments) { auto p = segment.text.getPosition().y; if (p > posY) { posY = p; lineIndex++; } if (lineIndex == m_fadeLineIndex) m_renderTexture->draw(segment.text, sf::BlendNone); else if (lineIndex > m_fadeLineIndex) break; else target.draw(segment.text, states); } m_renderTexture->draw(m_shape, sf::BlendMultiply); m_renderTexture->draw(m_shapeFade, sf::BlendMultiply); m_renderTexture->display(); target.draw(m_sprite, states); } else { for (auto &segment : m_segments) target.draw(segment.text, states); } } void ActiveText::ensureUpdate() const { if (!m_needsUpdate) return; auto padding = 6.f; float lineHeight = 24.f; // TODO: Don't use fixed value auto processedFirstBlock = false; m_cursorPos = m_cursorStart; m_segments.clear(); m_linePositions.clear(); m_debugSegmentShapes.clear(); m_bounds = sf::FloatRect(0.f, m_cursorStart.y, m_cursorStart.x, m_cursorStart.y + lineHeight); for (auto &block : blocks()) { // Keep largest char size for current line auto lineMaxCharacterSize = 0u; auto &frags = block->fragments(); if (processedFirstBlock) // When '\n' is encountered { m_cursorPos.x = 0.f; m_cursorPos.y = m_bounds.height; if (!frags.empty() && frags[0]->getText().empty()) m_bounds.height += lineHeight + m_lineSpacing; } else processedFirstBlock = true; for (auto &frag : frags) { auto font = Proj.getFont(0); auto format = frag->getTextFormat(); sf::Uint32 style = sf::Text::Regular; if (format.bold()) style |= sf::Text::Bold; if (format.italic()) style |= sf::Text::Italic; if (format.underline()) style |= sf::Text::Underlined; sf::RectangleShape shape; shape.setFillColor(sf::Color(0, 0, 0, 30)); auto newTextPairs = getNewTextPairs(frag->getText()); for (auto &newTextPair : newTextPairs) { auto textObjectPairs = getTextObjectPairs(newTextPair.second); TweenText text; text.setFont(*font); text.setCharacterSize(2.f * m_fontSizeMultiplier * format.size()); text.setStyle(style); text.setString(" "); auto spaceWidth = text.getLocalBounds().width; for (auto &textObjectPair : textObjectPairs) { // Don't start line with a space if (textObjectPair.first.empty()) { if (m_cursorPos.x > 0) m_cursorPos.x += spaceWidth; continue; } auto string = textObjectPair.first; auto objectId = textObjectPair.second; auto objectExists = false; auto color = (newTextPair.first ? sf::Color(150, 0, 0) : format.color()); if (!objectId.empty()) { objectExists = ActiveGame->getRoom()->containsId(objectId) || ActiveGame->getObjectList()->containsId(objectId); } color.a = m_alpha; text.setString(string); text.setFillColor(color); lineMaxCharacterSize = std::max(lineMaxCharacterSize, text.getCharacterSize()); // Hack to prevent these chars from wrapping by themselves. const std::string specialChars = ".,!?"; auto isSpecialChar = (string.size() == 1 && specialChars.find(string) != specialChars.npos); auto newX = m_cursorPos.x + text.getLocalBounds().width; if (newX > m_size.x && m_cursorPos.x > 0.f && !isSpecialChar) { m_linePositions.push_back(m_cursorPos); m_cursorPos.x = 0.f; m_cursorPos.y += lineMaxCharacterSize + m_lineSpacing; lineMaxCharacterSize = text.getCharacterSize(); } text.setPosition(m_cursorPos); m_cursorPos.x += text.getLocalBounds().width; m_bounds.width = std::max(m_bounds.width, m_cursorPos.x); m_bounds.height = std::max(m_bounds.height, m_cursorPos.y + lineMaxCharacterSize + m_lineSpacing); auto bounds = sf::FloatRect( text.getGlobalBounds().left - padding, text.getGlobalBounds().top - padding, text.getLocalBounds().width + padding * 2, text.getLocalBounds().height + padding * 2); shape.setSize(sf::Vector2f(bounds.width, bounds.height)); shape.setPosition(bounds.left, bounds.top); m_debugSegmentShapes.push_back(shape); m_segments.push_back({objectExists, textObjectPair.second, text, bounds}); } } } m_linePositions.push_back(m_cursorPos); } applyAlpha(); applyHighlightFactor(); m_debugBorder.setFillColor(sf::Color::Transparent); m_debugBorder.setOutlineColor(sf::Color::Red); m_debugBorder.setOutlineThickness(2.f); m_debugBorder.setSize(sf::Vector2f(m_bounds.width, m_bounds.height - m_bounds.top)); m_debugBorder.setPosition(m_bounds.left, m_bounds.top); m_needsUpdate = false; } } // namespace NovelTea
23.976628
128
0.693497
[ "object", "shape", "vector", "transform" ]
70a042c5cb33947de303f20f5e992df0b3c97e22
3,687
cxx
C++
src/Cxx/PolyData/QuantizePolyDataPoints.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
81
2020-08-10T01:44:30.000Z
2022-03-23T06:46:36.000Z
src/Cxx/PolyData/QuantizePolyDataPoints.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
2
2020-09-12T17:33:52.000Z
2021-04-15T17:33:09.000Z
src/Cxx/PolyData/QuantizePolyDataPoints.cxx
ajpmaclean/vtk-examples
1a55fc8c6af67a3c07791807c7d1ec0ab97607a2
[ "Apache-2.0" ]
27
2020-08-17T07:09:30.000Z
2022-02-15T03:44:58.000Z
#include <vtkNew.h> #include <vtkProperty.h> #include <vtkQuantizePolyDataPoints.h> #include <vtkSmartPointer.h> #include <vtkCamera.h> #include <vtkGlyph3DMapper.h> #include <vtkPointSource.h> #include <vtkPoints.h> #include <vtkPolyData.h> #include <vtkPolyDataMapper.h> #include <vtkProperty.h> #include <vtkRenderWindow.h> #include <vtkRenderWindowInteractor.h> #include <vtkRenderer.h> #include <vtkSphereSource.h> #include <vtkXMLPolyDataReader.h> #include <vtkNamedColors.h> #include <vtkNew.h> #include <vtkProperty.h> int main(int, char*[]) { vtkNew<vtkNamedColors> colors; vtkNew<vtkPointSource> pointSource; pointSource->SetNumberOfPoints(100); pointSource->Update(); std::cout << "There are " << pointSource->GetNumberOfPoints() << " points." << std::endl; vtkNew<vtkQuantizePolyDataPoints> quantizeFilter; quantizeFilter->SetInputConnection(pointSource->GetOutputPort()); quantizeFilter->SetQFactor(.1); quantizeFilter->Update(); vtkPolyData* quantized = quantizeFilter->GetOutput(); std::cout << "There are " << quantized->GetNumberOfPoints() << " quantized points." << std::endl; for (vtkIdType i = 0; i < pointSource->GetOutput()->GetNumberOfPoints(); i++) { double pOrig[3]; double pQuantized[3]; pointSource->GetOutput()->GetPoint(i, pOrig); quantized->GetPoints()->GetPoint(i, pQuantized); std::cout << "Point " << i << " : (" << pOrig[0] << ", " << pOrig[1] << ", " << pOrig[2] << ")" << " (" << pQuantized[0] << ", " << pQuantized[1] << ", " << pQuantized[2] << ")" << std::endl; } double radius = 0.02; vtkNew<vtkSphereSource> sphereSource; sphereSource->SetRadius(radius); vtkNew<vtkGlyph3DMapper> inputMapper; inputMapper->SetInputConnection(pointSource->GetOutputPort()); inputMapper->SetSourceConnection(sphereSource->GetOutputPort()); inputMapper->ScalarVisibilityOff(); inputMapper->ScalingOff(); vtkNew<vtkActor> inputActor; inputActor->SetMapper(inputMapper); inputActor->GetProperty()->SetColor( colors->GetColor3d("Orchid").GetData()); vtkNew<vtkGlyph3DMapper> quantizedMapper; quantizedMapper->SetInputConnection(quantizeFilter->GetOutputPort()); quantizedMapper->SetSourceConnection(sphereSource->GetOutputPort()); quantizedMapper->ScalarVisibilityOff(); quantizedMapper->ScalingOff(); vtkNew<vtkActor> quantizedActor; quantizedActor->SetMapper(quantizedMapper); quantizedActor->GetProperty()->SetColor( colors->GetColor3d("Orchid").GetData()); // There will be one render window vtkNew<vtkRenderWindow> renderWindow; renderWindow->SetSize(640, 360); // And one interactor vtkNew<vtkRenderWindowInteractor> interactor; interactor->SetRenderWindow(renderWindow); renderWindow->SetWindowName("QuantizePolyDataPoints"); // Define viewport ranges // (xmin, ymin, xmax, ymax) double leftViewport[4] = {0.0, 0.0, 0.5, 1.0}; double rightViewport[4] = {0.5, 0.0, 1.0, 1.0}; // Setup both renderers vtkNew<vtkRenderer> leftRenderer; renderWindow->AddRenderer(leftRenderer); leftRenderer->SetViewport(leftViewport); leftRenderer->SetBackground(colors->GetColor3d("Bisque").GetData()); vtkNew<vtkRenderer> rightRenderer; renderWindow->AddRenderer(rightRenderer); rightRenderer->SetViewport(rightViewport); rightRenderer->SetBackground(colors->GetColor3d("PaleTurquoise").GetData()); leftRenderer->AddActor(inputActor); rightRenderer->AddActor(quantizedActor); leftRenderer->ResetCamera(); rightRenderer->SetActiveCamera(leftRenderer->GetActiveCamera()); renderWindow->Render(); interactor->Start(); return EXIT_SUCCESS; }
30.983193
80
0.71386
[ "render" ]
70a58f8107a30b6c9789181dace1874b3409cb38
4,109
cpp
C++
cpp/p3_python/source/p3/python/p3ui.cpp
mfkiwl/p3ui
639030830cf3366e722b2a251c847972ff8df11e
[ "MIT" ]
null
null
null
cpp/p3_python/source/p3/python/p3ui.cpp
mfkiwl/p3ui
639030830cf3366e722b2a251c847972ff8df11e
[ "MIT" ]
null
null
null
cpp/p3_python/source/p3/python/p3ui.cpp
mfkiwl/p3ui
639030830cf3366e722b2a251c847972ff8df11e
[ "MIT" ]
null
null
null
/***************************************************************************//*/ Copyright (c) 2021 Martin Rudoff 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 "p3ui.h" PYBIND11_MODULE(p3ui, module) { using namespace ::p3; module.doc() = R"docstring( Object Oriented ImGUI (https://github.com/0lru/p3) )docstring"; python::Definition<Node>::apply(module); python::Definition<Button>::apply(module); python::Definition<CheckBox>::apply(module); python::Definition<Layout>::apply(module); python::Definition<Texture>::apply(module); python::Definition<ToolTip>::apply(module); python::Definition<Image>::apply(module); python::Definition<Color>::apply(module); python::Definition<ColorEdit>::apply(module); python::Definition<ComboBox>::apply(module); python::Definition<Tab>::apply(module); python::Definition<Table>::apply(module); python::Definition<Text>::apply(module); python::Definition<Collapsible>::apply(module); python::Definition<InputText>::apply(module); python::Definition<InputScalar<std::int8_t>>::apply(module); python::Definition<InputScalar<std::uint8_t>>::apply(module); python::Definition<InputScalar<std::int16_t>>::apply(module); python::Definition<InputScalar<std::uint16_t>>::apply(module); python::Definition<InputScalar<std::int32_t>>::apply(module); python::Definition<InputScalar<std::uint32_t>>::apply(module); python::Definition<InputScalar<std::int64_t>>::apply(module); python::Definition<InputScalar<std::uint64_t>>::apply(module); python::Definition<InputScalar<float>>::apply(module); python::Definition<InputScalar<double>>::apply(module); python::Definition<Menu>::apply(module); python::Definition<MenuItem>::apply(module); python::Definition<MenuBar>::apply(module); python::Definition<Plot>::apply(module); python::Definition<Popup>::apply(module); python::Definition<ProgressBar>::apply(module); python::Definition<ChildWindow>::apply(module); python::Definition<ScrollArea>::apply(module); python::Definition<Slider<std::int8_t>>::apply(module); python::Definition<Slider<std::uint8_t>>::apply(module); python::Definition<Slider<std::int16_t>>::apply(module); python::Definition<Slider<std::uint16_t>>::apply(module); python::Definition<Slider<std::int32_t>>::apply(module); python::Definition<Slider<std::uint32_t>>::apply(module); python::Definition<Slider<std::int64_t>>::apply(module); python::Definition<Slider<std::uint64_t>>::apply(module); python::Definition<Slider<float>>::apply(module); python::Definition<Slider<double>>::apply(module); python::Definition<StyleBlock>::apply(module); python::Definition<Theme>::apply(module); python::Definition<UserInterface>::apply(module); python::Definition<Window>::apply(module); python::Definition<python::Builder>::apply(module); python::Definition<python::Surface>::apply(module); }
47.77907
80
0.69798
[ "object" ]
70b0123640913ded68b4802220301a3b7c113797
133,627
cpp
C++
src/ublox/SparkFun_Ublox_Arduino_Library.cpp
hanoba/Moonlight
e0293c9996cc4ba90e87377791e7a21a335788f4
[ "MIT" ]
null
null
null
src/ublox/SparkFun_Ublox_Arduino_Library.cpp
hanoba/Moonlight
e0293c9996cc4ba90e87377791e7a21a335788f4
[ "MIT" ]
null
null
null
src/ublox/SparkFun_Ublox_Arduino_Library.cpp
hanoba/Moonlight
e0293c9996cc4ba90e87377791e7a21a335788f4
[ "MIT" ]
null
null
null
/* This is a library written for the Ublox ZED-F9P and NEO-M8P-2 SparkFun sells these at its website: www.sparkfun.com Do you like this library? Help support SparkFun. Buy a board! https://www.sparkfun.com/products/15136 https://www.sparkfun.com/products/15005 https://www.sparkfun.com/products/15733 https://www.sparkfun.com/products/15193 https://www.sparkfun.com/products/15210 Written by Nathan Seidle @ SparkFun Electronics, September 6th, 2018 This library handles configuring and handling the responses from a Ublox GPS module. Works with most modules from Ublox including the Zed-F9P, NEO-M8P-2, NEO-M9N, ZOE-M8Q, SAM-M8Q, and many others. https://github.com/sparkfun/SparkFun_Ublox_Arduino_Library Development environment specifics: Arduino IDE 1.8.5 SparkFun code, firmware, and software is released under the MIT License(http://opensource.org/licenses/MIT). The MIT License (MIT) Copyright (c) 2016 SparkFun Electronics 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 "SparkFun_Ublox_Arduino_Library.h" SFE_UBLOX_GPS::SFE_UBLOX_GPS(void) { // Constructor currentGeofenceParams.numFences = 0; // Zero the number of geofences currently in use moduleQueried.versionNumber = false; if (checksumFailurePin >= 0) { pinMode((uint8_t)checksumFailurePin, OUTPUT); digitalWrite((uint8_t)checksumFailurePin, HIGH); } } //Initialize the Serial port boolean SFE_UBLOX_GPS::begin(TwoWire &wirePort, uint8_t deviceAddress) { commType = COMM_TYPE_I2C; _i2cPort = &wirePort; //Grab which port the user wants us to use //We expect caller to begin their I2C port, with the speed of their choice external to the library //But if they forget, we start the hardware here. //We're moving away from the practice of starting Wire hardware in a library. This is to avoid cross platform issues. //ie, there are some platforms that don't handle multiple starts to the wire hardware. Also, every time you start the wire //hardware the clock speed reverts back to 100kHz regardless of previous Wire.setClocks(). //_i2cPort->begin(); _gpsI2Caddress = deviceAddress; //Store the I2C address from user return (isConnected()); } //Initialize the Serial port boolean SFE_UBLOX_GPS::begin(Stream &serialPort) { commType = COMM_TYPE_SERIAL; _serialPort = &serialPort; //Grab which port the user wants us to use return (isConnected()); /*int counter = 0; while (true){ if (isConnected(200)) break; if (counter > 50){ return false; } counter++; } return true;*/ } //Enable or disable the printing of sent/response HEX values. //Use this in conjunction with 'Transport Logging' from the Universal Reader Assistant to see what they're doing that we're not void SFE_UBLOX_GPS::enableDebugging(Stream &debugPort, boolean printLimitedDebug) { _debugSerial = &debugPort; //Grab which port the user wants us to use for debugging if (printLimitedDebug == false) { _printDebug = true; //Should we print the commands we send? Good for debugging } else { _printLimitedDebug = true; //Should we print limited debug messages? Good for debugging high navigation rates } } void SFE_UBLOX_GPS::disableDebugging(void) { _printDebug = false; //Turn off extra print statements _printLimitedDebug = false; } //Safely print messages void SFE_UBLOX_GPS::debugPrint(char *message) { if (_printDebug == true) { _debugSerial->print(message); } } //Safely print messages void SFE_UBLOX_GPS::debugPrintln(char *message) { if (_printDebug == true) { _debugSerial->println(message); } } const char *SFE_UBLOX_GPS::statusString(sfe_ublox_status_e stat) { switch (stat) { case SFE_UBLOX_STATUS_SUCCESS: return "Success"; break; case SFE_UBLOX_STATUS_FAIL: return "General Failure"; break; case SFE_UBLOX_STATUS_CRC_FAIL: return "CRC Fail"; break; case SFE_UBLOX_STATUS_TIMEOUT: return "Timeout"; break; case SFE_UBLOX_STATUS_COMMAND_NACK: return "Command not acknowledged (NACK)"; break; case SFE_UBLOX_STATUS_OUT_OF_RANGE: return "Out of range"; break; case SFE_UBLOX_STATUS_INVALID_ARG: return "Invalid Arg"; break; case SFE_UBLOX_STATUS_INVALID_OPERATION: return "Invalid operation"; break; case SFE_UBLOX_STATUS_MEM_ERR: return "Memory Error"; break; case SFE_UBLOX_STATUS_HW_ERR: return "Hardware Error"; break; case SFE_UBLOX_STATUS_DATA_SENT: return "Data Sent"; break; case SFE_UBLOX_STATUS_DATA_RECEIVED: return "Data Received"; break; case SFE_UBLOX_STATUS_I2C_COMM_FAILURE: return "I2C Comm Failure"; break; case SFE_UBLOX_STATUS_DATA_OVERWRITTEN: return "Data Packet Overwritten"; break; default: return "Unknown Status"; break; } return "None"; } void SFE_UBLOX_GPS::factoryReset() { // Copy default settings to permanent // Note: this does not load the permanent configuration into the current configuration. Calling factoryDefault() will do that. packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_CFG; packetCfg.len = 13; packetCfg.startingSpot = 0; for (uint8_t i = 0; i < 4; i++) { payloadCfg[0 + i] = 0xff; // clear mask: copy default config to permanent config payloadCfg[4 + i] = 0x00; // save mask: don't save current to permanent payloadCfg[8 + i] = 0x00; // load mask: don't copy permanent config to current } payloadCfg[12] = 0xff; // all forms of permanent memory sendCommand(&packetCfg, 0); // don't expect ACK hardReset(); // cause factory default config to actually be loaded and used cleanly } void SFE_UBLOX_GPS::hardReset() { // Issue hard reset packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_RST; packetCfg.len = 4; packetCfg.startingSpot = 0; payloadCfg[0] = 0xff; // cold start payloadCfg[1] = 0xff; // cold start payloadCfg[2] = 0; // 0=HW reset payloadCfg[3] = 0; // reserved sendCommand(&packetCfg, 0); // don't expect ACK } void SFE_UBLOX_GPS::GNSSRestart() { // Issue hard reset packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_RST; packetCfg.len = 4; packetCfg.startingSpot = 0; payloadCfg[0] = 0x00; // warm start payloadCfg[1] = 0x00; // warm start payloadCfg[2] = 0x02; // 0x02=software reset (GNSS only) payloadCfg[3] = 0; // reserved sendCommand(&packetCfg, 0); // don't expect ACK } //Changes the serial baud rate of the Ublox module, can't return success/fail 'cause ACK from modem //is lost due to baud rate change void SFE_UBLOX_GPS::setSerialRate(uint32_t baudrate, uint8_t uartPort, uint16_t maxWait) { //Get the current config values for the UART port getPortSettings(uartPort, maxWait); //This will load the payloadCfg array with current port settings if (_printDebug == true) { _debugSerial->print(F("Current baud rate: ")); _debugSerial->println(((uint32_t)payloadCfg[10] << 16) | ((uint32_t)payloadCfg[9] << 8) | payloadCfg[8]); } packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_PRT; packetCfg.len = 20; packetCfg.startingSpot = 0; //payloadCfg is now loaded with current bytes. Change only the ones we need to payloadCfg[8] = baudrate; payloadCfg[9] = baudrate >> 8; payloadCfg[10] = baudrate >> 16; payloadCfg[11] = baudrate >> 24; if (_printDebug == true) { _debugSerial->print(F("New baud rate:")); _debugSerial->println(((uint32_t)payloadCfg[10] << 16) | ((uint32_t)payloadCfg[9] << 8) | payloadCfg[8]); } sfe_ublox_status_e retVal = sendCommand(&packetCfg, maxWait); if (_printDebug == true) { _debugSerial->print(F("setSerialRate: sendCommand returned: ")); _debugSerial->println(statusString(retVal)); } } //Changes the I2C address that the Ublox module responds to //0x42 is the default but can be changed with this command boolean SFE_UBLOX_GPS::setI2CAddress(uint8_t deviceAddress, uint16_t maxWait) { //Get the current config values for the I2C port getPortSettings(COM_PORT_I2C, maxWait); //This will load the payloadCfg array with current port settings packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_PRT; packetCfg.len = 20; packetCfg.startingSpot = 0; //payloadCfg is now loaded with current bytes. Change only the ones we need to payloadCfg[4] = deviceAddress << 1; //DDC mode LSB if (sendCommand(&packetCfg, maxWait) == SFE_UBLOX_STATUS_DATA_SENT) // We are only expecting an ACK { //Success! Now change our internal global. _gpsI2Caddress = deviceAddress; //Store the I2C address from user return (true); } return (false); } //Want to see the NMEA messages on the Serial port? Here's how void SFE_UBLOX_GPS::setNMEAOutputPort(Stream &nmeaOutputPort) { _nmeaOutputPort = &nmeaOutputPort; //Store the port from user } //Called regularly to check for available bytes on the user' specified port boolean SFE_UBLOX_GPS::checkUblox(uint8_t requestedClass, uint8_t requestedID) { return checkUbloxInternal(&packetCfg, requestedClass, requestedID); } //Called regularly to check for available bytes on the user' specified port boolean SFE_UBLOX_GPS::checkUbloxInternal(ubxPacket *incomingUBX, uint8_t requestedClass, uint8_t requestedID) { if (commType == COMM_TYPE_I2C) return (checkUbloxI2C(incomingUBX, requestedClass, requestedID)); else if (commType == COMM_TYPE_SERIAL) return (checkUbloxSerial(incomingUBX, requestedClass, requestedID)); return false; } //Polls I2C for data, passing any new bytes to process() //Returns true if new bytes are available boolean SFE_UBLOX_GPS::checkUbloxI2C(ubxPacket *incomingUBX, uint8_t requestedClass, uint8_t requestedID) { if (millis() - lastCheck >= i2cPollingWait) { //Get the number of bytes available from the module uint16_t bytesAvailable = 0; _i2cPort->beginTransmission(_gpsI2Caddress); _i2cPort->write(0xFD); //0xFD (MSB) and 0xFE (LSB) are the registers that contain number of bytes available if (_i2cPort->endTransmission(false) != 0) //Send a restart command. Do not release bus. return (false); //Sensor did not ACK _i2cPort->requestFrom((uint8_t)_gpsI2Caddress, (uint8_t)2); if (_i2cPort->available()) { uint8_t msb = _i2cPort->read(); uint8_t lsb = _i2cPort->read(); if (lsb == 0xFF) { //I believe this is a Ublox bug. Device should never present an 0xFF. if ((_printDebug == true) || (_printLimitedDebug == true)) // Print this if doing limited debugging { _debugSerial->println(F("checkUbloxI2C: Ublox bug, length lsb is 0xFF")); } if (checksumFailurePin >= 0) { digitalWrite((uint8_t)checksumFailurePin, LOW); delay(10); digitalWrite((uint8_t)checksumFailurePin, HIGH); } lastCheck = millis(); //Put off checking to avoid I2C bus traffic return (false); } bytesAvailable = (uint16_t)msb << 8 | lsb; } if (bytesAvailable == 0) { if (_printDebug == true) { _debugSerial->println(F("checkUbloxI2C: OK, zero bytes available")); } lastCheck = millis(); //Put off checking to avoid I2C bus traffic return (false); } //Check for undocumented bit error. We found this doing logic scans. //This error is rare but if we incorrectly interpret the first bit of the two 'data available' bytes as 1 //then we have far too many bytes to check. May be related to I2C setup time violations: https://github.com/sparkfun/SparkFun_Ublox_Arduino_Library/issues/40 if (bytesAvailable & ((uint16_t)1 << 15)) { //Clear the MSbit bytesAvailable &= ~((uint16_t)1 << 15); if ((_printDebug == true) || (_printLimitedDebug == true)) // Print this if doing limited debugging { _debugSerial->print(F("checkUbloxI2C: Bytes available error:")); _debugSerial->println(bytesAvailable); if (checksumFailurePin >= 0) { digitalWrite((uint8_t)checksumFailurePin, LOW); delay(10); digitalWrite((uint8_t)checksumFailurePin, HIGH); } } } if (bytesAvailable > 100) { if (_printDebug == true) { _debugSerial->print(F("checkUbloxI2C: Large packet of ")); _debugSerial->print(bytesAvailable); _debugSerial->println(F(" bytes received")); } } else { if (_printDebug == true) { _debugSerial->print(F("checkUbloxI2C: Reading ")); _debugSerial->print(bytesAvailable); _debugSerial->println(F(" bytes")); } } while (bytesAvailable) { _i2cPort->beginTransmission(_gpsI2Caddress); _i2cPort->write(0xFF); //0xFF is the register to read data from if (_i2cPort->endTransmission(false) != 0) //Send a restart command. Do not release bus. return (false); //Sensor did not ACK //Limit to 32 bytes or whatever the buffer limit is for given platform uint16_t bytesToRead = bytesAvailable; if (bytesToRead > I2C_BUFFER_LENGTH) bytesToRead = I2C_BUFFER_LENGTH; TRY_AGAIN: _i2cPort->requestFrom((uint8_t)_gpsI2Caddress, (uint8_t)bytesToRead); if (_i2cPort->available()) { for (uint16_t x = 0; x < bytesToRead; x++) { uint8_t incoming = _i2cPort->read(); //Grab the actual character //Check to see if the first read is 0x7F. If it is, the module is not ready //to respond. Stop, wait, and try again if (x == 0) { if (incoming == 0x7F) { if ((_printDebug == true) || (_printLimitedDebug == true)) // Print this if doing limited debugging { _debugSerial->println(F("checkUbloxU2C: Ublox error, module not ready with data")); } delay(5); //In logic analyzation, the module starting responding after 1.48ms if (checksumFailurePin >= 0) { digitalWrite((uint8_t)checksumFailurePin, LOW); delay(10); digitalWrite((uint8_t)checksumFailurePin, HIGH); } goto TRY_AGAIN; } } process(incoming, incomingUBX, requestedClass, requestedID); //Process this valid character } } else return (false); //Sensor did not respond bytesAvailable -= bytesToRead; } } return (true); } //end checkUbloxI2C() //Checks Serial for data, passing any new bytes to process() boolean SFE_UBLOX_GPS::checkUbloxSerial(ubxPacket *incomingUBX, uint8_t requestedClass, uint8_t requestedID) { while (_serialPort->available()) { process(_serialPort->read(), incomingUBX, requestedClass, requestedID); } return (true); } //end checkUbloxSerial() //Processes NMEA and UBX binary sentences one byte at a time //Take a given byte and file it into the proper array void SFE_UBLOX_GPS::process(uint8_t incoming, ubxPacket *incomingUBX, uint8_t requestedClass, uint8_t requestedID) { if ((currentSentence == NONE) || (currentSentence == NMEA)) { if (incoming == 0xB5) //UBX binary frames start with 0xB5, aka � { //This is the start of a binary sentence. Reset flags. //We still don't know the response class ubxFrameCounter = 0; currentSentence = UBX; //Reset the packetBuf.counter even though we will need to reset it again when ubxFrameCounter == 2 packetBuf.counter = 0; ignoreThisPayload = false; //We should not ignore this payload - yet //Store data in packetBuf until we know if we have a requested class and ID match activePacketBuffer = SFE_UBLOX_PACKET_PACKETBUF; } else if (incoming == '$') { currentSentence = NMEA; } else if (incoming == 0xD3) //RTCM frames start with 0xD3 { rtcmFrameCounter = 0; currentSentence = RTCM; } else { //This character is unknown or we missed the previous start of a sentence } } //Depending on the sentence, pass the character to the individual processor if (currentSentence == UBX) { //Decide what type of response this is if ((ubxFrameCounter == 0) && (incoming != 0xB5)) //ISO '�' currentSentence = NONE; //Something went wrong. Reset. else if ((ubxFrameCounter == 1) && (incoming != 0x62)) //ASCII 'b' currentSentence = NONE; //Something went wrong. Reset. // Note to future self: // There may be some duplication / redundancy in the next few lines as processUBX will also // load information into packetBuf, but we'll do it here too for clarity else if (ubxFrameCounter == 2) //Class { // Record the class in packetBuf until we know what to do with it packetBuf.cls = incoming; // (Duplication) rollingChecksumA = 0; //Reset our rolling checksums here (not when we receive the 0xB5) rollingChecksumB = 0; packetBuf.counter = 0; //Reset the packetBuf.counter (again) packetBuf.valid = SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED; // Reset the packet validity (redundant?) packetBuf.startingSpot = incomingUBX->startingSpot; //Copy the startingSpot } else if (ubxFrameCounter == 3) //ID { // Record the ID in packetBuf until we know what to do with it packetBuf.id = incoming; // (Duplication) //We can now identify the type of response //If the packet we are receiving is not an ACK then check for a class and ID match if (packetBuf.cls != UBX_CLASS_ACK) { //This is not an ACK so check for a class and ID match if ((packetBuf.cls == requestedClass) && (packetBuf.id == requestedID)) { //This is not an ACK and we have a class and ID match //So start diverting data into incomingUBX (usually packetCfg) activePacketBuffer = SFE_UBLOX_PACKET_PACKETCFG; incomingUBX->cls = packetBuf.cls; //Copy the class and ID into incomingUBX (usually packetCfg) incomingUBX->id = packetBuf.id; incomingUBX->counter = packetBuf.counter; //Copy over the .counter too } else { //This is not an ACK and we do not have a class and ID match //so we should keep diverting data into packetBuf and ignore the payload ignoreThisPayload = true; } } else { // This is an ACK so it is to early to do anything with it // We need to wait until we have received the length and data bytes // So we should keep diverting data into packetBuf } } else if (ubxFrameCounter == 4) //Length LSB { //We should save the length in packetBuf even if activePacketBuffer == SFE_UBLOX_PACKET_PACKETCFG packetBuf.len = incoming; // (Duplication) } else if (ubxFrameCounter == 5) //Length MSB { //We should save the length in packetBuf even if activePacketBuffer == SFE_UBLOX_PACKET_PACKETCFG packetBuf.len |= incoming << 8; // (Duplication) } else if (ubxFrameCounter == 6) //This should be the first byte of the payload unless .len is zero { if (packetBuf.len == 0) // Check if length is zero (hopefully this is impossible!) { if (_printDebug == true) { _debugSerial->print(F("process: ZERO LENGTH packet received: Class: 0x")); _debugSerial->print(packetBuf.cls, HEX); _debugSerial->print(F(" ID: 0x")); _debugSerial->println(packetBuf.id, HEX); } //If length is zero (!) this will be the first byte of the checksum so record it packetBuf.checksumA = incoming; } else { //The length is not zero so record this byte in the payload packetBuf.payload[0] = incoming; } } else if (ubxFrameCounter == 7) //This should be the second byte of the payload unless .len is zero or one { if (packetBuf.len == 0) // Check if length is zero (hopefully this is impossible!) { //If length is zero (!) this will be the second byte of the checksum so record it packetBuf.checksumB = incoming; } else if (packetBuf.len == 1) // Check if length is one { //The length is one so this is the first byte of the checksum packetBuf.checksumA = incoming; } else // Length is >= 2 so this must be a payload byte { packetBuf.payload[1] = incoming; } // Now that we have received two payload bytes, we can check for a matching ACK/NACK if ((activePacketBuffer == SFE_UBLOX_PACKET_PACKETBUF) // If we are not already processing a data packet && (packetBuf.cls == UBX_CLASS_ACK) // and if this is an ACK/NACK && (packetBuf.payload[0] == requestedClass) // and if the class matches && (packetBuf.payload[1] == requestedID)) // and if the ID matches { if (packetBuf.len == 2) // Check if .len is 2 { // Then this is a matching ACK so copy it into packetAck activePacketBuffer = SFE_UBLOX_PACKET_PACKETACK; packetAck.cls = packetBuf.cls; packetAck.id = packetBuf.id; packetAck.len = packetBuf.len; packetAck.counter = packetBuf.counter; packetAck.payload[0] = packetBuf.payload[0]; packetAck.payload[1] = packetBuf.payload[1]; } else // Length is not 2 (hopefully this is impossible!) { if (_printDebug == true) { _debugSerial->print(F("process: ACK received with .len != 2: Class: 0x")); _debugSerial->print(packetBuf.payload[0], HEX); _debugSerial->print(F(" ID: 0x")); _debugSerial->print(packetBuf.payload[1], HEX); _debugSerial->print(F(" len: ")); _debugSerial->println(packetBuf.len); } } } } //Divert incoming into the correct buffer if (activePacketBuffer == SFE_UBLOX_PACKET_PACKETACK) processUBX(incoming, &packetAck, requestedClass, requestedID); else if (activePacketBuffer == SFE_UBLOX_PACKET_PACKETCFG) processUBX(incoming, incomingUBX, requestedClass, requestedID); else // if (activePacketBuffer == SFE_UBLOX_PACKET_PACKETBUF) processUBX(incoming, &packetBuf, requestedClass, requestedID); //Finally, increment the frame counter ubxFrameCounter++; } else if (currentSentence == NMEA) { processNMEA(incoming); //Process each NMEA character } else if (currentSentence == RTCM) { processRTCMframe(incoming); //Deal with RTCM bytes } } //This is the default or generic NMEA processor. We're only going to pipe the data to serial port so we can see it. //User could overwrite this function to pipe characters to nmea.process(c) of tinyGPS or MicroNMEA //Or user could pipe each character to a buffer, radio, etc. void SFE_UBLOX_GPS::processNMEA(char incoming) { //If user has assigned an output port then pipe the characters there if (_nmeaOutputPort != NULL) _nmeaOutputPort->write(incoming); //Echo this byte to the serial port } //We need to be able to identify an RTCM packet and then the length //so that we know when the RTCM message is completely received and we then start //listening for other sentences (like NMEA or UBX) //RTCM packet structure is very odd. I never found RTCM STANDARD 10403.2 but //http://d1.amobbs.com/bbs_upload782111/files_39/ourdev_635123CK0HJT.pdf is good //https://dspace.cvut.cz/bitstream/handle/10467/65205/F3-BP-2016-Shkalikava-Anastasiya-Prenos%20polohove%20informace%20prostrednictvim%20datove%20site.pdf?sequence=-1 //Lead me to: https://forum.u-blox.com/index.php/4348/how-to-read-rtcm-messages-from-neo-m8p //RTCM 3.2 bytes look like this: //Byte 0: Always 0xD3 //Byte 1: 6-bits of zero //Byte 2: 10-bits of length of this packet including the first two-ish header bytes, + 6. //byte 3 + 4 bits: Msg type 12 bits //Example: D3 00 7C 43 F0 ... / 0x7C = 124+6 = 130 bytes in this packet, 0x43F = Msg type 1087 void SFE_UBLOX_GPS::processRTCMframe(uint8_t incoming) { if (rtcmFrameCounter == 1) { rtcmLen = (incoming & 0x03) << 8; //Get the last two bits of this byte. Bits 8&9 of 10-bit length } else if (rtcmFrameCounter == 2) { rtcmLen |= incoming; //Bits 0-7 of packet length rtcmLen += 6; //There are 6 additional bytes of what we presume is header, msgType, CRC, and stuff } /*else if (rtcmFrameCounter == 3) { rtcmMsgType = incoming << 4; //Message Type, MS 4 bits } else if (rtcmFrameCounter == 4) { rtcmMsgType |= (incoming >> 4); //Message Type, bits 0-7 }*/ rtcmFrameCounter++; processRTCM(incoming); //Here is where we expose this byte to the user if (rtcmFrameCounter == rtcmLen) { //We're done! currentSentence = NONE; //Reset and start looking for next sentence type } } //This function is called for each byte of an RTCM frame //Ths user can overwrite this function and process the RTCM frame as they please //Bytes can be piped to Serial or other interface. The consumer could be a radio or the internet (Ntrip broadcaster) void SFE_UBLOX_GPS::processRTCM(uint8_t incoming) { //Radio.sendReliable((String)incoming); //An example of passing this byte to a radio //_debugSerial->write(incoming); //An example of passing this byte out the serial port //Debug printing // _debugSerial->print(F(" ")); // if(incoming < 0x10) _debugSerial->print(F("0")); // if(incoming < 0x10) _debugSerial->print(F("0")); // _debugSerial->print(incoming, HEX); // if(rtcmFrameCounter % 16 == 0) _debugSerial->println(); } //Given a character, file it away into the uxb packet structure //Set valid to VALID or NOT_VALID once sentence is completely received and passes or fails CRC //The payload portion of the packet can be 100s of bytes but the max array //size is MAX_PAYLOAD_SIZE bytes. startingSpot can be set so we only record //a subset of bytes within a larger packet. void SFE_UBLOX_GPS::processUBX(uint8_t incoming, ubxPacket *incomingUBX, uint8_t requestedClass, uint8_t requestedID) { //Add all incoming bytes to the rolling checksum //Stop at len+4 as this is the checksum bytes to that should not be added to the rolling checksum if (incomingUBX->counter < incomingUBX->len + 4) addToChecksum(incoming); if (incomingUBX->counter == 0) { incomingUBX->cls = incoming; } else if (incomingUBX->counter == 1) { incomingUBX->id = incoming; } else if (incomingUBX->counter == 2) //Len LSB { incomingUBX->len = incoming; } else if (incomingUBX->counter == 3) //Len MSB { incomingUBX->len |= incoming << 8; } else if (incomingUBX->counter == incomingUBX->len + 4) //ChecksumA { incomingUBX->checksumA = incoming; } else if (incomingUBX->counter == incomingUBX->len + 5) //ChecksumB { incomingUBX->checksumB = incoming; currentSentence = NONE; //We're done! Reset the sentence to being looking for a new start char //Validate this sentence if ((incomingUBX->checksumA == rollingChecksumA) && (incomingUBX->checksumB == rollingChecksumB)) { incomingUBX->valid = SFE_UBLOX_PACKET_VALIDITY_VALID; // Flag the packet as valid // Let's check if the class and ID match the requestedClass and requestedID // Remember - this could be a data packet or an ACK packet if ((incomingUBX->cls == requestedClass) && (incomingUBX->id == requestedID)) { incomingUBX->classAndIDmatch = SFE_UBLOX_PACKET_VALIDITY_VALID; // If we have a match, set the classAndIDmatch flag to valid } // If this is an ACK then let's check if the class and ID match the requestedClass and requestedID else if ((incomingUBX->cls == UBX_CLASS_ACK) && (incomingUBX->id == UBX_ACK_ACK) && (incomingUBX->payload[0] == requestedClass) && (incomingUBX->payload[1] == requestedID)) { incomingUBX->classAndIDmatch = SFE_UBLOX_PACKET_VALIDITY_VALID; // If we have a match, set the classAndIDmatch flag to valid } // If this is a NACK then let's check if the class and ID match the requestedClass and requestedID else if ((incomingUBX->cls == UBX_CLASS_ACK) && (incomingUBX->id == UBX_ACK_NACK) && (incomingUBX->payload[0] == requestedClass) && (incomingUBX->payload[1] == requestedID)) { incomingUBX->classAndIDmatch = SFE_UBLOX_PACKET_NOTACKNOWLEDGED; // If we have a match, set the classAndIDmatch flag to NOTACKNOWLEDGED if (_printDebug == true) { _debugSerial->print(F("processUBX: NACK received: Requested Class: 0x")); _debugSerial->print(incomingUBX->payload[0], HEX); _debugSerial->print(F(" Requested ID: 0x")); _debugSerial->println(incomingUBX->payload[1], HEX); } } if (_printDebug == true) { _debugSerial->print(F("Incoming: Size: ")); _debugSerial->print(incomingUBX->len); _debugSerial->print(F(" Received: ")); printPacket(incomingUBX); if (incomingUBX->valid == SFE_UBLOX_PACKET_VALIDITY_VALID) { _debugSerial->println(F("packetCfg now valid")); } if (packetAck.valid == SFE_UBLOX_PACKET_VALIDITY_VALID) { _debugSerial->println(F("packetAck now valid")); } if (incomingUBX->classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_VALID) { _debugSerial->println(F("packetCfg classAndIDmatch")); } if (packetAck.classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_VALID) { _debugSerial->println(F("packetAck classAndIDmatch")); } } //We've got a valid packet, now do something with it but only if ignoreThisPayload is false if (ignoreThisPayload == false) { processUBXpacket(incomingUBX); } } else // Checksum failure { incomingUBX->valid = SFE_UBLOX_PACKET_VALIDITY_NOT_VALID; // Let's check if the class and ID match the requestedClass and requestedID. // This is potentially risky as we are saying that we saw the requested Class and ID // but that the packet checksum failed. Potentially it could be the class or ID bytes // that caused the checksum error! if ((incomingUBX->cls == requestedClass) && (incomingUBX->id == requestedID)) { incomingUBX->classAndIDmatch = SFE_UBLOX_PACKET_VALIDITY_NOT_VALID; // If we have a match, set the classAndIDmatch flag to not valid } // If this is an ACK then let's check if the class and ID match the requestedClass and requestedID else if ((incomingUBX->cls == UBX_CLASS_ACK) && (incomingUBX->payload[0] == requestedClass) && (incomingUBX->payload[1] == requestedID)) { incomingUBX->classAndIDmatch = SFE_UBLOX_PACKET_VALIDITY_NOT_VALID; // If we have a match, set the classAndIDmatch flag to not valid } if ((_printDebug == true) || (_printLimitedDebug == true)) // Print this if doing limited debugging { //Drive an external pin to allow for easier logic analyzation if (checksumFailurePin >= 0) { digitalWrite((uint8_t)checksumFailurePin, LOW); delay(10); digitalWrite((uint8_t)checksumFailurePin, HIGH); } _debugSerial->print(F("Checksum failed:")); _debugSerial->print(F(" checksumA: ")); _debugSerial->print(incomingUBX->checksumA); _debugSerial->print(F(" checksumB: ")); _debugSerial->print(incomingUBX->checksumB); _debugSerial->print(F(" rollingChecksumA: ")); _debugSerial->print(rollingChecksumA); _debugSerial->print(F(" rollingChecksumB: ")); _debugSerial->print(rollingChecksumB); _debugSerial->println(); _debugSerial->print(F("Failed : ")); _debugSerial->print(F("Size: ")); _debugSerial->print(incomingUBX->len); _debugSerial->print(F(" Received: ")); printPacket(incomingUBX); } } } else //Load this byte into the payload array { //If a UBX_NAV_PVT packet comes in asynchronously, we need to fudge the startingSpot uint16_t startingSpot = incomingUBX->startingSpot; if (incomingUBX->cls == UBX_CLASS_NAV && incomingUBX->id == UBX_NAV_PVT) startingSpot = 0; //Begin recording if counter goes past startingSpot if ((incomingUBX->counter - 4) >= startingSpot) { //Check to see if we have room for this byte if (((incomingUBX->counter - 4) - startingSpot) < MAX_PAYLOAD_SIZE) //If counter = 208, starting spot = 200, we're good to record. { // Check if this is payload data which should be ignored if (ignoreThisPayload == false) { incomingUBX->payload[incomingUBX->counter - 4 - startingSpot] = incoming; //Store this byte into payload array } } } } //Increment the counter incomingUBX->counter++; if (incomingUBX->counter == MAX_PAYLOAD_SIZE) { //Something has gone very wrong currentSentence = NONE; //Reset the sentence to being looking for a new start char if (_printDebug == true) { _debugSerial->println(F("processUBX: counter hit MAX_PAYLOAD_SIZE")); } } } //Once a packet has been received and validated, identify this packet's class/id and update internal flags //Note: if the user requests a PVT or a HPPOSLLH message using a custom packet, the data extraction will // not work as expected beacuse extractLong etc are hardwired to packetCfg payloadCfg. Ideally // extractLong etc should be updated so they receive a pointer to the packet buffer. void SFE_UBLOX_GPS::processUBXpacket(ubxPacket *msg) { switch (msg->cls) { case UBX_CLASS_NAV: if (msg->id == UBX_NAV_PVT && msg->len == 92) { //Parse various byte fields into global vars constexpr int startingSpot = 0; //fixed value used in processUBX timeOfWeek = extractLong(0); gpsMillisecond = extractLong(0) % 1000; //Get last three digits of iTOW gpsYear = extractInt(4); gpsMonth = extractByte(6); gpsDay = extractByte(7); gpsHour = extractByte(8); gpsMinute = extractByte(9); gpsSecond = extractByte(10); gpsDateValid = extractByte(11) & 0x01; gpsTimeValid = (extractByte(11) & 0x02) >> 1; gpsNanosecond = extractLong(16); //Includes milliseconds fixType = extractByte(20 - startingSpot); carrierSolution = extractByte(21 - startingSpot) >> 6; //Get 6th&7th bits of this byte SIV = extractByte(23 - startingSpot); longitude = extractLong(24 - startingSpot); latitude = extractLong(28 - startingSpot); altitude = extractLong(32 - startingSpot); altitudeMSL = extractLong(36 - startingSpot); groundSpeed = extractLong(60 - startingSpot); headingOfMotion = extractLong(64 - startingSpot); pDOP = extractInt(76 - startingSpot); //Mark all datums as fresh (not read before) moduleQueried.gpsiTOW = true; moduleQueried.gpsYear = true; moduleQueried.gpsMonth = true; moduleQueried.gpsDay = true; moduleQueried.gpsHour = true; moduleQueried.gpsMinute = true; moduleQueried.gpsSecond = true; moduleQueried.gpsDateValid = true; moduleQueried.gpsTimeValid = true; moduleQueried.gpsNanosecond = true; moduleQueried.all = true; moduleQueried.longitude = true; moduleQueried.latitude = true; moduleQueried.altitude = true; moduleQueried.altitudeMSL = true; moduleQueried.SIV = true; moduleQueried.fixType = true; moduleQueried.carrierSolution = true; moduleQueried.groundSpeed = true; moduleQueried.headingOfMotion = true; moduleQueried.pDOP = true; } else if (msg->id == UBX_NAV_HPPOSLLH && msg->len == 36) { timeOfWeek = extractLong(4); highResLongitude = extractLong(8); highResLatitude = extractLong(12); elipsoid = extractLong(16); meanSeaLevel = extractLong(20); highResLongitudeHp = extractSignedChar(24); highResLatitudeHp = extractSignedChar(25); elipsoidHp = extractSignedChar(26); meanSeaLevelHp = extractSignedChar(27); horizontalAccuracy = extractLong(28); verticalAccuracy = extractLong(32); highResModuleQueried.all = true; highResModuleQueried.highResLatitude = true; highResModuleQueried.highResLatitudeHp = true; highResModuleQueried.highResLongitude = true; highResModuleQueried.highResLongitudeHp = true; highResModuleQueried.elipsoid = true; highResModuleQueried.elipsoidHp = true; highResModuleQueried.meanSeaLevel = true; highResModuleQueried.meanSeaLevelHp = true; highResModuleQueried.geoidSeparation = true; highResModuleQueried.horizontalAccuracy = true; highResModuleQueried.verticalAccuracy = true; moduleQueried.gpsiTOW = true; // this can arrive via HPPOS too. if (_printDebug == true) { _debugSerial->print(F("Sec: ")); _debugSerial->print(((float)extractLong(4)) / 1000.0f); _debugSerial->print(F(" ")); _debugSerial->print(F("LON: ")); _debugSerial->print(((float)(int32_t)extractLong(8)) / 10000000.0f); _debugSerial->print(F(" ")); _debugSerial->print(F("LAT: ")); _debugSerial->print(((float)(int32_t)extractLong(12)) / 10000000.0f); _debugSerial->print(F(" ")); _debugSerial->print(F("ELI M: ")); _debugSerial->print(((float)(int32_t)extractLong(16)) / 1000.0f); _debugSerial->print(F(" ")); _debugSerial->print(F("MSL M: ")); _debugSerial->print(((float)(int32_t)extractLong(20)) / 1000.0f); _debugSerial->print(F(" ")); _debugSerial->print(F("LON HP: ")); _debugSerial->print(extractSignedChar(24)); _debugSerial->print(F(" ")); _debugSerial->print(F("LAT HP: ")); _debugSerial->print(extractSignedChar(25)); _debugSerial->print(F(" ")); _debugSerial->print(F("ELI HP: ")); _debugSerial->print(extractSignedChar(26)); _debugSerial->print(F(" ")); _debugSerial->print(F("MSL HP: ")); _debugSerial->print(extractSignedChar(27)); _debugSerial->print(F(" ")); _debugSerial->print(F("HA 2D M: ")); _debugSerial->print(((float)(int32_t)extractLong(28)) / 10000.0f); _debugSerial->print(F(" ")); _debugSerial->print(F("VERT M: ")); _debugSerial->println(((float)(int32_t)extractLong(32)) / 10000.0f); } } break; } } //Given a packet and payload, send everything including CRC bytes via I2C port sfe_ublox_status_e SFE_UBLOX_GPS::sendCommand(ubxPacket *outgoingUBX, uint16_t maxWait) { sfe_ublox_status_e retVal = SFE_UBLOX_STATUS_SUCCESS; calcChecksum(outgoingUBX); //Sets checksum A and B bytes of the packet if (_printDebug == true) { _debugSerial->print(F("\nSending: ")); printPacket(outgoingUBX); } if (commType == COMM_TYPE_I2C) { retVal = sendI2cCommand(outgoingUBX, maxWait); if (retVal != SFE_UBLOX_STATUS_SUCCESS) { if (_printDebug == true) { _debugSerial->println(F("Send I2C Command failed")); } return retVal; } } else if (commType == COMM_TYPE_SERIAL) { sendSerialCommand(outgoingUBX); } if (maxWait > 0) { //Depending on what we just sent, either we need to look for an ACK or not if (outgoingUBX->cls == UBX_CLASS_CFG) { if (_printDebug == true) { _debugSerial->println(F("sendCommand: Waiting for ACK response")); } retVal = waitForACKResponse(outgoingUBX, outgoingUBX->cls, outgoingUBX->id, maxWait); //Wait for Ack response } else { if (_printDebug == true) { _debugSerial->println(F("sendCommand: Waiting for No ACK response")); } retVal = waitForNoACKResponse(outgoingUBX, outgoingUBX->cls, outgoingUBX->id, maxWait); //Wait for Ack response } } return retVal; } //Returns false if sensor fails to respond to I2C traffic sfe_ublox_status_e SFE_UBLOX_GPS::sendI2cCommand(ubxPacket *outgoingUBX, uint16_t maxWait) { //Point at 0xFF data register _i2cPort->beginTransmission((uint8_t)_gpsI2Caddress); //There is no register to write to, we just begin writing data bytes _i2cPort->write(0xFF); if (_i2cPort->endTransmission() != 0) //Don't release bus return (SFE_UBLOX_STATUS_I2C_COMM_FAILURE); //Sensor did not ACK //Write header bytes _i2cPort->beginTransmission((uint8_t)_gpsI2Caddress); //There is no register to write to, we just begin writing data bytes _i2cPort->write(UBX_SYNCH_1); //� - oh ublox, you're funny. I will call you micro-blox from now on. _i2cPort->write(UBX_SYNCH_2); //b _i2cPort->write(outgoingUBX->cls); _i2cPort->write(outgoingUBX->id); _i2cPort->write(outgoingUBX->len & 0xFF); //LSB _i2cPort->write(outgoingUBX->len >> 8); //MSB if (_i2cPort->endTransmission(false) != 0) //Do not release bus return (SFE_UBLOX_STATUS_I2C_COMM_FAILURE); //Sensor did not ACK //Write payload. Limit the sends into 32 byte chunks //This code based on ublox: https://forum.u-blox.com/index.php/20528/how-to-use-i2c-to-get-the-nmea-frames uint16_t bytesToSend = outgoingUBX->len; //"The number of data bytes must be at least 2 to properly distinguish //from the write access to set the address counter in random read accesses." uint16_t startSpot = 0; while (bytesToSend > 1) { uint8_t len = bytesToSend; if (len > I2C_BUFFER_LENGTH) len = I2C_BUFFER_LENGTH; _i2cPort->beginTransmission((uint8_t)_gpsI2Caddress); //_i2cPort->write(outgoingUBX->payload, len); //Write a portion of the payload to the bus for (uint16_t x = 0; x < len; x++) _i2cPort->write(outgoingUBX->payload[startSpot + x]); //Write a portion of the payload to the bus if (_i2cPort->endTransmission(false) != 0) //Don't release bus return (SFE_UBLOX_STATUS_I2C_COMM_FAILURE); //Sensor did not ACK //*outgoingUBX->payload += len; //Move the pointer forward startSpot += len; //Move the pointer forward bytesToSend -= len; } //Write checksum _i2cPort->beginTransmission((uint8_t)_gpsI2Caddress); if (bytesToSend == 1) _i2cPort->write(outgoingUBX->payload, 1); _i2cPort->write(outgoingUBX->checksumA); _i2cPort->write(outgoingUBX->checksumB); //All done transmitting bytes. Release bus. if (_i2cPort->endTransmission() != 0) return (SFE_UBLOX_STATUS_I2C_COMM_FAILURE); //Sensor did not ACK return (SFE_UBLOX_STATUS_SUCCESS); } //Given a packet and payload, send everything including CRC bytesA via Serial port void SFE_UBLOX_GPS::sendSerialCommand(ubxPacket *outgoingUBX) { //Write header bytes _serialPort->write(UBX_SYNCH_1); //� - oh ublox, you're funny. I will call you micro-blox from now on. _serialPort->write(UBX_SYNCH_2); //b _serialPort->write(outgoingUBX->cls); _serialPort->write(outgoingUBX->id); _serialPort->write(outgoingUBX->len & 0xFF); //LSB _serialPort->write(outgoingUBX->len >> 8); //MSB //Write payload. for (int i = 0; i < outgoingUBX->len; i++) { _serialPort->write(outgoingUBX->payload[i]); } //Write checksum _serialPort->write(outgoingUBX->checksumA); _serialPort->write(outgoingUBX->checksumB); } //Returns true if I2C device ack's boolean SFE_UBLOX_GPS::isConnected(uint16_t maxWait) { if (commType == COMM_TYPE_I2C) { _i2cPort->beginTransmission((uint8_t)_gpsI2Caddress); if (_i2cPort->endTransmission() != 0) return false; //Sensor did not ack } // Query navigation rate to see whether we get a meaningful response packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_RATE; packetCfg.len = 0; packetCfg.startingSpot = 0; return (sendCommand(&packetCfg, maxWait) == SFE_UBLOX_STATUS_DATA_RECEIVED); // We are polling the RATE so we expect data and an ACK } //Given a message, calc and store the two byte "8-Bit Fletcher" checksum over the entirety of the message //This is called before we send a command message void SFE_UBLOX_GPS::calcChecksum(ubxPacket *msg) { msg->checksumA = 0; msg->checksumB = 0; msg->checksumA += msg->cls; msg->checksumB += msg->checksumA; msg->checksumA += msg->id; msg->checksumB += msg->checksumA; msg->checksumA += (msg->len & 0xFF); msg->checksumB += msg->checksumA; msg->checksumA += (msg->len >> 8); msg->checksumB += msg->checksumA; for (uint16_t i = 0; i < msg->len; i++) { msg->checksumA += msg->payload[i]; msg->checksumB += msg->checksumA; } } //Given a message and a byte, add to rolling "8-Bit Fletcher" checksum //This is used when receiving messages from module void SFE_UBLOX_GPS::addToChecksum(uint8_t incoming) { rollingChecksumA += incoming; rollingChecksumB += rollingChecksumA; } //Pretty prints the current ubxPacket void SFE_UBLOX_GPS::printPacket(ubxPacket *packet) { if (_printDebug == true) { _debugSerial->print(F("CLS:")); if (packet->cls == UBX_CLASS_NAV) //1 _debugSerial->print(F("NAV")); else if (packet->cls == UBX_CLASS_ACK) //5 _debugSerial->print(F("ACK")); else if (packet->cls == UBX_CLASS_CFG) //6 _debugSerial->print(F("CFG")); else if (packet->cls == UBX_CLASS_MON) //0x0A _debugSerial->print(F("MON")); else { _debugSerial->print(F("0x")); _debugSerial->print(packet->cls, HEX); } _debugSerial->print(F(" ID:")); if (packet->cls == UBX_CLASS_NAV && packet->id == UBX_NAV_PVT) _debugSerial->print(F("PVT")); else if (packet->cls == UBX_CLASS_CFG && packet->id == UBX_CFG_RATE) _debugSerial->print(F("RATE")); else if (packet->cls == UBX_CLASS_CFG && packet->id == UBX_CFG_CFG) _debugSerial->print(F("SAVE")); else { _debugSerial->print(F("0x")); _debugSerial->print(packet->id, HEX); } _debugSerial->print(F(" Len: 0x")); _debugSerial->print(packet->len, HEX); // Only print the payload is ignoreThisPayload is false otherwise // we could be printing gibberish from beyond the end of packetBuf if (ignoreThisPayload == false) { _debugSerial->print(F(" Payload:")); for (int x = 0; x < packet->len; x++) { _debugSerial->print(F(" ")); _debugSerial->print(packet->payload[x], HEX); } } else { _debugSerial->print(F(" Payload: IGNORED")); } _debugSerial->println(); } } //=-=-=-=-=-=-=-= Specific commands =-=-=-=-=-=-=-==-=-=-=-=-=-=-= //=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-==-=-=-=-=-=-=-=-=-=-=-=-=-=-=-= //When messages from the class CFG are sent to the receiver, the receiver will send an "acknowledge"(UBX - ACK - ACK) or a //"not acknowledge"(UBX-ACK-NAK) message back to the sender, depending on whether or not the message was processed correctly. //Some messages from other classes also use the same acknowledgement mechanism. //When we poll or get a setting, we will receive _both_ a config packet and an ACK //If the poll or get request is not valid, we will receive _only_ a NACK //If we are trying to get or poll a setting, then packetCfg.len will be 0 or 1 when the packetCfg is _sent_. //If we poll the setting for a particular port using UBX-CFG-PRT then .len will be 1 initially //For all other gets or polls, .len will be 0 initially //(It would be possible for .len to be 2 _if_ we were using UBX-CFG-MSG to poll the settings for a particular message - but we don't use that (currently)) //If the get or poll _fails_, i.e. is NACK'd, then packetCfg.len could still be 0 or 1 after the NACK is received //But if the get or poll is ACK'd, then packetCfg.len will have been updated by the incoming data and will always be at least 2 //If we are going to set the value for a setting, then packetCfg.len will be at least 3 when the packetCfg is _sent_. //(UBX-CFG-MSG appears to have the shortest set length of 3 bytes) //We need to think carefully about how interleaved PVT packets affect things. //It is entirely possible that our packetCfg and packetAck were received successfully //but while we are still in the "if (checkUblox() == true)" loop a PVT packet is processed //or _starts_ to arrive (remember that Serial data can arrive very slowly). //Returns SFE_UBLOX_STATUS_DATA_RECEIVED if we got an ACK and a valid packetCfg (module is responding with register content) //Returns SFE_UBLOX_STATUS_DATA_SENT if we got an ACK and no packetCfg (no valid packetCfg needed, module absorbs new register data) //Returns SFE_UBLOX_STATUS_FAIL if something very bad happens (e.g. a double checksum failure) //Returns SFE_UBLOX_STATUS_COMMAND_NACK if the packet was not-acknowledged (NACK) //Returns SFE_UBLOX_STATUS_CRC_FAIL if we had a checksum failure //Returns SFE_UBLOX_STATUS_TIMEOUT if we timed out //Returns SFE_UBLOX_STATUS_DATA_OVERWRITTEN if we got an ACK and a valid packetCfg but that the packetCfg has been // or is currently being overwritten (remember that Serial data can arrive very slowly) sfe_ublox_status_e SFE_UBLOX_GPS::waitForACKResponse(ubxPacket *outgoingUBX, uint8_t requestedClass, uint8_t requestedID, uint16_t maxTime) { outgoingUBX->valid = SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED; //This will go VALID (or NOT_VALID) when we receive a response to the packet we sent packetAck.valid = SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED; packetBuf.valid = SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED; outgoingUBX->classAndIDmatch = SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED; // This will go VALID (or NOT_VALID) when we receive a packet that matches the requested class and ID packetAck.classAndIDmatch = SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED; packetBuf.classAndIDmatch = SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED; unsigned long startTime = millis(); while (millis() - startTime < maxTime) { if (checkUbloxInternal(outgoingUBX, requestedClass, requestedID) == true) //See if new data is available. Process bytes as they come in. { // If both the outgoingUBX->classAndIDmatch and packetAck.classAndIDmatch are VALID // and outgoingUBX->valid is _still_ VALID and the class and ID _still_ match // then we can be confident that the data in outgoingUBX is valid if ((outgoingUBX->classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_VALID) && (packetAck.classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_VALID) && (outgoingUBX->valid == SFE_UBLOX_PACKET_VALIDITY_VALID) && (outgoingUBX->cls == requestedClass) && (outgoingUBX->id == requestedID)) { if (_printDebug == true) { _debugSerial->print(F("waitForACKResponse: valid data and valid ACK received after ")); _debugSerial->print(millis() - startTime); _debugSerial->println(F(" msec")); } return (SFE_UBLOX_STATUS_DATA_RECEIVED); //We received valid data and a correct ACK! } // We can be confident that the data packet (if we are going to get one) will always arrive // before the matching ACK. So if we sent a config packet which only produces an ACK // then outgoingUBX->classAndIDmatch will be NOT_DEFINED and the packetAck.classAndIDmatch will VALID. // We should not check outgoingUBX->valid, outgoingUBX->cls or outgoingUBX->id // as these may have been changed by a PVT packet. else if ((outgoingUBX->classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED) && (packetAck.classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_VALID)) { if (_printDebug == true) { _debugSerial->print(F("waitForACKResponse: no data and valid ACK after ")); _debugSerial->print(millis() - startTime); _debugSerial->println(F(" msec")); } return (SFE_UBLOX_STATUS_DATA_SENT); //We got an ACK but no data... } // If both the outgoingUBX->classAndIDmatch and packetAck.classAndIDmatch are VALID // but the outgoingUBX->cls or ID no longer match then we can be confident that we had // valid data but it has been or is currently being overwritten by another packet (e.g. PVT). // If (e.g.) a PVT packet is _being_ received: outgoingUBX->valid will be NOT_DEFINED // If (e.g.) a PVT packet _has been_ received: outgoingUBX->valid will be VALID (or just possibly NOT_VALID) // So we cannot use outgoingUBX->valid as part of this check. // Note: the addition of packetBuf should make this check redundant! else if ((outgoingUBX->classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_VALID) && (packetAck.classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_VALID) && !((outgoingUBX->cls != requestedClass) || (outgoingUBX->id != requestedID))) { if (_printDebug == true) { _debugSerial->print(F("waitForACKResponse: data being OVERWRITTEN after ")); _debugSerial->print(millis() - startTime); _debugSerial->println(F(" msec")); } return (SFE_UBLOX_STATUS_DATA_OVERWRITTEN); // Data was valid but has been or is being overwritten } // If packetAck.classAndIDmatch is VALID but both outgoingUBX->valid and outgoingUBX->classAndIDmatch // are NOT_VALID then we can be confident we have had a checksum failure on the data packet else if ((packetAck.classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_VALID) && (outgoingUBX->classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_NOT_VALID) && (outgoingUBX->valid == SFE_UBLOX_PACKET_VALIDITY_NOT_VALID)) { if (_printDebug == true) { _debugSerial->print(F("waitForACKResponse: CRC failed after ")); _debugSerial->print(millis() - startTime); _debugSerial->println(F(" msec")); } return (SFE_UBLOX_STATUS_CRC_FAIL); //Checksum fail } // If our packet was not-acknowledged (NACK) we do not receive a data packet - we only get the NACK. // So you would expect outgoingUBX->valid and outgoingUBX->classAndIDmatch to still be NOT_DEFINED // But if a full PVT packet arrives afterwards outgoingUBX->valid could be VALID (or just possibly NOT_VALID) // but outgoingUBX->cls and outgoingUBX->id would not match... // So I think this is telling us we need a special state for packetAck.classAndIDmatch to tell us // the packet was definitely NACK'd otherwise we are possibly just guessing... // Note: the addition of packetBuf changes the logic of this, but we'll leave the code as is for now. else if (packetAck.classAndIDmatch == SFE_UBLOX_PACKET_NOTACKNOWLEDGED) { if (_printDebug == true) { _debugSerial->print(F("waitForACKResponse: data was NOTACKNOWLEDGED (NACK) after ")); _debugSerial->print(millis() - startTime); _debugSerial->println(F(" msec")); } return (SFE_UBLOX_STATUS_COMMAND_NACK); //We received a NACK! } // If the outgoingUBX->classAndIDmatch is VALID but the packetAck.classAndIDmatch is NOT_VALID // then the ack probably had a checksum error. We will take a gamble and return DATA_RECEIVED. // If we were playing safe, we should return FAIL instead else if ((outgoingUBX->classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_VALID) && (packetAck.classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_NOT_VALID) && (outgoingUBX->valid == SFE_UBLOX_PACKET_VALIDITY_VALID) && (outgoingUBX->cls == requestedClass) && (outgoingUBX->id == requestedID)) { if (_printDebug == true) { _debugSerial->print(F("waitForACKResponse: VALID data and INVALID ACK received after ")); _debugSerial->print(millis() - startTime); _debugSerial->println(F(" msec")); } return (SFE_UBLOX_STATUS_DATA_RECEIVED); //We received valid data and an invalid ACK! } // If the outgoingUBX->classAndIDmatch is NOT_VALID and the packetAck.classAndIDmatch is NOT_VALID // then we return a FAIL. This must be a double checksum failure? else if ((outgoingUBX->classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_NOT_VALID) && (packetAck.classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_NOT_VALID)) { if (_printDebug == true) { _debugSerial->print(F("waitForACKResponse: INVALID data and INVALID ACK received after ")); _debugSerial->print(millis() - startTime); _debugSerial->println(F(" msec")); } return (SFE_UBLOX_STATUS_FAIL); //We received invalid data and an invalid ACK! } // If the outgoingUBX->classAndIDmatch is VALID and the packetAck.classAndIDmatch is NOT_DEFINED // then the ACK has not yet been received and we should keep waiting for it else if ((outgoingUBX->classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_VALID) && (packetAck.classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED)) { if (_printDebug == true) { _debugSerial->print(F("waitForACKResponse: valid data after ")); _debugSerial->print(millis() - startTime); _debugSerial->println(F(" msec. Waiting for ACK.")); } } } //checkUbloxInternal == true delayMicroseconds(500); } //while (millis() - startTime < maxTime) // We have timed out... // If the outgoingUBX->classAndIDmatch is VALID then we can take a gamble and return DATA_RECEIVED // even though we did not get an ACK if ((outgoingUBX->classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_VALID) && (packetAck.classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED) && (outgoingUBX->valid == SFE_UBLOX_PACKET_VALIDITY_VALID) && (outgoingUBX->cls == requestedClass) && (outgoingUBX->id == requestedID)) { if (_printDebug == true) { _debugSerial->print(F("waitForACKResponse: TIMEOUT with valid data after ")); _debugSerial->print(millis() - startTime); _debugSerial->println(F(" msec. ")); } return (SFE_UBLOX_STATUS_DATA_RECEIVED); //We received valid data... But no ACK! } if (_printDebug == true) { _debugSerial->print(F("waitForACKResponse: TIMEOUT after ")); _debugSerial->print(millis() - startTime); _debugSerial->println(F(" msec.")); } return (SFE_UBLOX_STATUS_TIMEOUT); } //For non-CFG queries no ACK is sent so we use this function //Returns SFE_UBLOX_STATUS_DATA_RECEIVED if we got a config packet full of response data that has CLS/ID match to our query packet //Returns SFE_UBLOX_STATUS_CRC_FAIL if we got a corrupt config packet that has CLS/ID match to our query packet //Returns SFE_UBLOX_STATUS_TIMEOUT if we timed out //Returns SFE_UBLOX_STATUS_DATA_OVERWRITTEN if we got an a valid packetCfg but that the packetCfg has been // or is currently being overwritten (remember that Serial data can arrive very slowly) sfe_ublox_status_e SFE_UBLOX_GPS::waitForNoACKResponse(ubxPacket *outgoingUBX, uint8_t requestedClass, uint8_t requestedID, uint16_t maxTime) { outgoingUBX->valid = SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED; //This will go VALID (or NOT_VALID) when we receive a response to the packet we sent packetAck.valid = SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED; packetBuf.valid = SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED; outgoingUBX->classAndIDmatch = SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED; // This will go VALID (or NOT_VALID) when we receive a packet that matches the requested class and ID packetAck.classAndIDmatch = SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED; packetBuf.classAndIDmatch = SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED; unsigned long startTime = millis(); while (millis() - startTime < maxTime) { if (checkUbloxInternal(outgoingUBX, requestedClass, requestedID) == true) //See if new data is available. Process bytes as they come in. { // If outgoingUBX->classAndIDmatch is VALID // and outgoingUBX->valid is _still_ VALID and the class and ID _still_ match // then we can be confident that the data in outgoingUBX is valid if ((outgoingUBX->classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_VALID) && (outgoingUBX->valid == SFE_UBLOX_PACKET_VALIDITY_VALID) && (outgoingUBX->cls == requestedClass) && (outgoingUBX->id == requestedID)) { if (_printDebug == true) { _debugSerial->print(F("waitForNoACKResponse: valid data with CLS/ID match after ")); _debugSerial->print(millis() - startTime); _debugSerial->println(F(" msec")); } return (SFE_UBLOX_STATUS_DATA_RECEIVED); //We received valid data! } // If the outgoingUBX->classAndIDmatch is VALID // but the outgoingUBX->cls or ID no longer match then we can be confident that we had // valid data but it has been or is currently being overwritten by another packet (e.g. PVT). // If (e.g.) a PVT packet is _being_ received: outgoingUBX->valid will be NOT_DEFINED // If (e.g.) a PVT packet _has been_ received: outgoingUBX->valid will be VALID (or just possibly NOT_VALID) // So we cannot use outgoingUBX->valid as part of this check. // Note: the addition of packetBuf should make this check redundant! else if ((outgoingUBX->classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_VALID) && !((outgoingUBX->cls != requestedClass) || (outgoingUBX->id != requestedID))) { if (_printDebug == true) { _debugSerial->print(F("waitForNoACKResponse: data being OVERWRITTEN after ")); _debugSerial->print(millis() - startTime); _debugSerial->println(F(" msec")); } return (SFE_UBLOX_STATUS_DATA_OVERWRITTEN); // Data was valid but has been or is being overwritten } // If outgoingUBX->classAndIDmatch is NOT_DEFINED // and outgoingUBX->valid is VALID then this must be (e.g.) a PVT packet else if ((outgoingUBX->classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_NOT_DEFINED) && (outgoingUBX->valid == SFE_UBLOX_PACKET_VALIDITY_VALID)) { if (_printDebug == true) { _debugSerial->print(F("waitForNoACKResponse: valid but UNWANTED data after ")); _debugSerial->print(millis() - startTime); _debugSerial->print(F(" msec. Class: ")); _debugSerial->print(outgoingUBX->cls); _debugSerial->print(F(" ID: ")); _debugSerial->print(outgoingUBX->id); } } // If the outgoingUBX->classAndIDmatch is NOT_VALID then we return CRC failure else if (outgoingUBX->classAndIDmatch == SFE_UBLOX_PACKET_VALIDITY_NOT_VALID) { if (_printDebug == true) { _debugSerial->print(F("waitForNoACKResponse: CLS/ID match but failed CRC after ")); _debugSerial->print(millis() - startTime); _debugSerial->println(F(" msec")); } return (SFE_UBLOX_STATUS_CRC_FAIL); //We received invalid data } } delayMicroseconds(500); } if (_printDebug == true) { _debugSerial->print(F("waitForNoACKResponse: TIMEOUT after ")); _debugSerial->print(millis() - startTime); _debugSerial->println(F(" msec. No packet received.")); } return (SFE_UBLOX_STATUS_TIMEOUT); } //Save current configuration to flash and BBR (battery backed RAM) //This still works but it is the old way of configuring ublox modules. See getVal and setVal for the new methods boolean SFE_UBLOX_GPS::saveConfiguration(uint16_t maxWait) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_CFG; packetCfg.len = 12; packetCfg.startingSpot = 0; //Clear packet payload for (uint8_t x = 0; x < packetCfg.len; x++) packetCfg.payload[x] = 0; packetCfg.payload[4] = 0xFF; //Set any bit in the saveMask field to save current config to Flash and BBR packetCfg.payload[5] = 0xFF; return (sendCommand(&packetCfg, maxWait) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Save the selected configuration sub-sections to flash and BBR (battery backed RAM) //This still works but it is the old way of configuring ublox modules. See getVal and setVal for the new methods boolean SFE_UBLOX_GPS::saveConfigSelective(uint32_t configMask, uint16_t maxWait) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_CFG; packetCfg.len = 12; packetCfg.startingSpot = 0; //Clear packet payload for (uint8_t x = 0; x < packetCfg.len; x++) packetCfg.payload[x] = 0; packetCfg.payload[4] = configMask & 0xFF; //Set the appropriate bits in the saveMask field to save current config to Flash and BBR packetCfg.payload[5] = (configMask >> 8) & 0xFF; packetCfg.payload[6] = (configMask >> 16) & 0xFF; packetCfg.payload[7] = (configMask >> 24) & 0xFF; return (sendCommand(&packetCfg, maxWait) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Reset module to factory defaults //This still works but it is the old way of configuring ublox modules. See getVal and setVal for the new methods boolean SFE_UBLOX_GPS::factoryDefault(uint16_t maxWait) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_CFG; packetCfg.len = 12; packetCfg.startingSpot = 0; //Clear packet payload for (uint8_t x = 0; x < packetCfg.len; x++) packetCfg.payload[x] = 0; packetCfg.payload[0] = 0xFF; //Set any bit in the clearMask field to clear saved config packetCfg.payload[1] = 0xFF; packetCfg.payload[8] = 0xFF; //Set any bit in the loadMask field to discard current config and rebuild from lower non-volatile memory layers packetCfg.payload[9] = 0xFF; return (sendCommand(&packetCfg, maxWait) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Given a group, ID and size, return the value of this config spot //The 32-bit key is put together from group/ID/size. See other getVal to send key directly. //Configuration of modern Ublox modules is now done via getVal/setVal/delVal, ie protocol v27 and above found on ZED-F9P uint8_t SFE_UBLOX_GPS::getVal8(uint16_t group, uint16_t id, uint8_t size, uint8_t layer, uint16_t maxWait) { //Create key uint32_t key = 0; key |= (uint32_t)id; key |= (uint32_t)group << 16; key |= (uint32_t)size << 28; if (_printDebug == true) { _debugSerial->print(F("key: 0x")); _debugSerial->print(key, HEX); _debugSerial->println(); } return getVal8(key, layer, maxWait); } //Given a key, return its value //This function takes a full 32-bit key //Default layer is BBR //Configuration of modern Ublox modules is now done via getVal/setVal/delVal, ie protocol v27 and above found on ZED-F9P uint8_t SFE_UBLOX_GPS::getVal8(uint32_t key, uint8_t layer, uint16_t maxWait) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_VALGET; packetCfg.len = 4 + 4 * 1; //While multiple keys are allowed, we will send only one key at a time packetCfg.startingSpot = 0; //Clear packet payload for (uint8_t x = 0; x < packetCfg.len; x++) packetCfg.payload[x] = 0; //VALGET uses different memory layer definitions to VALSET //because it can only return the value for one layer. //So we need to fiddle the layer here. //And just to complicate things further, the ZED-F9P only responds //correctly to layer 0 (RAM) and layer 7 (Default)! uint8_t getLayer = 7; // 7 is the "Default Layer" if ((layer & VAL_LAYER_RAM) == VAL_LAYER_RAM) // Did the user request the RAM layer? { getLayer = 0; // Layer 0 is RAM } payloadCfg[0] = 0; //Message Version - set to 0 payloadCfg[1] = getLayer; //Layer //Load key into outgoing payload payloadCfg[4] = key >> 8 * 0; //Key LSB payloadCfg[5] = key >> 8 * 1; payloadCfg[6] = key >> 8 * 2; payloadCfg[7] = key >> 8 * 3; if (_printDebug == true) { _debugSerial->print(F("key: 0x")); _debugSerial->print(key, HEX); _debugSerial->println(); } //Send VALGET command with this key sfe_ublox_status_e retVal = sendCommand(&packetCfg, maxWait); if (_printDebug == true) { _debugSerial->print(F("getVal8: sendCommand returned: ")); _debugSerial->println(statusString(retVal)); } if (retVal != SFE_UBLOX_STATUS_DATA_RECEIVED) // We are expecting data and an ACK return (0); //If command send fails then bail //Verify the response is the correct length as compared to what the user called (did the module respond with 8-bits but the user called getVal32?) //Response is 8 bytes plus cfg data //if(packet->len > 8+1) //Pull the requested value from the response //Response starts at 4+1*N with the 32-bit key so the actual data we're looking for is at 8+1*N return (extractByte(8)); } //Given a key, set a 16-bit value //This function takes a full 32-bit key //Default layer is BBR //Configuration of modern Ublox modules is now done via getVal/setVal/delVal, ie protocol v27 and above found on ZED-F9P uint8_t SFE_UBLOX_GPS::setVal(uint32_t key, uint16_t value, uint8_t layer, uint16_t maxWait) { return setVal16(key, value, layer, maxWait); } //Given a key, set a 16-bit value //This function takes a full 32-bit key //Default layer is BBR //Configuration of modern Ublox modules is now done via getVal/setVal/delVal, ie protocol v27 and above found on ZED-F9P uint8_t SFE_UBLOX_GPS::setVal16(uint32_t key, uint16_t value, uint8_t layer, uint16_t maxWait) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_VALSET; packetCfg.len = 4 + 4 + 2; //4 byte header, 4 byte key ID, 2 bytes of value packetCfg.startingSpot = 0; //Clear packet payload for (uint16_t x = 0; x < packetCfg.len; x++) packetCfg.payload[x] = 0; payloadCfg[0] = 0; //Message Version - set to 0 payloadCfg[1] = layer; //By default we ask for the BBR layer //Load key into outgoing payload payloadCfg[4] = key >> 8 * 0; //Key LSB payloadCfg[5] = key >> 8 * 1; payloadCfg[6] = key >> 8 * 2; payloadCfg[7] = key >> 8 * 3; //Load user's value payloadCfg[8] = value >> 8 * 0; //Value LSB payloadCfg[9] = value >> 8 * 1; //Send VALSET command with this key and value return (sendCommand(&packetCfg, maxWait) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Given a key, set an 8-bit value //This function takes a full 32-bit key //Default layer is BBR //Configuration of modern Ublox modules is now done via getVal/setVal/delVal, ie protocol v27 and above found on ZED-F9P uint8_t SFE_UBLOX_GPS::setVal8(uint32_t key, uint8_t value, uint8_t layer, uint16_t maxWait) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_VALSET; packetCfg.len = 4 + 4 + 1; //4 byte header, 4 byte key ID, 1 byte value packetCfg.startingSpot = 0; //Clear packet payload for (uint16_t x = 0; x < packetCfg.len; x++) packetCfg.payload[x] = 0; payloadCfg[0] = 0; //Message Version - set to 0 payloadCfg[1] = layer; //By default we ask for the BBR layer //Load key into outgoing payload payloadCfg[4] = key >> 8 * 0; //Key LSB payloadCfg[5] = key >> 8 * 1; payloadCfg[6] = key >> 8 * 2; payloadCfg[7] = key >> 8 * 3; //Load user's value payloadCfg[8] = value; //Value //Send VALSET command with this key and value return (sendCommand(&packetCfg, maxWait) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Given a key, set a 32-bit value //This function takes a full 32-bit key //Default layer is BBR //Configuration of modern Ublox modules is now done via getVal/setVal/delVal, ie protocol v27 and above found on ZED-F9P uint8_t SFE_UBLOX_GPS::setVal32(uint32_t key, uint32_t value, uint8_t layer, uint16_t maxWait) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_VALSET; packetCfg.len = 4 + 4 + 4; //4 byte header, 4 byte key ID, 4 bytes of value packetCfg.startingSpot = 0; //Clear packet payload for (uint16_t x = 0; x < packetCfg.len; x++) packetCfg.payload[x] = 0; payloadCfg[0] = 0; //Message Version - set to 0 payloadCfg[1] = layer; //By default we ask for the BBR layer //Load key into outgoing payload payloadCfg[4] = key >> 8 * 0; //Key LSB payloadCfg[5] = key >> 8 * 1; payloadCfg[6] = key >> 8 * 2; payloadCfg[7] = key >> 8 * 3; //Load user's value payloadCfg[8] = value >> 8 * 0; //Value LSB payloadCfg[9] = value >> 8 * 1; payloadCfg[10] = value >> 8 * 2; payloadCfg[11] = value >> 8 * 3; //Send VALSET command with this key and value return (sendCommand(&packetCfg, maxWait) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Start defining a new UBX-CFG-VALSET ubxPacket //This function takes a full 32-bit key and 32-bit value //Default layer is BBR //Configuration of modern Ublox modules is now done via getVal/setVal/delVal, ie protocol v27 and above found on ZED-F9P uint8_t SFE_UBLOX_GPS::newCfgValset32(uint32_t key, uint32_t value, uint8_t layer) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_VALSET; packetCfg.len = 4 + 4 + 4; //4 byte header, 4 byte key ID, 4 bytes of value packetCfg.startingSpot = 0; //Clear packet payload for (uint16_t x = 0; x < MAX_PAYLOAD_SIZE; x++) packetCfg.payload[x] = 0; payloadCfg[0] = 0; //Message Version - set to 0 payloadCfg[1] = layer; //By default we ask for the BBR layer //Load key into outgoing payload payloadCfg[4] = key >> 8 * 0; //Key LSB payloadCfg[5] = key >> 8 * 1; payloadCfg[6] = key >> 8 * 2; payloadCfg[7] = key >> 8 * 3; //Load user's value payloadCfg[8] = value >> 8 * 0; //Value LSB payloadCfg[9] = value >> 8 * 1; payloadCfg[10] = value >> 8 * 2; payloadCfg[11] = value >> 8 * 3; //All done return (true); } //Start defining a new UBX-CFG-VALSET ubxPacket //This function takes a full 32-bit key and 16-bit value //Default layer is BBR //Configuration of modern Ublox modules is now done via getVal/setVal/delVal, ie protocol v27 and above found on ZED-F9P uint8_t SFE_UBLOX_GPS::newCfgValset16(uint32_t key, uint16_t value, uint8_t layer) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_VALSET; packetCfg.len = 4 + 4 + 2; //4 byte header, 4 byte key ID, 2 bytes of value packetCfg.startingSpot = 0; //Clear packet payload for (uint16_t x = 0; x < MAX_PAYLOAD_SIZE; x++) packetCfg.payload[x] = 0; payloadCfg[0] = 0; //Message Version - set to 0 payloadCfg[1] = layer; //By default we ask for the BBR layer //Load key into outgoing payload payloadCfg[4] = key >> 8 * 0; //Key LSB payloadCfg[5] = key >> 8 * 1; payloadCfg[6] = key >> 8 * 2; payloadCfg[7] = key >> 8 * 3; //Load user's value payloadCfg[8] = value >> 8 * 0; //Value LSB payloadCfg[9] = value >> 8 * 1; //All done return (true); } //Start defining a new UBX-CFG-VALSET ubxPacket //This function takes a full 32-bit key and 8-bit value //Default layer is BBR //Configuration of modern Ublox modules is now done via getVal/setVal/delVal, ie protocol v27 and above found on ZED-F9P uint8_t SFE_UBLOX_GPS::newCfgValset8(uint32_t key, uint8_t value, uint8_t layer) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_VALSET; packetCfg.len = 4 + 4 + 1; //4 byte header, 4 byte key ID, 1 byte value packetCfg.startingSpot = 0; //Clear packet payload for (uint16_t x = 0; x < MAX_PAYLOAD_SIZE; x++) packetCfg.payload[x] = 0; payloadCfg[0] = 0; //Message Version - set to 0 payloadCfg[1] = layer; //By default we ask for the BBR layer //Load key into outgoing payload payloadCfg[4] = key >> 8 * 0; //Key LSB payloadCfg[5] = key >> 8 * 1; payloadCfg[6] = key >> 8 * 2; payloadCfg[7] = key >> 8 * 3; //Load user's value payloadCfg[8] = value; //Value //All done return (true); } //Add another keyID and value to an existing UBX-CFG-VALSET ubxPacket //This function takes a full 32-bit key and 32-bit value uint8_t SFE_UBLOX_GPS::addCfgValset32(uint32_t key, uint32_t value) { //Load key into outgoing payload payloadCfg[packetCfg.len + 0] = key >> 8 * 0; //Key LSB payloadCfg[packetCfg.len + 1] = key >> 8 * 1; payloadCfg[packetCfg.len + 2] = key >> 8 * 2; payloadCfg[packetCfg.len + 3] = key >> 8 * 3; //Load user's value payloadCfg[packetCfg.len + 4] = value >> 8 * 0; //Value LSB payloadCfg[packetCfg.len + 5] = value >> 8 * 1; payloadCfg[packetCfg.len + 6] = value >> 8 * 2; payloadCfg[packetCfg.len + 7] = value >> 8 * 3; //Update packet length: 4 byte key ID, 4 bytes of value packetCfg.len = packetCfg.len + 4 + 4; //All done return (true); } //Add another keyID and value to an existing UBX-CFG-VALSET ubxPacket //This function takes a full 32-bit key and 16-bit value uint8_t SFE_UBLOX_GPS::addCfgValset16(uint32_t key, uint16_t value) { //Load key into outgoing payload payloadCfg[packetCfg.len + 0] = key >> 8 * 0; //Key LSB payloadCfg[packetCfg.len + 1] = key >> 8 * 1; payloadCfg[packetCfg.len + 2] = key >> 8 * 2; payloadCfg[packetCfg.len + 3] = key >> 8 * 3; //Load user's value payloadCfg[packetCfg.len + 4] = value >> 8 * 0; //Value LSB payloadCfg[packetCfg.len + 5] = value >> 8 * 1; //Update packet length: 4 byte key ID, 2 bytes of value packetCfg.len = packetCfg.len + 4 + 2; //All done return (true); } //Add another keyID and value to an existing UBX-CFG-VALSET ubxPacket //This function takes a full 32-bit key and 8-bit value uint8_t SFE_UBLOX_GPS::addCfgValset8(uint32_t key, uint8_t value) { //Load key into outgoing payload payloadCfg[packetCfg.len + 0] = key >> 8 * 0; //Key LSB payloadCfg[packetCfg.len + 1] = key >> 8 * 1; payloadCfg[packetCfg.len + 2] = key >> 8 * 2; payloadCfg[packetCfg.len + 3] = key >> 8 * 3; //Load user's value payloadCfg[packetCfg.len + 4] = value; //Value //Update packet length: 4 byte key ID, 1 byte value packetCfg.len = packetCfg.len + 4 + 1; //All done return (true); } //Add a final keyID and value to an existing UBX-CFG-VALSET ubxPacket and send it //This function takes a full 32-bit key and 32-bit value uint8_t SFE_UBLOX_GPS::sendCfgValset32(uint32_t key, uint32_t value, uint16_t maxWait) { //Load keyID and value into outgoing payload addCfgValset32(key, value); //Send VALSET command with this key and value return (sendCommand(&packetCfg, maxWait) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Add a final keyID and value to an existing UBX-CFG-VALSET ubxPacket and send it //This function takes a full 32-bit key and 16-bit value uint8_t SFE_UBLOX_GPS::sendCfgValset16(uint32_t key, uint16_t value, uint16_t maxWait) { //Load keyID and value into outgoing payload addCfgValset16(key, value); //Send VALSET command with this key and value return (sendCommand(&packetCfg, maxWait) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Add a final keyID and value to an existing UBX-CFG-VALSET ubxPacket and send it //This function takes a full 32-bit key and 8-bit value uint8_t SFE_UBLOX_GPS::sendCfgValset8(uint32_t key, uint8_t value, uint16_t maxWait) { //Load keyID and value into outgoing payload addCfgValset8(key, value); //Send VALSET command with this key and value return (sendCommand(&packetCfg, maxWait) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Get the current TimeMode3 settings - these contain survey in statuses boolean SFE_UBLOX_GPS::getSurveyMode(uint16_t maxWait) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_TMODE3; packetCfg.len = 0; packetCfg.startingSpot = 0; return ((sendCommand(&packetCfg, maxWait)) == SFE_UBLOX_STATUS_DATA_RECEIVED); // We are expecting data and an ACK } //Control Survey-In for NEO-M8P boolean SFE_UBLOX_GPS::setSurveyMode(uint8_t mode, uint16_t observationTime, float requiredAccuracy, uint16_t maxWait) { if (getSurveyMode(maxWait) == false) //Ask module for the current TimeMode3 settings. Loads into payloadCfg. return (false); packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_TMODE3; packetCfg.len = 40; packetCfg.startingSpot = 0; //Clear packet payload for (uint8_t x = 0; x < packetCfg.len; x++) packetCfg.payload[x] = 0; //payloadCfg should be loaded with poll response. Now modify only the bits we care about payloadCfg[2] = mode; //Set mode. Survey-In and Disabled are most common. Use ECEF (not LAT/LON/ALT). //svinMinDur is U4 (uint32_t) but we'll only use a uint16_t (waiting more than 65535 seconds seems excessive!) payloadCfg[24] = observationTime & 0xFF; //svinMinDur in seconds payloadCfg[25] = observationTime >> 8; //svinMinDur in seconds payloadCfg[26] = 0; //Truncate to 16 bits payloadCfg[27] = 0; //Truncate to 16 bits //svinAccLimit is U4 (uint32_t) in 0.1mm. uint32_t svinAccLimit = (uint32_t)(requiredAccuracy * 10000.0); //Convert m to 0.1mm payloadCfg[28] = svinAccLimit & 0xFF; //svinAccLimit in 0.1mm increments payloadCfg[29] = svinAccLimit >> 8; payloadCfg[30] = svinAccLimit >> 16; payloadCfg[31] = svinAccLimit >> 24; return ((sendCommand(&packetCfg, maxWait)) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Begin Survey-In for NEO-M8P boolean SFE_UBLOX_GPS::enableSurveyMode(uint16_t observationTime, float requiredAccuracy, uint16_t maxWait) { return (setSurveyMode(SVIN_MODE_ENABLE, observationTime, requiredAccuracy, maxWait)); } //Stop Survey-In for NEO-M8P boolean SFE_UBLOX_GPS::disableSurveyMode(uint16_t maxWait) { return (setSurveyMode(SVIN_MODE_DISABLE, 0, 0, maxWait)); } //Reads survey in status and sets the global variables //for status, position valid, observation time, and mean 3D StdDev //Returns true if commands was successful boolean SFE_UBLOX_GPS::getSurveyStatus(uint16_t maxWait) { //Reset variables svin.active = false; svin.valid = false; svin.observationTime = 0; svin.meanAccuracy = 0; packetCfg.cls = UBX_CLASS_NAV; packetCfg.id = UBX_NAV_SVIN; packetCfg.len = 0; packetCfg.startingSpot = 0; if ((sendCommand(&packetCfg, maxWait)) != SFE_UBLOX_STATUS_DATA_RECEIVED) // We are expecting data and an ACK return (false); //If command send fails then bail //We got a response, now parse the bits into the svin structure //dur (Passed survey-in observation time) is U4 (uint32_t) seconds. We truncate to 16 bits //(waiting more than 65535 seconds (18.2 hours) seems excessive!) uint32_t tmpObsTime = extractLong(8); if (tmpObsTime <= 0xFFFF) { svin.observationTime = (uint16_t)tmpObsTime; } else { svin.observationTime = 0xFFFF; } // meanAcc is U4 (uint32_t) in 0.1mm. We convert this to float. uint32_t tempFloat = extractLong(28); svin.meanAccuracy = ((float)tempFloat) / 10000.0; //Convert 0.1mm to m svin.valid = payloadCfg[36]; //1 if survey-in position is valid, 0 otherwise svin.active = payloadCfg[37]; //1 if survey-in in progress, 0 otherwise return (true); } //Loads the payloadCfg array with the current protocol bits located the UBX-CFG-PRT register for a given port boolean SFE_UBLOX_GPS::getPortSettings(uint8_t portID, uint16_t maxWait) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_PRT; packetCfg.len = 1; packetCfg.startingSpot = 0; payloadCfg[0] = portID; return ((sendCommand(&packetCfg, maxWait)) == SFE_UBLOX_STATUS_DATA_RECEIVED); // We are expecting data and an ACK } //Configure a given port to output UBX, NMEA, RTCM3 or a combination thereof //Port 0=I2c, 1=UART1, 2=UART2, 3=USB, 4=SPI //Bit:0 = UBX, :1=NMEA, :5=RTCM3 boolean SFE_UBLOX_GPS::setPortOutput(uint8_t portID, uint8_t outStreamSettings, uint16_t maxWait) { //Get the current config values for this port ID if (getPortSettings(portID, maxWait) == false) return (false); //Something went wrong. Bail. packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_PRT; packetCfg.len = 20; packetCfg.startingSpot = 0; //payloadCfg is now loaded with current bytes. Change only the ones we need to payloadCfg[14] = outStreamSettings; //OutProtocolMask LSB - Set outStream bits return ((sendCommand(&packetCfg, maxWait)) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Configure a given port to input UBX, NMEA, RTCM3 or a combination thereof //Port 0=I2c, 1=UART1, 2=UART2, 3=USB, 4=SPI //Bit:0 = UBX, :1=NMEA, :5=RTCM3 boolean SFE_UBLOX_GPS::setPortInput(uint8_t portID, uint8_t inStreamSettings, uint16_t maxWait) { //Get the current config values for this port ID //This will load the payloadCfg array with current port settings if (getPortSettings(portID, maxWait) == false) return (false); //Something went wrong. Bail. packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_PRT; packetCfg.len = 20; packetCfg.startingSpot = 0; //payloadCfg is now loaded with current bytes. Change only the ones we need to payloadCfg[12] = inStreamSettings; //InProtocolMask LSB - Set inStream bits return ((sendCommand(&packetCfg, maxWait)) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Configure a port to output UBX, NMEA, RTCM3 or a combination thereof boolean SFE_UBLOX_GPS::setI2COutput(uint8_t comSettings, uint16_t maxWait) { return (setPortOutput(COM_PORT_I2C, comSettings, maxWait)); } boolean SFE_UBLOX_GPS::setUART1Output(uint8_t comSettings, uint16_t maxWait) { return (setPortOutput(COM_PORT_UART1, comSettings, maxWait)); } boolean SFE_UBLOX_GPS::setUART2Output(uint8_t comSettings, uint16_t maxWait) { return (setPortOutput(COM_PORT_UART2, comSettings, maxWait)); } boolean SFE_UBLOX_GPS::setUSBOutput(uint8_t comSettings, uint16_t maxWait) { return (setPortOutput(COM_PORT_USB, comSettings, maxWait)); } boolean SFE_UBLOX_GPS::setSPIOutput(uint8_t comSettings, uint16_t maxWait) { return (setPortOutput(COM_PORT_SPI, comSettings, maxWait)); } //Set the rate at which the module will give us an updated navigation solution //Expects a number that is the updates per second. For example 1 = 1Hz, 2 = 2Hz, etc. //Max is 40Hz(?!) boolean SFE_UBLOX_GPS::setNavigationFrequency(uint8_t navFreq, uint16_t maxWait) { //if(updateRate > 40) updateRate = 40; //Not needed: module will correct out of bounds values //Adjust the I2C polling timeout based on update rate i2cPollingWait = 1000 / (navFreq * 4); //This is the number of ms to wait between checks for new I2C data //Query the module for the latest lat/long packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_RATE; packetCfg.len = 0; packetCfg.startingSpot = 0; //This will load the payloadCfg array with current settings of the given register if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) // We are expecting data and an ACK return (false); //If command send fails then bail uint16_t measurementRate = 1000 / navFreq; //payloadCfg is now loaded with current bytes. Change only the ones we need to payloadCfg[0] = measurementRate & 0xFF; //measRate LSB payloadCfg[1] = measurementRate >> 8; //measRate MSB return ((sendCommand(&packetCfg, maxWait)) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Get the rate at which the module is outputting nav solutions uint8_t SFE_UBLOX_GPS::getNavigationFrequency(uint16_t maxWait) { //Query the module for the latest lat/long packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_RATE; packetCfg.len = 0; packetCfg.startingSpot = 0; //This will load the payloadCfg array with current settings of the given register if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) // We are expecting data and an ACK return (false); //If command send fails then bail uint16_t measurementRate = 0; //payloadCfg is now loaded with current bytes. Get what we need measurementRate = extractInt(0); //Pull from payloadCfg at measRate LSB measurementRate = 1000 / measurementRate; //This may return an int when it's a float, but I'd rather not return 4 bytes return (measurementRate); } //In case no config access to the GPS is possible and PVT is send cyclically already //set config to suitable parameters boolean SFE_UBLOX_GPS::assumeAutoPVT(boolean enabled, boolean implicitUpdate) { boolean changes = autoPVT != enabled || autoPVTImplicitUpdate != implicitUpdate; if (changes) { autoPVT = enabled; autoPVTImplicitUpdate = implicitUpdate; } return changes; } //Enable or disable automatic navigation message generation by the GPS. This changes the way getPVT //works. boolean SFE_UBLOX_GPS::setAutoPVT(boolean enable, uint16_t maxWait) { return setAutoPVT(enable, true, maxWait); } //Enable or disable automatic navigation message generation by the GPS. This changes the way getPVT //works. boolean SFE_UBLOX_GPS::setAutoPVT(boolean enable, boolean implicitUpdate, uint16_t maxWait) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_MSG; packetCfg.len = 3; packetCfg.startingSpot = 0; payloadCfg[0] = UBX_CLASS_NAV; payloadCfg[1] = UBX_NAV_PVT; payloadCfg[2] = enable ? 1 : 0; // rate relative to navigation freq. boolean ok = ((sendCommand(&packetCfg, maxWait)) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK if (ok) { autoPVT = enable; autoPVTImplicitUpdate = implicitUpdate; } moduleQueried.all = false; return ok; } //Configure a given message type for a given port (UART1, I2C, SPI, etc) boolean SFE_UBLOX_GPS::configureMessage(uint8_t msgClass, uint8_t msgID, uint8_t portID, uint8_t sendRate, uint16_t maxWait) { //Poll for the current settings for a given message packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_MSG; packetCfg.len = 2; packetCfg.startingSpot = 0; payloadCfg[0] = msgClass; payloadCfg[1] = msgID; //This will load the payloadCfg array with current settings of the given register if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) // We are expecting data and an ACK return (false); //If command send fails then bail //Now send it back with new mods packetCfg.len = 8; //payloadCfg is now loaded with current bytes. Change only the ones we need to payloadCfg[2 + portID] = sendRate; //Send rate is relative to the event a message is registered on. For example, if the rate of a navigation message is set to 2, the message is sent every 2nd navigation solution. return ((sendCommand(&packetCfg, maxWait)) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Enable a given message type, default of 1 per update rate (usually 1 per second) boolean SFE_UBLOX_GPS::enableMessage(uint8_t msgClass, uint8_t msgID, uint8_t portID, uint8_t rate, uint16_t maxWait) { return (configureMessage(msgClass, msgID, portID, rate, maxWait)); } //Disable a given message type on a given port boolean SFE_UBLOX_GPS::disableMessage(uint8_t msgClass, uint8_t msgID, uint8_t portID, uint16_t maxWait) { return (configureMessage(msgClass, msgID, portID, 0, maxWait)); } boolean SFE_UBLOX_GPS::enableNMEAMessage(uint8_t msgID, uint8_t portID, uint8_t rate, uint16_t maxWait) { return (configureMessage(UBX_CLASS_NMEA, msgID, portID, rate, maxWait)); } boolean SFE_UBLOX_GPS::disableNMEAMessage(uint8_t msgID, uint8_t portID, uint16_t maxWait) { return (enableNMEAMessage(msgID, portID, 0, maxWait)); } //Given a message number turns on a message ID for output over a given portID (UART, I2C, SPI, USB, etc) //To disable a message, set secondsBetween messages to 0 //Note: This function will return false if the message is already enabled //For base station RTK output we need to enable various sentences //NEO-M8P has four: //1005 = 0xF5 0x05 - Stationary RTK reference ARP //1077 = 0xF5 0x4D - GPS MSM7 //1087 = 0xF5 0x57 - GLONASS MSM7 //1230 = 0xF5 0xE6 - GLONASS code-phase biases, set to once every 10 seconds //ZED-F9P has six: //1005, 1074, 1084, 1094, 1124, 1230 //Much of this configuration is not documented and instead discerned from u-center binary console boolean SFE_UBLOX_GPS::enableRTCMmessage(uint8_t messageNumber, uint8_t portID, uint8_t sendRate, uint16_t maxWait) { return (configureMessage(UBX_RTCM_MSB, messageNumber, portID, sendRate, maxWait)); } //Disable a given message on a given port by setting secondsBetweenMessages to zero boolean SFE_UBLOX_GPS::disableRTCMmessage(uint8_t messageNumber, uint8_t portID, uint16_t maxWait) { return (enableRTCMmessage(messageNumber, portID, 0, maxWait)); } //Add a new geofence using UBX-CFG-GEOFENCE boolean SFE_UBLOX_GPS::addGeofence(int32_t latitude, int32_t longitude, uint32_t radius, byte confidence, byte pinPolarity, byte pin, uint16_t maxWait) { if (currentGeofenceParams.numFences >= 4) return (false); // Quit if we already have four geofences defined // Store the new geofence parameters currentGeofenceParams.lats[currentGeofenceParams.numFences] = latitude; currentGeofenceParams.longs[currentGeofenceParams.numFences] = longitude; currentGeofenceParams.rads[currentGeofenceParams.numFences] = radius; currentGeofenceParams.numFences = currentGeofenceParams.numFences + 1; // Increment the number of fences packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_GEOFENCE; packetCfg.len = (currentGeofenceParams.numFences * 12) + 8; packetCfg.startingSpot = 0; payloadCfg[0] = 0; // Message version = 0x00 payloadCfg[1] = currentGeofenceParams.numFences; // numFences payloadCfg[2] = confidence; // confLvl = Confidence level 0-4 (none, 68%, 95%, 99.7%, 99.99%) payloadCfg[3] = 0; // reserved1 if (pin > 0) { payloadCfg[4] = 1; // enable PIO combined fence state } else { payloadCfg[4] = 0; // disable PIO combined fence state } payloadCfg[5] = pinPolarity; // PIO pin polarity (0 = low means inside, 1 = low means outside (or unknown)) payloadCfg[6] = pin; // PIO pin payloadCfg[7] = 0; //reserved2 payloadCfg[8] = currentGeofenceParams.lats[0] & 0xFF; payloadCfg[9] = currentGeofenceParams.lats[0] >> 8; payloadCfg[10] = currentGeofenceParams.lats[0] >> 16; payloadCfg[11] = currentGeofenceParams.lats[0] >> 24; payloadCfg[12] = currentGeofenceParams.longs[0] & 0xFF; payloadCfg[13] = currentGeofenceParams.longs[0] >> 8; payloadCfg[14] = currentGeofenceParams.longs[0] >> 16; payloadCfg[15] = currentGeofenceParams.longs[0] >> 24; payloadCfg[16] = currentGeofenceParams.rads[0] & 0xFF; payloadCfg[17] = currentGeofenceParams.rads[0] >> 8; payloadCfg[18] = currentGeofenceParams.rads[0] >> 16; payloadCfg[19] = currentGeofenceParams.rads[0] >> 24; if (currentGeofenceParams.numFences >= 2) { payloadCfg[20] = currentGeofenceParams.lats[1] & 0xFF; payloadCfg[21] = currentGeofenceParams.lats[1] >> 8; payloadCfg[22] = currentGeofenceParams.lats[1] >> 16; payloadCfg[23] = currentGeofenceParams.lats[1] >> 24; payloadCfg[24] = currentGeofenceParams.longs[1] & 0xFF; payloadCfg[25] = currentGeofenceParams.longs[1] >> 8; payloadCfg[26] = currentGeofenceParams.longs[1] >> 16; payloadCfg[27] = currentGeofenceParams.longs[1] >> 24; payloadCfg[28] = currentGeofenceParams.rads[1] & 0xFF; payloadCfg[29] = currentGeofenceParams.rads[1] >> 8; payloadCfg[30] = currentGeofenceParams.rads[1] >> 16; payloadCfg[31] = currentGeofenceParams.rads[1] >> 24; } if (currentGeofenceParams.numFences >= 3) { payloadCfg[32] = currentGeofenceParams.lats[2] & 0xFF; payloadCfg[33] = currentGeofenceParams.lats[2] >> 8; payloadCfg[34] = currentGeofenceParams.lats[2] >> 16; payloadCfg[35] = currentGeofenceParams.lats[2] >> 24; payloadCfg[36] = currentGeofenceParams.longs[2] & 0xFF; payloadCfg[37] = currentGeofenceParams.longs[2] >> 8; payloadCfg[38] = currentGeofenceParams.longs[2] >> 16; payloadCfg[39] = currentGeofenceParams.longs[2] >> 24; payloadCfg[40] = currentGeofenceParams.rads[2] & 0xFF; payloadCfg[41] = currentGeofenceParams.rads[2] >> 8; payloadCfg[42] = currentGeofenceParams.rads[2] >> 16; payloadCfg[43] = currentGeofenceParams.rads[2] >> 24; } if (currentGeofenceParams.numFences >= 4) { payloadCfg[44] = currentGeofenceParams.lats[3] & 0xFF; payloadCfg[45] = currentGeofenceParams.lats[3] >> 8; payloadCfg[46] = currentGeofenceParams.lats[3] >> 16; payloadCfg[47] = currentGeofenceParams.lats[3] >> 24; payloadCfg[48] = currentGeofenceParams.longs[3] & 0xFF; payloadCfg[49] = currentGeofenceParams.longs[3] >> 8; payloadCfg[50] = currentGeofenceParams.longs[3] >> 16; payloadCfg[51] = currentGeofenceParams.longs[3] >> 24; payloadCfg[52] = currentGeofenceParams.rads[3] & 0xFF; payloadCfg[53] = currentGeofenceParams.rads[3] >> 8; payloadCfg[54] = currentGeofenceParams.rads[3] >> 16; payloadCfg[55] = currentGeofenceParams.rads[3] >> 24; } return ((sendCommand(&packetCfg, maxWait)) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Clear all geofences using UBX-CFG-GEOFENCE boolean SFE_UBLOX_GPS::clearGeofences(uint16_t maxWait) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_GEOFENCE; packetCfg.len = 8; packetCfg.startingSpot = 0; payloadCfg[0] = 0; // Message version = 0x00 payloadCfg[1] = 0; // numFences payloadCfg[2] = 0; // confLvl payloadCfg[3] = 0; // reserved1 payloadCfg[4] = 0; // disable PIO combined fence state payloadCfg[5] = 0; // PIO pin polarity (0 = low means inside, 1 = low means outside (or unknown)) payloadCfg[6] = 0; // PIO pin payloadCfg[7] = 0; //reserved2 currentGeofenceParams.numFences = 0; // Zero the number of geofences currently in use return ((sendCommand(&packetCfg, maxWait)) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Clear the antenna control settings using UBX-CFG-ANT //This function is hopefully redundant but may be needed to release //any PIO pins pre-allocated for antenna functions boolean SFE_UBLOX_GPS::clearAntPIO(uint16_t maxWait) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_ANT; packetCfg.len = 4; packetCfg.startingSpot = 0; payloadCfg[0] = 0x10; // Antenna flag mask: set the recovery bit payloadCfg[1] = 0; payloadCfg[2] = 0xFF; // Antenna pin configuration: set pinSwitch and pinSCD to 31 payloadCfg[3] = 0xFF; // Antenna pin configuration: set pinOCD to 31, set reconfig bit return ((sendCommand(&packetCfg, maxWait)) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Returns the combined geofence state using UBX-NAV-GEOFENCE boolean SFE_UBLOX_GPS::getGeofenceState(geofenceState &currentGeofenceState, uint16_t maxWait) { packetCfg.cls = UBX_CLASS_NAV; packetCfg.id = UBX_NAV_GEOFENCE; packetCfg.len = 0; packetCfg.startingSpot = 0; //Ask module for the geofence status. Loads into payloadCfg. if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) // We are expecting data and an ACK return (false); currentGeofenceState.status = payloadCfg[5]; // Extract the status currentGeofenceState.numFences = payloadCfg[6]; // Extract the number of geofences currentGeofenceState.combState = payloadCfg[7]; // Extract the combined state of all geofences if (currentGeofenceState.numFences > 0) currentGeofenceState.states[0] = payloadCfg[8]; // Extract geofence 1 state if (currentGeofenceState.numFences > 1) currentGeofenceState.states[1] = payloadCfg[10]; // Extract geofence 2 state if (currentGeofenceState.numFences > 2) currentGeofenceState.states[2] = payloadCfg[12]; // Extract geofence 3 state if (currentGeofenceState.numFences > 3) currentGeofenceState.states[3] = payloadCfg[14]; // Extract geofence 4 state return (true); } //Power Save Mode //Enables/Disables Low Power Mode using UBX-CFG-RXM boolean SFE_UBLOX_GPS::powerSaveMode(bool power_save, uint16_t maxWait) { // Let's begin by checking the Protocol Version as UBX_CFG_RXM is not supported on the ZED (protocol >= 27) uint8_t protVer = getProtocolVersionHigh(maxWait); /* if (_printDebug == true) { _debugSerial->print(F("Protocol version is ")); _debugSerial->println(protVer); } */ if (protVer >= 27) { if (_printDebug == true) { _debugSerial->println(F("powerSaveMode (UBX-CFG-RXM) is not supported by this protocol version")); } return (false); } // Now let's change the power setting using UBX-CFG-RXM packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_RXM; packetCfg.len = 0; packetCfg.startingSpot = 0; //Ask module for the current power management settings. Loads into payloadCfg. if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) // We are expecting data and an ACK return (false); if (power_save) { payloadCfg[1] = 1; // Power Save Mode } else { payloadCfg[1] = 0; // Continuous Mode } packetCfg.len = 2; packetCfg.startingSpot = 0; return (sendCommand(&packetCfg, maxWait) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } // Get Power Save Mode // Returns the current Low Power Mode using UBX-CFG-RXM // Returns 255 if the sendCommand fails uint8_t SFE_UBLOX_GPS::getPowerSaveMode(uint16_t maxWait) { // Let's begin by checking the Protocol Version as UBX_CFG_RXM is not supported on the ZED (protocol >= 27) uint8_t protVer = getProtocolVersionHigh(maxWait); /* if (_printDebug == true) { _debugSerial->print(F("Protocol version is ")); _debugSerial->println(protVer); } */ if (protVer >= 27) { if (_printDebug == true) { _debugSerial->println(F("powerSaveMode (UBX-CFG-RXM) is not supported by this protocol version")); } return (255); } // Now let's read the power setting using UBX-CFG-RXM packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_RXM; packetCfg.len = 0; packetCfg.startingSpot = 0; //Ask module for the current power management settings. Loads into payloadCfg. if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) // We are expecting data and an ACK return (255); return (payloadCfg[1]); // Return the low power mode } // Powers off the GPS device for a given duration to reduce power consumption. // NOTE: Querying the device before the duration is complete, for example by "getLatitude()" will wake it up! // Returns true if command has not been not acknowledged. // Returns false if command has not been acknowledged or maxWait = 0. boolean SFE_UBLOX_GPS::powerOff(uint32_t durationInMs, uint16_t maxWait) { // use durationInMs = 0 for infinite duration if (_printDebug == true) { _debugSerial->print(F("Powering off for ")); _debugSerial->print(durationInMs); _debugSerial->println(" ms"); } // Power off device using UBX-RXM-PMREQ packetCfg.cls = UBX_CLASS_RXM; // 0x02 packetCfg.id = UBX_RXM_PMREQ; // 0x41 packetCfg.len = 8; packetCfg.startingSpot = 0; // duration // big endian to little endian, switch byte order payloadCfg[0] = (durationInMs >> (8*0)) & 0xff; payloadCfg[1] = (durationInMs >> (8*1)) & 0xff; payloadCfg[2] = (durationInMs >> (8*2)) & 0xff; payloadCfg[3] = (durationInMs >> (8*3)) & 0xff; payloadCfg[4] = 0x02; //Flags : set the backup bit payloadCfg[5] = 0x00; //Flags payloadCfg[6] = 0x00; //Flags payloadCfg[7] = 0x00; //Flags if (maxWait != 0) { // check for "not acknowledged" command return (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_COMMAND_NACK); } else { sendCommand(&packetCfg, maxWait); return false; // can't tell if command not acknowledged if maxWait = 0 } } // Powers off the GPS device for a given duration to reduce power consumption. // While powered off it can be woken up by creating a falling or rising voltage edge on the specified pin. // NOTE: The GPS seems to be sensitve to signals on the pins while powered off. Works best when Microcontroller is in deepsleep. // NOTE: Querying the device before the duration is complete, for example by "getLatitude()" will wake it up! // Returns true if command has not been not acknowledged. // Returns false if command has not been acknowledged or maxWait = 0. boolean SFE_UBLOX_GPS::powerOffWithInterrupt(uint32_t durationInMs, uint32_t wakeupSources, boolean forceWhileUsb, uint16_t maxWait) { // use durationInMs = 0 for infinite duration if (_printDebug == true) { _debugSerial->print(F("Powering off for ")); _debugSerial->print(durationInMs); _debugSerial->println(" ms"); } // Power off device using UBX-RXM-PMREQ packetCfg.cls = UBX_CLASS_RXM; // 0x02 packetCfg.id = UBX_RXM_PMREQ; // 0x41 packetCfg.len = 16; packetCfg.startingSpot = 0; payloadCfg[0] = 0x00; // message version // bytes 1-3 are reserved - and must be set to zero payloadCfg[1] = 0x00; payloadCfg[2] = 0x00; payloadCfg[3] = 0x00; // duration // big endian to little endian, switch byte order payloadCfg[4] = (durationInMs >> (8*0)) & 0xff; payloadCfg[5] = (durationInMs >> (8*1)) & 0xff; payloadCfg[6] = (durationInMs >> (8*2)) & 0xff; payloadCfg[7] = (durationInMs >> (8*3)) & 0xff; // flags // disables USB interface when powering off, defaults to true if (forceWhileUsb) { payloadCfg[8] = 0x06; // force | backup } else { payloadCfg[8] = 0x02; // backup only (leave the force bit clear - module will stay on if USB is connected) } payloadCfg[9] = 0x00; payloadCfg[10] = 0x00; payloadCfg[11] = 0x00; // wakeUpSources // wakeupPin mapping, defaults to VAL_RXM_PMREQ_WAKEUPSOURCE_EXTINT0 // Possible values are: // VAL_RXM_PMREQ_WAKEUPSOURCE_UARTRX // VAL_RXM_PMREQ_WAKEUPSOURCE_EXTINT0 // VAL_RXM_PMREQ_WAKEUPSOURCE_EXTINT1 // VAL_RXM_PMREQ_WAKEUPSOURCE_SPICS payloadCfg[12] = (wakeupSources >> (8*0)) & 0xff; payloadCfg[13] = (wakeupSources >> (8*1)) & 0xff; payloadCfg[14] = (wakeupSources >> (8*2)) & 0xff; payloadCfg[15] = (wakeupSources >> (8*3)) & 0xff; if (maxWait != 0) { // check for "not acknowledged" command return (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_COMMAND_NACK); } else { sendCommand(&packetCfg, maxWait); return false; // can't tell if command not acknowledged if maxWait = 0 } } //Change the dynamic platform model using UBX-CFG-NAV5 //Possible values are: //PORTABLE,STATIONARY,PEDESTRIAN,AUTOMOTIVE,SEA, //AIRBORNE1g,AIRBORNE2g,AIRBORNE4g,WRIST,BIKE //WRIST is not supported in protocol versions less than 18 //BIKE is supported in protocol versions 19.2 boolean SFE_UBLOX_GPS::setDynamicModel(dynModel newDynamicModel, uint16_t maxWait) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_NAV5; packetCfg.len = 0; packetCfg.startingSpot = 0; //Ask module for the current navigation model settings. Loads into payloadCfg. if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) // We are expecting data and an ACK return (false); payloadCfg[0] = 0x01; // mask: set only the dyn bit (0) payloadCfg[1] = 0x00; // mask payloadCfg[2] = newDynamicModel; // dynModel packetCfg.len = 36; packetCfg.startingSpot = 0; return (sendCommand(&packetCfg, maxWait) == SFE_UBLOX_STATUS_DATA_SENT); // We are only expecting an ACK } //Get the dynamic platform model using UBX-CFG-NAV5 //Returns 255 if the sendCommand fails uint8_t SFE_UBLOX_GPS::getDynamicModel(uint16_t maxWait) { packetCfg.cls = UBX_CLASS_CFG; packetCfg.id = UBX_CFG_NAV5; packetCfg.len = 0; packetCfg.startingSpot = 0; //Ask module for the current navigation model settings. Loads into payloadCfg. if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) // We are expecting data and an ACK return (255); return (payloadCfg[2]); // Return the dynamic model } //Given a spot in the payload array, extract four bytes and build a long uint32_t SFE_UBLOX_GPS::extractLong(uint8_t spotToStart) { uint32_t val = 0; val |= (uint32_t)payloadCfg[spotToStart + 0] << 8 * 0; val |= (uint32_t)payloadCfg[spotToStart + 1] << 8 * 1; val |= (uint32_t)payloadCfg[spotToStart + 2] << 8 * 2; val |= (uint32_t)payloadCfg[spotToStart + 3] << 8 * 3; return (val); } //Given a spot in the payload array, extract two bytes and build an int uint16_t SFE_UBLOX_GPS::extractInt(uint8_t spotToStart) { uint16_t val = 0; val |= (uint16_t)payloadCfg[spotToStart + 0] << 8 * 0; val |= (uint16_t)payloadCfg[spotToStart + 1] << 8 * 1; return (val); } //Given a spot, extract a byte from the payload uint8_t SFE_UBLOX_GPS::extractByte(uint8_t spotToStart) { return (payloadCfg[spotToStart]); } //Given a spot, extract a signed 8-bit value from the payload int8_t SFE_UBLOX_GPS::extractSignedChar(uint8_t spotToStart) { return ((int8_t)payloadCfg[spotToStart]); } //Get the current year uint16_t SFE_UBLOX_GPS::getYear(uint16_t maxWait) { if (moduleQueried.gpsYear == false) getPVT(maxWait); moduleQueried.gpsYear = false; //Since we are about to give this to user, mark this data as stale return (gpsYear); } //Get the current month uint8_t SFE_UBLOX_GPS::getMonth(uint16_t maxWait) { if (moduleQueried.gpsMonth == false) getPVT(maxWait); moduleQueried.gpsMonth = false; //Since we are about to give this to user, mark this data as stale return (gpsMonth); } //Get the current day uint8_t SFE_UBLOX_GPS::getDay(uint16_t maxWait) { if (moduleQueried.gpsDay == false) getPVT(maxWait); moduleQueried.gpsDay = false; //Since we are about to give this to user, mark this data as stale return (gpsDay); } //Get the current hour uint8_t SFE_UBLOX_GPS::getHour(uint16_t maxWait) { if (moduleQueried.gpsHour == false) getPVT(maxWait); moduleQueried.gpsHour = false; //Since we are about to give this to user, mark this data as stale return (gpsHour); } //Get the current minute uint8_t SFE_UBLOX_GPS::getMinute(uint16_t maxWait) { if (moduleQueried.gpsMinute == false) getPVT(maxWait); moduleQueried.gpsMinute = false; //Since we are about to give this to user, mark this data as stale return (gpsMinute); } //Get the current second uint8_t SFE_UBLOX_GPS::getSecond(uint16_t maxWait) { if (moduleQueried.gpsSecond == false) getPVT(maxWait); moduleQueried.gpsSecond = false; //Since we are about to give this to user, mark this data as stale return (gpsSecond); } //Get the current date validity bool SFE_UBLOX_GPS::getDateValid(uint16_t maxWait) { if (moduleQueried.gpsDateValid == false) getPVT(maxWait); moduleQueried.gpsDateValid = false; //Since we are about to give this to user, mark this data as stale return (gpsDateValid); } //Get the current time validity bool SFE_UBLOX_GPS::getTimeValid(uint16_t maxWait) { if (moduleQueried.gpsTimeValid == false) getPVT(maxWait); moduleQueried.gpsTimeValid = false; //Since we are about to give this to user, mark this data as stale return (gpsTimeValid); } //Get the current millisecond uint16_t SFE_UBLOX_GPS::getMillisecond(uint16_t maxWait) { if (moduleQueried.gpsiTOW == false) getPVT(maxWait); moduleQueried.gpsiTOW = false; //Since we are about to give this to user, mark this data as stale return (gpsMillisecond); } //Get the current nanoseconds - includes milliseconds int32_t SFE_UBLOX_GPS::getNanosecond(uint16_t maxWait) { if (moduleQueried.gpsNanosecond == false) getPVT(maxWait); moduleQueried.gpsNanosecond = false; //Since we are about to give this to user, mark this data as stale return (gpsNanosecond); } //Get the latest Position/Velocity/Time solution and fill all global variables boolean SFE_UBLOX_GPS::getPVT(uint16_t maxWait) { if (autoPVT && autoPVTImplicitUpdate) { //The GPS is automatically reporting, we just check whether we got unread data if (_printDebug == true) { _debugSerial->println(F("getPVT: Autoreporting")); } checkUbloxInternal(&packetCfg, UBX_CLASS_NAV, UBX_NAV_PVT); return moduleQueried.all; } else if (autoPVT && !autoPVTImplicitUpdate) { //Someone else has to call checkUblox for us... if (_printDebug == true) { _debugSerial->println(F("getPVT: Exit immediately")); } return (false); } else { if (_printDebug == true) { _debugSerial->println(F("getPVT: Polling")); } //The GPS is not automatically reporting navigation position so we have to poll explicitly packetCfg.cls = UBX_CLASS_NAV; packetCfg.id = UBX_NAV_PVT; packetCfg.len = 0; //packetCfg.startingSpot = 20; //Begin listening at spot 20 so we can record up to 20+MAX_PAYLOAD_SIZE = 84 bytes Note:now hard-coded in processUBX //The data is parsed as part of processing the response sfe_ublox_status_e retVal = sendCommand(&packetCfg, maxWait); if (retVal == SFE_UBLOX_STATUS_DATA_RECEIVED) return (true); if (_printDebug == true) { _debugSerial->print(F("getPVT retVal: ")); _debugSerial->println(statusString(retVal)); } return (false); } } uint32_t SFE_UBLOX_GPS::getTimeOfWeek(uint16_t maxWait /* = 250*/) { if (moduleQueried.gpsiTOW == false) getPVT(maxWait); moduleQueried.gpsiTOW = false; //Since we are about to give this to user, mark this data as stale return (timeOfWeek); } int32_t SFE_UBLOX_GPS::getHighResLatitude(uint16_t maxWait /* = 250*/) { if (highResModuleQueried.highResLatitude == false) getHPPOSLLH(maxWait); highResModuleQueried.highResLatitude = false; //Since we are about to give this to user, mark this data as stale return (highResLatitude); } int8_t SFE_UBLOX_GPS::getHighResLatitudeHp(uint16_t maxWait /* = 250*/) { if (highResModuleQueried.highResLatitudeHp == false) getHPPOSLLH(maxWait); highResModuleQueried.highResLatitudeHp = false; //Since we are about to give this to user, mark this data as stale return (highResLatitudeHp); } int32_t SFE_UBLOX_GPS::getHighResLongitude(uint16_t maxWait /* = 250*/) { if (highResModuleQueried.highResLongitude == false) getHPPOSLLH(maxWait); highResModuleQueried.highResLongitude = false; //Since we are about to give this to user, mark this data as stale return (highResLongitude); } int8_t SFE_UBLOX_GPS::getHighResLongitudeHp(uint16_t maxWait /* = 250*/) { if (highResModuleQueried.highResLongitudeHp == false) getHPPOSLLH(maxWait); highResModuleQueried.highResLongitudeHp = false; //Since we are about to give this to user, mark this data as stale return (highResLongitudeHp); } int32_t SFE_UBLOX_GPS::getElipsoid(uint16_t maxWait /* = 250*/) { if (highResModuleQueried.elipsoid == false) getHPPOSLLH(maxWait); highResModuleQueried.elipsoid = false; //Since we are about to give this to user, mark this data as stale return (elipsoid); } int8_t SFE_UBLOX_GPS::getElipsoidHp(uint16_t maxWait /* = 250*/) { if (highResModuleQueried.elipsoidHp == false) getHPPOSLLH(maxWait); highResModuleQueried.elipsoidHp = false; //Since we are about to give this to user, mark this data as stale return (elipsoidHp); } int32_t SFE_UBLOX_GPS::getMeanSeaLevel(uint16_t maxWait /* = 250*/) { if (highResModuleQueried.meanSeaLevel == false) getHPPOSLLH(maxWait); highResModuleQueried.meanSeaLevel = false; //Since we are about to give this to user, mark this data as stale return (meanSeaLevel); } int8_t SFE_UBLOX_GPS::getMeanSeaLevelHp(uint16_t maxWait /* = 250*/) { if (highResModuleQueried.meanSeaLevelHp == false) getHPPOSLLH(maxWait); highResModuleQueried.meanSeaLevelHp = false; //Since we are about to give this to user, mark this data as stale return (meanSeaLevelHp); } // getGeoidSeparation is currently redundant. The geoid separation seems to only be provided in NMEA GGA and GNS messages. int32_t SFE_UBLOX_GPS::getGeoidSeparation(uint16_t maxWait /* = 250*/) { if (highResModuleQueried.geoidSeparation == false) getHPPOSLLH(maxWait); highResModuleQueried.geoidSeparation = false; //Since we are about to give this to user, mark this data as stale return (geoidSeparation); } uint32_t SFE_UBLOX_GPS::getHorizontalAccuracy(uint16_t maxWait /* = 250*/) { if (highResModuleQueried.horizontalAccuracy == false) getHPPOSLLH(maxWait); highResModuleQueried.horizontalAccuracy = false; //Since we are about to give this to user, mark this data as stale return (horizontalAccuracy); } uint32_t SFE_UBLOX_GPS::getVerticalAccuracy(uint16_t maxWait /* = 250*/) { if (highResModuleQueried.verticalAccuracy == false) getHPPOSLLH(maxWait); highResModuleQueried.verticalAccuracy = false; //Since we are about to give this to user, mark this data as stale return (verticalAccuracy); } boolean SFE_UBLOX_GPS::getHPPOSLLH(uint16_t maxWait) { //The GPS is not automatically reporting navigation position so we have to poll explicitly packetCfg.cls = UBX_CLASS_NAV; packetCfg.id = UBX_NAV_HPPOSLLH; packetCfg.len = 0; return (sendCommand(&packetCfg, maxWait) == SFE_UBLOX_STATUS_DATA_RECEIVED); // We are only expecting data (no ACK) } //Get the current 3D high precision positional accuracy - a fun thing to watch //Returns a long representing the 3D accuracy in millimeters uint32_t SFE_UBLOX_GPS::getPositionAccuracy(uint16_t maxWait) { packetCfg.cls = UBX_CLASS_NAV; packetCfg.id = UBX_NAV_HPPOSECEF; packetCfg.len = 0; packetCfg.startingSpot = 0; if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) // We are only expecting data (no ACK) return (0); //If command send fails then bail uint32_t tempAccuracy = extractLong(24); //We got a response, now extract a long beginning at a given position if ((tempAccuracy % 10) >= 5) tempAccuracy += 5; //Round fraction of mm up to next mm if .5 or above tempAccuracy /= 10; //Convert 0.1mm units to mm return (tempAccuracy); } //Get the current latitude in degrees //Returns a long representing the number of degrees *10^-7 int32_t SFE_UBLOX_GPS::getLatitude(uint16_t maxWait) { if (moduleQueried.latitude == false) getPVT(maxWait); moduleQueried.latitude = false; //Since we are about to give this to user, mark this data as stale moduleQueried.all = false; return (latitude); } //Get the current longitude in degrees //Returns a long representing the number of degrees *10^-7 int32_t SFE_UBLOX_GPS::getLongitude(uint16_t maxWait) { if (moduleQueried.longitude == false) getPVT(maxWait); moduleQueried.longitude = false; //Since we are about to give this to user, mark this data as stale moduleQueried.all = false; return (longitude); } //Get the current altitude in mm according to ellipsoid model int32_t SFE_UBLOX_GPS::getAltitude(uint16_t maxWait) { if (moduleQueried.altitude == false) getPVT(maxWait); moduleQueried.altitude = false; //Since we are about to give this to user, mark this data as stale moduleQueried.all = false; return (altitude); } //Get the current altitude in mm according to mean sea level //Ellipsoid model: https://www.esri.com/news/arcuser/0703/geoid1of3.html //Difference between Ellipsoid Model and Mean Sea Level: https://eos-gnss.com/elevation-for-beginners/ int32_t SFE_UBLOX_GPS::getAltitudeMSL(uint16_t maxWait) { if (moduleQueried.altitudeMSL == false) getPVT(maxWait); moduleQueried.altitudeMSL = false; //Since we are about to give this to user, mark this data as stale moduleQueried.all = false; return (altitudeMSL); } //Get the number of satellites used in fix uint8_t SFE_UBLOX_GPS::getSIV(uint16_t maxWait) { if (moduleQueried.SIV == false) getPVT(maxWait); moduleQueried.SIV = false; //Since we are about to give this to user, mark this data as stale moduleQueried.all = false; return (SIV); } //Get the current fix type //0=no fix, 1=dead reckoning, 2=2D, 3=3D, 4=GNSS, 5=Time fix uint8_t SFE_UBLOX_GPS::getFixType(uint16_t maxWait) { if (moduleQueried.fixType == false) { getPVT(maxWait); } moduleQueried.fixType = false; //Since we are about to give this to user, mark this data as stale moduleQueried.all = false; return (fixType); } //Get the carrier phase range solution status //Useful when querying module to see if it has high-precision RTK fix //0=No solution, 1=Float solution, 2=Fixed solution uint8_t SFE_UBLOX_GPS::getCarrierSolutionType(uint16_t maxWait) { if (moduleQueried.carrierSolution == false) getPVT(maxWait); moduleQueried.carrierSolution = false; //Since we are about to give this to user, mark this data as stale moduleQueried.all = false; return (carrierSolution); } //Get the ground speed in mm/s int32_t SFE_UBLOX_GPS::getGroundSpeed(uint16_t maxWait) { if (moduleQueried.groundSpeed == false) getPVT(maxWait); moduleQueried.groundSpeed = false; //Since we are about to give this to user, mark this data as stale moduleQueried.all = false; return (groundSpeed); } //Get the heading of motion (as opposed to heading of car) in degrees * 10^-5 int32_t SFE_UBLOX_GPS::getHeading(uint16_t maxWait) { if (moduleQueried.headingOfMotion == false) getPVT(maxWait); moduleQueried.headingOfMotion = false; //Since we are about to give this to user, mark this data as stale moduleQueried.all = false; return (headingOfMotion); } //Get the positional dillution of precision * 10^-2 uint16_t SFE_UBLOX_GPS::getPDOP(uint16_t maxWait) { if (moduleQueried.pDOP == false) getPVT(maxWait); moduleQueried.pDOP = false; //Since we are about to give this to user, mark this data as stale moduleQueried.all = false; return (pDOP); } //Get the current protocol version of the Ublox module we're communicating with //This is helpful when deciding if we should call the high-precision Lat/Long (HPPOSLLH) or the regular (POSLLH) uint8_t SFE_UBLOX_GPS::getProtocolVersionHigh(uint16_t maxWait) { if (moduleQueried.versionNumber == false) getProtocolVersion(maxWait); return (versionHigh); } //Get the current protocol version of the Ublox module we're communicating with //This is helpful when deciding if we should call the high-precision Lat/Long (HPPOSLLH) or the regular (POSLLH) uint8_t SFE_UBLOX_GPS::getProtocolVersionLow(uint16_t maxWait) { if (moduleQueried.versionNumber == false) getProtocolVersion(maxWait); return (versionLow); } //Get the current protocol version of the Ublox module we're communicating with //This is helpful when deciding if we should call the high-precision Lat/Long (HPPOSLLH) or the regular (POSLLH) boolean SFE_UBLOX_GPS::getProtocolVersion(uint16_t maxWait) { //Send packet with only CLS and ID, length of zero. This will cause the module to respond with the contents of that CLS/ID. packetCfg.cls = UBX_CLASS_MON; packetCfg.id = UBX_MON_VER; packetCfg.len = 0; packetCfg.startingSpot = 40; //Start at first "extended software information" string if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) // We are only expecting data (no ACK) return (false); //If command send fails then bail //Payload should now contain ~220 characters (depends on module type) // if (_printDebug == true) // { // _debugSerial->print(F("MON VER Payload:")); // for (int location = 0; location < packetCfg.len; location++) // { // if (location % 30 == 0) // _debugSerial->println(); // _debugSerial->write(payloadCfg[location]); // } // _debugSerial->println(); // } //We will step through the payload looking at each extension field of 30 bytes for (uint8_t extensionNumber = 0; extensionNumber < 10; extensionNumber++) { //Now we need to find "PROTVER=18.00" in the incoming byte stream if (payloadCfg[(30 * extensionNumber) + 0] == 'P' && payloadCfg[(30 * extensionNumber) + 6] == 'R') { versionHigh = (payloadCfg[(30 * extensionNumber) + 8] - '0') * 10 + (payloadCfg[(30 * extensionNumber) + 9] - '0'); //Convert '18' to 18 versionLow = (payloadCfg[(30 * extensionNumber) + 11] - '0') * 10 + (payloadCfg[(30 * extensionNumber) + 12] - '0'); //Convert '00' to 00 moduleQueried.versionNumber = true; //Mark this data as new if (_printDebug == true) { _debugSerial->print(F("Protocol version: ")); _debugSerial->print(versionHigh); _debugSerial->print(F(".")); _debugSerial->println(versionLow); } return (true); //Success! } } return (false); //We failed } //Mark all the PVT data as read/stale. This is handy to get data alignment after CRC failure void SFE_UBLOX_GPS::flushPVT() { //Mark all datums as stale (read before) moduleQueried.gpsiTOW = false; moduleQueried.gpsYear = false; moduleQueried.gpsMonth = false; moduleQueried.gpsDay = false; moduleQueried.gpsHour = false; moduleQueried.gpsMinute = false; moduleQueried.gpsSecond = false; moduleQueried.gpsDateValid = false; moduleQueried.gpsTimeValid = false; moduleQueried.gpsNanosecond = false; moduleQueried.all = false; moduleQueried.longitude = false; moduleQueried.latitude = false; moduleQueried.altitude = false; moduleQueried.altitudeMSL = false; moduleQueried.SIV = false; moduleQueried.fixType = false; moduleQueried.carrierSolution = false; moduleQueried.groundSpeed = false; moduleQueried.headingOfMotion = false; moduleQueried.pDOP = false; } //Relative Positioning Information in NED frame //Returns true if commands was successful boolean SFE_UBLOX_GPS::getRELPOSNED(uint16_t maxWait) { packetCfg.cls = UBX_CLASS_NAV; packetCfg.id = UBX_NAV_RELPOSNED; packetCfg.len = 0; packetCfg.startingSpot = 0; if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) // We are only expecting data (no ACK) return (false); //If command send fails then bail //We got a response, now parse the bits uint16_t refStationID = extractInt(2); //_debugSerial->print(F("refStationID: ")); //_debugSerial->println(refStationID)); int32_t tempRelPos; tempRelPos = extractLong(8); relPosInfo.relPosN = tempRelPos / 100.0; //Convert cm to m tempRelPos = extractLong(12); relPosInfo.relPosE = tempRelPos / 100.0; //Convert cm to m tempRelPos = extractLong(16); relPosInfo.relPosD = tempRelPos / 100.0; //Convert cm to m relPosInfo.relPosLength = extractLong(20); relPosInfo.relPosHeading = extractLong(24); relPosInfo.relPosHPN = payloadCfg[32]; relPosInfo.relPosHPE = payloadCfg[33]; relPosInfo.relPosHPD = payloadCfg[34]; relPosInfo.relPosHPLength = payloadCfg[35]; uint32_t tempAcc; tempAcc = extractLong(36); relPosInfo.accN = tempAcc / 10000.0; //Convert 0.1 mm to m tempAcc = extractLong(40); relPosInfo.accE = tempAcc / 10000.0; //Convert 0.1 mm to m tempAcc = extractLong(44); relPosInfo.accD = tempAcc / 10000.0; //Convert 0.1 mm to m uint8_t flags = payloadCfg[60]; relPosInfo.gnssFixOk = flags & (1 << 0); relPosInfo.diffSoln = flags & (1 << 1); relPosInfo.relPosValid = flags & (1 << 2); relPosInfo.carrSoln = (flags & (0b11 << 3)) >> 3; relPosInfo.isMoving = flags & (1 << 5); relPosInfo.refPosMiss = flags & (1 << 6); relPosInfo.refObsMiss = flags & (1 << 7); return (true); } boolean SFE_UBLOX_GPS::getEsfInfo(uint16_t maxWait) { // Requesting Data from the receiver packetCfg.cls = UBX_CLASS_ESF; packetCfg.id = UBX_ESF_STATUS; packetCfg.len = 0; packetCfg.startingSpot = 0; if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) return (false); //If command send fails then bail checkUblox(); // payload should be loaded. imuMeas.version = extractByte(4); imuMeas.fusionMode = extractByte(12); ubloxSen.numSens = extractByte(15); // Individual Status Sensor in different function return (true); } // boolean SFE_UBLOX_GPS::getEsfIns(uint16_t maxWait) { packetCfg.cls = UBX_CLASS_ESF; packetCfg.id = UBX_ESF_INS; packetCfg.len = 0; packetCfg.startingSpot = 0; if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) return (false); //If command send fails then bail checkUblox(); // Validity of each sensor value below uint32_t validity = extractLong(0); imuMeas.xAngRateVald = (validity && 0x0080) >> 8; imuMeas.yAngRateVald = (validity && 0x0100) >> 9; imuMeas.zAngRateVald = (validity && 0x0200) >> 10; imuMeas.xAccelVald = (validity && 0x0400) >> 11; imuMeas.yAccelVald = (validity && 0x0800) >> 12; imuMeas.zAccelVald = (validity && 0x1000) >> 13; imuMeas.xAngRate = extractLong(12); // deg/s imuMeas.yAngRate = extractLong(16); // deg/s imuMeas.zAngRate = extractLong(20); // deg/s imuMeas.xAccel = extractLong(24); // m/s imuMeas.yAccel = extractLong(28); // m/s imuMeas.zAccel = extractLong(32); // m/s return (true); } // boolean SFE_UBLOX_GPS::getEsfDataInfo(uint16_t maxWait) { packetCfg.cls = UBX_CLASS_ESF; packetCfg.id = UBX_ESF_MEAS; packetCfg.len = 0; packetCfg.startingSpot = 0; if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) return (false); //If command send fails then bail checkUblox(); uint32_t timeStamp = extractLong(0); uint32_t flags = extractInt(4); uint8_t timeSent = (flags && 0x01) >> 1; uint8_t timeEdge = (flags && 0x02) >> 2; uint8_t tagValid = (flags && 0x04) >> 3; uint8_t numMeas = (flags && 0x1000) >> 15; if (numMeas > DEF_NUM_SENS) numMeas = DEF_NUM_SENS; uint8_t byteOffset = 4; for (uint8_t i = 0; i < numMeas; i++) { uint32_t bitField = extractLong(4 + byteOffset * i); imuMeas.dataType[i] = (bitField && 0xFF000000) >> 23; imuMeas.data[i] = (bitField && 0xFFFFFF); imuMeas.dataTStamp[i] = extractLong(8 + byteOffset * i); } return (true); } boolean SFE_UBLOX_GPS::getEsfRawDataInfo(uint16_t maxWait) { // Need to know the number of sensor to get the correct data // Rate selected in UBX-CFG-MSG is not respected packetCfg.cls = UBX_CLASS_ESF; packetCfg.id = UBX_ESF_RAW; packetCfg.len = 0; packetCfg.startingSpot = 0; if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) return (false); //If command send fails then bail checkUblox(); uint32_t bitField = extractLong(4); imuMeas.rawDataType = (bitField && 0xFF000000) >> 23; imuMeas.rawData = (bitField && 0xFFFFFF); imuMeas.rawTStamp = extractLong(8); return (true); } sfe_ublox_status_e SFE_UBLOX_GPS::getSensState(uint8_t sensor, uint16_t maxWait) { packetCfg.cls = UBX_CLASS_ESF; packetCfg.id = UBX_ESF_STATUS; packetCfg.len = 0; packetCfg.startingSpot = 0; if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) return (SFE_UBLOX_STATUS_FAIL); //If command send fails then bail ubloxSen.numSens = extractByte(15); if (sensor > ubloxSen.numSens) return (SFE_UBLOX_STATUS_OUT_OF_RANGE); checkUblox(); uint8_t offset = 4; // Only the last sensor value checked will remain. for (uint8_t i = 0; i < sensor; i++) { uint8_t sensorFieldOne = extractByte(16 + offset * i); uint8_t sensorFieldTwo = extractByte(17 + offset * i); ubloxSen.freq = extractByte(18 + offset * i); uint8_t sensorFieldThr = extractByte(19 + offset * i); ubloxSen.senType = (sensorFieldOne && 0x10) >> 5; ubloxSen.isUsed = (sensorFieldOne && 0x20) >> 6; ubloxSen.isReady = (sensorFieldOne && 0x30) >> 7; ubloxSen.calibStatus = sensorFieldTwo && 0x03; ubloxSen.timeStatus = (sensorFieldTwo && 0xC) >> 2; ubloxSen.badMeas = (sensorFieldThr && 0x01); ubloxSen.badTag = (sensorFieldThr && 0x02) >> 1; ubloxSen.missMeas = (sensorFieldThr && 0x04) >> 2; ubloxSen.noisyMeas = (sensorFieldThr && 0x08) >> 3; } return (SFE_UBLOX_STATUS_SUCCESS); } boolean SFE_UBLOX_GPS::getVehAtt(uint16_t maxWait) { packetCfg.cls = UBX_CLASS_NAV; packetCfg.id = UBX_NAV_ATT; packetCfg.len = 0; packetCfg.startingSpot = 0; if (sendCommand(&packetCfg, maxWait) != SFE_UBLOX_STATUS_DATA_RECEIVED) return (SFE_UBLOX_STATUS_FAIL); //If command send fails then bail checkUblox(); vehAtt.roll = extractLong(8); vehAtt.pitch = extractLong(12); vehAtt.heading = extractLong(16); vehAtt.accRoll = extractLong(20); vehAtt.accPitch = extractLong(24); vehAtt.accHeading = extractLong(28); return (true); }
37.919126
286
0.695413
[ "model", "3d" ]
70b123894aa8401853c482c8314f4d88aca78868
140,184
hpp
C++
ThirdParty-mod/java2cpp/android/view/View.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
1
2019-04-03T01:53:28.000Z
2019-04-03T01:53:28.000Z
ThirdParty-mod/java2cpp/android/view/View.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
ThirdParty-mod/java2cpp/android/view/View.hpp
kakashidinho/HQEngine
8125b290afa7c62db6cc6eac14e964d8138c7fd0
[ "MIT" ]
null
null
null
/*================================================================================ code generated by: java2cpp author: Zoran Angelov, mailto://baldzar@gmail.com class: android.view.View ================================================================================*/ #ifndef J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_VIEW_VIEW_HPP_DECL #define J2CPP_ANDROID_VIEW_VIEW_HPP_DECL namespace j2cpp { namespace java { namespace lang { class Object; } } } namespace j2cpp { namespace java { namespace lang { class CharSequence; } } } namespace j2cpp { namespace java { namespace lang { class String; } } } namespace j2cpp { namespace java { namespace lang { class Runnable; } } } namespace j2cpp { namespace java { namespace util { class ArrayList; } } } namespace j2cpp { namespace android { namespace graphics { class Canvas; } } } namespace j2cpp { namespace android { namespace graphics { class Bitmap; } } } namespace j2cpp { namespace android { namespace graphics { class Point; } } } namespace j2cpp { namespace android { namespace graphics { namespace drawable { class Drawable; } } } } namespace j2cpp { namespace android { namespace graphics { namespace drawable { namespace Drawable_ { class Callback; } } } } } namespace j2cpp { namespace android { namespace graphics { class Rect; } } } namespace j2cpp { namespace android { namespace content { namespace res { class Resources; } } } } namespace j2cpp { namespace android { namespace content { class Context; } } } namespace j2cpp { namespace android { namespace view { namespace View_ { class OnTouchListener; } } } } namespace j2cpp { namespace android { namespace view { class ViewGroup; } } } namespace j2cpp { namespace android { namespace view { class ViewTreeObserver; } } } namespace j2cpp { namespace android { namespace view { namespace inputmethod { class InputConnection; } } } } namespace j2cpp { namespace android { namespace view { namespace inputmethod { class EditorInfo; } } } } namespace j2cpp { namespace android { namespace view { class KeyEvent; } } } namespace j2cpp { namespace android { namespace view { class ViewParent; } } } namespace j2cpp { namespace android { namespace view { class ContextMenu; } } } namespace j2cpp { namespace android { namespace view { namespace View_ { class OnLongClickListener; } } } } namespace j2cpp { namespace android { namespace view { class AbsSavedState; } } } namespace j2cpp { namespace android { namespace view { class TouchDelegate; } } } namespace j2cpp { namespace android { namespace view { class MotionEvent; } } } namespace j2cpp { namespace android { namespace view { namespace accessibility { class AccessibilityEvent; } } } } namespace j2cpp { namespace android { namespace view { namespace accessibility { class AccessibilityEventSource; } } } } namespace j2cpp { namespace android { namespace view { namespace KeyEvent_ { class DispatcherState; } } } } namespace j2cpp { namespace android { namespace view { namespace View_ { class OnClickListener; } } } } namespace j2cpp { namespace android { namespace view { namespace ViewGroup_ { class LayoutParams; } } } } namespace j2cpp { namespace android { namespace view { namespace View_ { class OnFocusChangeListener; } } } } namespace j2cpp { namespace android { namespace view { namespace View_ { class OnKeyListener; } } } } namespace j2cpp { namespace android { namespace view { namespace View_ { class OnCreateContextMenuListener; } } } } namespace j2cpp { namespace android { namespace view { namespace ContextMenu_ { class ContextMenuInfo; } } } } namespace j2cpp { namespace android { namespace view { namespace animation { class Animation; } } } } namespace j2cpp { namespace android { namespace util { class SparseArray; } } } namespace j2cpp { namespace android { namespace util { class AttributeSet; } } } namespace j2cpp { namespace android { namespace os { class IBinder; } } } namespace j2cpp { namespace android { namespace os { class Parcel; } } } namespace j2cpp { namespace android { namespace os { class Parcelable; } } } namespace j2cpp { namespace android { namespace os { class Handler; } } } namespace j2cpp { namespace android { namespace os { namespace Parcelable_ { class Creator; } } } } #include <android/content/Context.hpp> #include <android/content/res/Resources.hpp> #include <android/graphics/Bitmap.hpp> #include <android/graphics/Canvas.hpp> #include <android/graphics/Point.hpp> #include <android/graphics/Rect.hpp> #include <android/graphics/drawable/Drawable.hpp> #include <android/os/Handler.hpp> #include <android/os/IBinder.hpp> #include <android/os/Parcel.hpp> #include <android/os/Parcelable.hpp> #include <android/util/AttributeSet.hpp> #include <android/util/SparseArray.hpp> #include <android/view/AbsSavedState.hpp> #include <android/view/ContextMenu.hpp> #include <android/view/KeyEvent.hpp> #include <android/view/MotionEvent.hpp> #include <android/view/TouchDelegate.hpp> #include <android/view/View.hpp> #include <android/view/ViewGroup.hpp> #include <android/view/ViewParent.hpp> #include <android/view/ViewTreeObserver.hpp> #include <android/view/accessibility/AccessibilityEvent.hpp> #include <android/view/accessibility/AccessibilityEventSource.hpp> #include <android/view/animation/Animation.hpp> #include <android/view/inputmethod/EditorInfo.hpp> #include <android/view/inputmethod/InputConnection.hpp> #include <java/lang/CharSequence.hpp> #include <java/lang/Object.hpp> #include <java/lang/Runnable.hpp> #include <java/lang/String.hpp> #include <java/util/ArrayList.hpp> namespace j2cpp { namespace android { namespace view { class View; namespace View_ { class OnTouchListener; class OnTouchListener : public object<OnTouchListener> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) explicit OnTouchListener(jobject jobj) : object<OnTouchListener>(jobj) { } operator local_ref<java::lang::Object>() const; jboolean onTouch(local_ref< android::view::View > const&, local_ref< android::view::MotionEvent > const&); }; //class OnTouchListener class BaseSavedState; class BaseSavedState : public object<BaseSavedState> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_FIELD(0) explicit BaseSavedState(jobject jobj) : object<BaseSavedState>(jobj) { } operator local_ref<android::view::AbsSavedState>() const; BaseSavedState(local_ref< android::os::Parcel > const&); BaseSavedState(local_ref< android::os::Parcelable > const&); static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), local_ref< android::os::Parcelable_::Creator > > CREATOR; }; //class BaseSavedState class OnLongClickListener; class OnLongClickListener : public object<OnLongClickListener> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) explicit OnLongClickListener(jobject jobj) : object<OnLongClickListener>(jobj) { } operator local_ref<java::lang::Object>() const; jboolean onLongClick(local_ref< android::view::View > const&); }; //class OnLongClickListener class OnClickListener; class OnClickListener : public object<OnClickListener> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) explicit OnClickListener(jobject jobj) : object<OnClickListener>(jobj) { } operator local_ref<java::lang::Object>() const; void onClick(local_ref< android::view::View > const&); }; //class OnClickListener class OnFocusChangeListener; class OnFocusChangeListener : public object<OnFocusChangeListener> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) explicit OnFocusChangeListener(jobject jobj) : object<OnFocusChangeListener>(jobj) { } operator local_ref<java::lang::Object>() const; void onFocusChange(local_ref< android::view::View > const&, jboolean); }; //class OnFocusChangeListener class OnKeyListener; class OnKeyListener : public object<OnKeyListener> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) explicit OnKeyListener(jobject jobj) : object<OnKeyListener>(jobj) { } operator local_ref<java::lang::Object>() const; jboolean onKey(local_ref< android::view::View > const&, jint, local_ref< android::view::KeyEvent > const&); }; //class OnKeyListener class OnCreateContextMenuListener; class OnCreateContextMenuListener : public object<OnCreateContextMenuListener> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) explicit OnCreateContextMenuListener(jobject jobj) : object<OnCreateContextMenuListener>(jobj) { } operator local_ref<java::lang::Object>() const; void onCreateContextMenu(local_ref< android::view::ContextMenu > const&, local_ref< android::view::View > const&, local_ref< android::view::ContextMenu_::ContextMenuInfo > const&); }; //class OnCreateContextMenuListener class MeasureSpec; class MeasureSpec : public object<MeasureSpec> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_FIELD(0) J2CPP_DECLARE_FIELD(1) J2CPP_DECLARE_FIELD(2) explicit MeasureSpec(jobject jobj) : object<MeasureSpec>(jobj) { } operator local_ref<java::lang::Object>() const; MeasureSpec(); static jint makeMeasureSpec(jint, jint); static jint getMode(jint); static jint getSize(jint); static local_ref< java::lang::String > toString(jint); static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(0), J2CPP_FIELD_SIGNATURE(0), jint > UNSPECIFIED; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jint > EXACTLY; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), jint > AT_MOST; }; //class MeasureSpec } //namespace View_ class View : public object<View> { public: J2CPP_DECLARE_CLASS J2CPP_DECLARE_METHOD(0) J2CPP_DECLARE_METHOD(1) J2CPP_DECLARE_METHOD(2) J2CPP_DECLARE_METHOD(3) J2CPP_DECLARE_METHOD(4) J2CPP_DECLARE_METHOD(5) J2CPP_DECLARE_METHOD(6) J2CPP_DECLARE_METHOD(7) J2CPP_DECLARE_METHOD(8) J2CPP_DECLARE_METHOD(9) J2CPP_DECLARE_METHOD(10) J2CPP_DECLARE_METHOD(11) J2CPP_DECLARE_METHOD(12) J2CPP_DECLARE_METHOD(13) J2CPP_DECLARE_METHOD(14) J2CPP_DECLARE_METHOD(15) J2CPP_DECLARE_METHOD(16) J2CPP_DECLARE_METHOD(17) J2CPP_DECLARE_METHOD(18) J2CPP_DECLARE_METHOD(19) J2CPP_DECLARE_METHOD(20) J2CPP_DECLARE_METHOD(21) J2CPP_DECLARE_METHOD(22) J2CPP_DECLARE_METHOD(23) J2CPP_DECLARE_METHOD(24) J2CPP_DECLARE_METHOD(25) J2CPP_DECLARE_METHOD(26) J2CPP_DECLARE_METHOD(27) J2CPP_DECLARE_METHOD(28) J2CPP_DECLARE_METHOD(29) J2CPP_DECLARE_METHOD(30) J2CPP_DECLARE_METHOD(31) J2CPP_DECLARE_METHOD(32) J2CPP_DECLARE_METHOD(33) J2CPP_DECLARE_METHOD(34) J2CPP_DECLARE_METHOD(35) J2CPP_DECLARE_METHOD(36) J2CPP_DECLARE_METHOD(37) J2CPP_DECLARE_METHOD(38) J2CPP_DECLARE_METHOD(39) J2CPP_DECLARE_METHOD(40) J2CPP_DECLARE_METHOD(41) J2CPP_DECLARE_METHOD(42) J2CPP_DECLARE_METHOD(43) J2CPP_DECLARE_METHOD(44) J2CPP_DECLARE_METHOD(45) J2CPP_DECLARE_METHOD(46) J2CPP_DECLARE_METHOD(47) J2CPP_DECLARE_METHOD(48) J2CPP_DECLARE_METHOD(49) J2CPP_DECLARE_METHOD(50) J2CPP_DECLARE_METHOD(51) J2CPP_DECLARE_METHOD(52) J2CPP_DECLARE_METHOD(53) J2CPP_DECLARE_METHOD(54) J2CPP_DECLARE_METHOD(55) J2CPP_DECLARE_METHOD(56) J2CPP_DECLARE_METHOD(57) J2CPP_DECLARE_METHOD(58) J2CPP_DECLARE_METHOD(59) J2CPP_DECLARE_METHOD(60) J2CPP_DECLARE_METHOD(61) J2CPP_DECLARE_METHOD(62) J2CPP_DECLARE_METHOD(63) J2CPP_DECLARE_METHOD(64) J2CPP_DECLARE_METHOD(65) J2CPP_DECLARE_METHOD(66) J2CPP_DECLARE_METHOD(67) J2CPP_DECLARE_METHOD(68) J2CPP_DECLARE_METHOD(69) J2CPP_DECLARE_METHOD(70) J2CPP_DECLARE_METHOD(71) J2CPP_DECLARE_METHOD(72) J2CPP_DECLARE_METHOD(73) J2CPP_DECLARE_METHOD(74) J2CPP_DECLARE_METHOD(75) J2CPP_DECLARE_METHOD(76) J2CPP_DECLARE_METHOD(77) J2CPP_DECLARE_METHOD(78) J2CPP_DECLARE_METHOD(79) J2CPP_DECLARE_METHOD(80) J2CPP_DECLARE_METHOD(81) J2CPP_DECLARE_METHOD(82) J2CPP_DECLARE_METHOD(83) J2CPP_DECLARE_METHOD(84) J2CPP_DECLARE_METHOD(85) J2CPP_DECLARE_METHOD(86) J2CPP_DECLARE_METHOD(87) J2CPP_DECLARE_METHOD(88) J2CPP_DECLARE_METHOD(89) J2CPP_DECLARE_METHOD(90) J2CPP_DECLARE_METHOD(91) J2CPP_DECLARE_METHOD(92) J2CPP_DECLARE_METHOD(93) J2CPP_DECLARE_METHOD(94) J2CPP_DECLARE_METHOD(95) J2CPP_DECLARE_METHOD(96) J2CPP_DECLARE_METHOD(97) J2CPP_DECLARE_METHOD(98) J2CPP_DECLARE_METHOD(99) J2CPP_DECLARE_METHOD(100) J2CPP_DECLARE_METHOD(101) J2CPP_DECLARE_METHOD(102) J2CPP_DECLARE_METHOD(103) J2CPP_DECLARE_METHOD(104) J2CPP_DECLARE_METHOD(105) J2CPP_DECLARE_METHOD(106) J2CPP_DECLARE_METHOD(107) J2CPP_DECLARE_METHOD(108) J2CPP_DECLARE_METHOD(109) J2CPP_DECLARE_METHOD(110) J2CPP_DECLARE_METHOD(111) J2CPP_DECLARE_METHOD(112) J2CPP_DECLARE_METHOD(113) J2CPP_DECLARE_METHOD(114) J2CPP_DECLARE_METHOD(115) J2CPP_DECLARE_METHOD(116) J2CPP_DECLARE_METHOD(117) J2CPP_DECLARE_METHOD(118) J2CPP_DECLARE_METHOD(119) J2CPP_DECLARE_METHOD(120) J2CPP_DECLARE_METHOD(121) J2CPP_DECLARE_METHOD(122) J2CPP_DECLARE_METHOD(123) J2CPP_DECLARE_METHOD(124) J2CPP_DECLARE_METHOD(125) J2CPP_DECLARE_METHOD(126) J2CPP_DECLARE_METHOD(127) J2CPP_DECLARE_METHOD(128) J2CPP_DECLARE_METHOD(129) J2CPP_DECLARE_METHOD(130) J2CPP_DECLARE_METHOD(131) J2CPP_DECLARE_METHOD(132) J2CPP_DECLARE_METHOD(133) J2CPP_DECLARE_METHOD(134) J2CPP_DECLARE_METHOD(135) J2CPP_DECLARE_METHOD(136) J2CPP_DECLARE_METHOD(137) J2CPP_DECLARE_METHOD(138) J2CPP_DECLARE_METHOD(139) J2CPP_DECLARE_METHOD(140) J2CPP_DECLARE_METHOD(141) J2CPP_DECLARE_METHOD(142) J2CPP_DECLARE_METHOD(143) J2CPP_DECLARE_METHOD(144) J2CPP_DECLARE_METHOD(145) J2CPP_DECLARE_METHOD(146) J2CPP_DECLARE_METHOD(147) J2CPP_DECLARE_METHOD(148) J2CPP_DECLARE_METHOD(149) J2CPP_DECLARE_METHOD(150) J2CPP_DECLARE_METHOD(151) J2CPP_DECLARE_METHOD(152) J2CPP_DECLARE_METHOD(153) J2CPP_DECLARE_METHOD(154) J2CPP_DECLARE_METHOD(155) J2CPP_DECLARE_METHOD(156) J2CPP_DECLARE_METHOD(157) J2CPP_DECLARE_METHOD(158) J2CPP_DECLARE_METHOD(159) J2CPP_DECLARE_METHOD(160) J2CPP_DECLARE_METHOD(161) J2CPP_DECLARE_METHOD(162) J2CPP_DECLARE_METHOD(163) J2CPP_DECLARE_METHOD(164) J2CPP_DECLARE_METHOD(165) J2CPP_DECLARE_METHOD(166) J2CPP_DECLARE_METHOD(167) J2CPP_DECLARE_METHOD(168) J2CPP_DECLARE_METHOD(169) J2CPP_DECLARE_METHOD(170) J2CPP_DECLARE_METHOD(171) J2CPP_DECLARE_METHOD(172) J2CPP_DECLARE_METHOD(173) J2CPP_DECLARE_METHOD(174) J2CPP_DECLARE_METHOD(175) J2CPP_DECLARE_METHOD(176) J2CPP_DECLARE_METHOD(177) J2CPP_DECLARE_METHOD(178) J2CPP_DECLARE_METHOD(179) J2CPP_DECLARE_METHOD(180) J2CPP_DECLARE_METHOD(181) J2CPP_DECLARE_METHOD(182) J2CPP_DECLARE_METHOD(183) J2CPP_DECLARE_METHOD(184) J2CPP_DECLARE_METHOD(185) J2CPP_DECLARE_METHOD(186) J2CPP_DECLARE_METHOD(187) J2CPP_DECLARE_METHOD(188) J2CPP_DECLARE_METHOD(189) J2CPP_DECLARE_METHOD(190) J2CPP_DECLARE_METHOD(191) J2CPP_DECLARE_METHOD(192) J2CPP_DECLARE_METHOD(193) J2CPP_DECLARE_METHOD(194) J2CPP_DECLARE_METHOD(195) J2CPP_DECLARE_METHOD(196) J2CPP_DECLARE_METHOD(197) J2CPP_DECLARE_METHOD(198) J2CPP_DECLARE_METHOD(199) J2CPP_DECLARE_METHOD(200) J2CPP_DECLARE_METHOD(201) J2CPP_DECLARE_METHOD(202) J2CPP_DECLARE_METHOD(203) J2CPP_DECLARE_METHOD(204) J2CPP_DECLARE_METHOD(205) J2CPP_DECLARE_METHOD(206) J2CPP_DECLARE_METHOD(207) J2CPP_DECLARE_METHOD(208) J2CPP_DECLARE_METHOD(209) J2CPP_DECLARE_METHOD(210) J2CPP_DECLARE_METHOD(211) J2CPP_DECLARE_METHOD(212) J2CPP_DECLARE_METHOD(213) J2CPP_DECLARE_METHOD(214) J2CPP_DECLARE_METHOD(215) J2CPP_DECLARE_METHOD(216) J2CPP_DECLARE_METHOD(217) J2CPP_DECLARE_METHOD(218) J2CPP_DECLARE_METHOD(219) J2CPP_DECLARE_METHOD(220) J2CPP_DECLARE_METHOD(221) J2CPP_DECLARE_METHOD(222) J2CPP_DECLARE_METHOD(223) J2CPP_DECLARE_METHOD(224) J2CPP_DECLARE_METHOD(225) J2CPP_DECLARE_METHOD(226) J2CPP_DECLARE_METHOD(227) J2CPP_DECLARE_METHOD(228) J2CPP_DECLARE_METHOD(229) J2CPP_DECLARE_METHOD(230) J2CPP_DECLARE_METHOD(231) J2CPP_DECLARE_METHOD(232) J2CPP_DECLARE_METHOD(233) J2CPP_DECLARE_METHOD(234) J2CPP_DECLARE_METHOD(235) J2CPP_DECLARE_METHOD(236) J2CPP_DECLARE_METHOD(237) J2CPP_DECLARE_METHOD(238) J2CPP_DECLARE_METHOD(239) J2CPP_DECLARE_METHOD(240) J2CPP_DECLARE_METHOD(241) J2CPP_DECLARE_METHOD(242) J2CPP_DECLARE_METHOD(243) J2CPP_DECLARE_METHOD(244) J2CPP_DECLARE_METHOD(245) J2CPP_DECLARE_METHOD(246) J2CPP_DECLARE_METHOD(247) J2CPP_DECLARE_METHOD(248) J2CPP_DECLARE_METHOD(249) J2CPP_DECLARE_METHOD(250) J2CPP_DECLARE_METHOD(251) J2CPP_DECLARE_METHOD(252) J2CPP_DECLARE_METHOD(253) J2CPP_DECLARE_METHOD(254) J2CPP_DECLARE_METHOD(255) J2CPP_DECLARE_METHOD(256) J2CPP_DECLARE_METHOD(257) J2CPP_DECLARE_METHOD(258) J2CPP_DECLARE_METHOD(259) J2CPP_DECLARE_METHOD(260) J2CPP_DECLARE_METHOD(261) J2CPP_DECLARE_METHOD(262) J2CPP_DECLARE_METHOD(263) J2CPP_DECLARE_METHOD(264) J2CPP_DECLARE_METHOD(265) J2CPP_DECLARE_METHOD(266) J2CPP_DECLARE_METHOD(267) J2CPP_DECLARE_METHOD(268) J2CPP_DECLARE_METHOD(269) J2CPP_DECLARE_METHOD(270) J2CPP_DECLARE_METHOD(271) J2CPP_DECLARE_METHOD(272) J2CPP_DECLARE_METHOD(273) J2CPP_DECLARE_METHOD(274) J2CPP_DECLARE_METHOD(275) J2CPP_DECLARE_METHOD(276) J2CPP_DECLARE_METHOD(277) J2CPP_DECLARE_METHOD(278) J2CPP_DECLARE_METHOD(279) J2CPP_DECLARE_FIELD(0) J2CPP_DECLARE_FIELD(1) J2CPP_DECLARE_FIELD(2) J2CPP_DECLARE_FIELD(3) J2CPP_DECLARE_FIELD(4) J2CPP_DECLARE_FIELD(5) J2CPP_DECLARE_FIELD(6) J2CPP_DECLARE_FIELD(7) J2CPP_DECLARE_FIELD(8) J2CPP_DECLARE_FIELD(9) J2CPP_DECLARE_FIELD(10) J2CPP_DECLARE_FIELD(11) J2CPP_DECLARE_FIELD(12) J2CPP_DECLARE_FIELD(13) J2CPP_DECLARE_FIELD(14) J2CPP_DECLARE_FIELD(15) J2CPP_DECLARE_FIELD(16) J2CPP_DECLARE_FIELD(17) J2CPP_DECLARE_FIELD(18) J2CPP_DECLARE_FIELD(19) J2CPP_DECLARE_FIELD(20) J2CPP_DECLARE_FIELD(21) J2CPP_DECLARE_FIELD(22) J2CPP_DECLARE_FIELD(23) J2CPP_DECLARE_FIELD(24) J2CPP_DECLARE_FIELD(25) J2CPP_DECLARE_FIELD(26) J2CPP_DECLARE_FIELD(27) J2CPP_DECLARE_FIELD(28) J2CPP_DECLARE_FIELD(29) J2CPP_DECLARE_FIELD(30) J2CPP_DECLARE_FIELD(31) J2CPP_DECLARE_FIELD(32) J2CPP_DECLARE_FIELD(33) J2CPP_DECLARE_FIELD(34) J2CPP_DECLARE_FIELD(35) J2CPP_DECLARE_FIELD(36) J2CPP_DECLARE_FIELD(37) J2CPP_DECLARE_FIELD(38) J2CPP_DECLARE_FIELD(39) J2CPP_DECLARE_FIELD(40) J2CPP_DECLARE_FIELD(41) J2CPP_DECLARE_FIELD(42) J2CPP_DECLARE_FIELD(43) J2CPP_DECLARE_FIELD(44) J2CPP_DECLARE_FIELD(45) J2CPP_DECLARE_FIELD(46) J2CPP_DECLARE_FIELD(47) J2CPP_DECLARE_FIELD(48) J2CPP_DECLARE_FIELD(49) J2CPP_DECLARE_FIELD(50) J2CPP_DECLARE_FIELD(51) J2CPP_DECLARE_FIELD(52) J2CPP_DECLARE_FIELD(53) typedef View_::OnTouchListener OnTouchListener; typedef View_::BaseSavedState BaseSavedState; typedef View_::OnLongClickListener OnLongClickListener; typedef View_::OnClickListener OnClickListener; typedef View_::OnFocusChangeListener OnFocusChangeListener; typedef View_::OnKeyListener OnKeyListener; typedef View_::OnCreateContextMenuListener OnCreateContextMenuListener; typedef View_::MeasureSpec MeasureSpec; explicit View(jobject jobj) : object<View>(jobj) { } operator local_ref<java::lang::Object>() const; operator local_ref<android::graphics::drawable::Drawable_::Callback>() const; operator local_ref<android::view::accessibility::AccessibilityEventSource>() const; View(local_ref< android::content::Context > const&); View(local_ref< android::content::Context > const&, local_ref< android::util::AttributeSet > const&); View(local_ref< android::content::Context > const&, local_ref< android::util::AttributeSet > const&, jint); jint getVerticalFadingEdgeLength(); void setFadingEdgeLength(jint); jint getHorizontalFadingEdgeLength(); jint getVerticalScrollbarWidth(); void setOnFocusChangeListener(local_ref< android::view::View_::OnFocusChangeListener > const&); local_ref< android::view::View_::OnFocusChangeListener > getOnFocusChangeListener(); void setOnClickListener(local_ref< android::view::View_::OnClickListener > const&); void setOnLongClickListener(local_ref< android::view::View_::OnLongClickListener > const&); void setOnCreateContextMenuListener(local_ref< android::view::View_::OnCreateContextMenuListener > const&); jboolean performClick(); jboolean performLongClick(); jboolean showContextMenu(); void setOnKeyListener(local_ref< android::view::View_::OnKeyListener > const&); void setOnTouchListener(local_ref< android::view::View_::OnTouchListener > const&); jboolean requestRectangleOnScreen(local_ref< android::graphics::Rect > const&); jboolean requestRectangleOnScreen(local_ref< android::graphics::Rect > const&, jboolean); void clearFocus(); jboolean hasFocus(); jboolean hasFocusable(); void sendAccessibilityEvent(jint); void sendAccessibilityEventUnchecked(local_ref< android::view::accessibility::AccessibilityEvent > const&); jboolean dispatchPopulateAccessibilityEvent(local_ref< android::view::accessibility::AccessibilityEvent > const&); local_ref< java::lang::CharSequence > getContentDescription(); void setContentDescription(local_ref< java::lang::CharSequence > const&); jboolean isFocused(); local_ref< android::view::View > findFocus(); void setScrollContainer(jboolean); jint getDrawingCacheQuality(); void setDrawingCacheQuality(jint); jboolean getKeepScreenOn(); void setKeepScreenOn(jboolean); jint getNextFocusLeftId(); void setNextFocusLeftId(jint); jint getNextFocusRightId(); void setNextFocusRightId(jint); jint getNextFocusUpId(); void setNextFocusUpId(jint); jint getNextFocusDownId(); void setNextFocusDownId(jint); jboolean isShown(); jint getVisibility(); void setVisibility(jint); jboolean isEnabled(); void setEnabled(jboolean); void setFocusable(jboolean); void setFocusableInTouchMode(jboolean); void setSoundEffectsEnabled(jboolean); jboolean isSoundEffectsEnabled(); void setHapticFeedbackEnabled(jboolean); jboolean isHapticFeedbackEnabled(); void setWillNotDraw(jboolean); jboolean willNotDraw(); void setWillNotCacheDrawing(jboolean); jboolean willNotCacheDrawing(); jboolean isClickable(); void setClickable(jboolean); jboolean isLongClickable(); void setLongClickable(jboolean); void setPressed(jboolean); jboolean isPressed(); jboolean isSaveEnabled(); void setSaveEnabled(jboolean); jboolean isFocusable(); jboolean isFocusableInTouchMode(); local_ref< android::view::View > focusSearch(jint); jboolean dispatchUnhandledMove(local_ref< android::view::View > const&, jint); local_ref< java::util::ArrayList > getFocusables(jint); void addFocusables(local_ref< java::util::ArrayList > const&, jint); void addFocusables(local_ref< java::util::ArrayList > const&, jint, jint); local_ref< java::util::ArrayList > getTouchables(); void addTouchables(local_ref< java::util::ArrayList > const&); jboolean requestFocus(); jboolean requestFocus(jint); jboolean requestFocus(jint, local_ref< android::graphics::Rect > const&); jboolean requestFocusFromTouch(); void onStartTemporaryDetach(); void onFinishTemporaryDetach(); local_ref< android::view::KeyEvent_::DispatcherState > getKeyDispatcherState(); jboolean dispatchKeyEventPreIme(local_ref< android::view::KeyEvent > const&); jboolean dispatchKeyEvent(local_ref< android::view::KeyEvent > const&); jboolean dispatchKeyShortcutEvent(local_ref< android::view::KeyEvent > const&); jboolean dispatchTouchEvent(local_ref< android::view::MotionEvent > const&); jboolean dispatchTrackballEvent(local_ref< android::view::MotionEvent > const&); void dispatchWindowFocusChanged(jboolean); void onWindowFocusChanged(jboolean); jboolean hasWindowFocus(); void dispatchWindowVisibilityChanged(jint); jint getWindowVisibility(); void getWindowVisibleDisplayFrame(local_ref< android::graphics::Rect > const&); jboolean isInTouchMode(); local_ref< android::content::Context > getContext(); jboolean onKeyPreIme(jint, local_ref< android::view::KeyEvent > const&); jboolean onKeyDown(jint, local_ref< android::view::KeyEvent > const&); jboolean onKeyLongPress(jint, local_ref< android::view::KeyEvent > const&); jboolean onKeyUp(jint, local_ref< android::view::KeyEvent > const&); jboolean onKeyMultiple(jint, jint, local_ref< android::view::KeyEvent > const&); jboolean onKeyShortcut(jint, local_ref< android::view::KeyEvent > const&); jboolean onCheckIsTextEditor(); local_ref< android::view::inputmethod::InputConnection > onCreateInputConnection(local_ref< android::view::inputmethod::EditorInfo > const&); jboolean checkInputConnectionProxy(local_ref< android::view::View > const&); void createContextMenu(local_ref< android::view::ContextMenu > const&); jboolean onTrackballEvent(local_ref< android::view::MotionEvent > const&); jboolean onTouchEvent(local_ref< android::view::MotionEvent > const&); void cancelLongPress(); void setTouchDelegate(local_ref< android::view::TouchDelegate > const&); local_ref< android::view::TouchDelegate > getTouchDelegate(); void bringToFront(); local_ref< android::view::ViewParent > getParent(); jint getScrollX(); jint getScrollY(); jint getWidth(); jint getHeight(); void getDrawingRect(local_ref< android::graphics::Rect > const&); jint getMeasuredWidth(); jint getMeasuredHeight(); jint getTop(); jint getBottom(); jint getLeft(); jint getRight(); void getHitRect(local_ref< android::graphics::Rect > const&); void getFocusedRect(local_ref< android::graphics::Rect > const&); jboolean getGlobalVisibleRect(local_ref< android::graphics::Rect > const&, local_ref< android::graphics::Point > const&); jboolean getGlobalVisibleRect(local_ref< android::graphics::Rect > const&); jboolean getLocalVisibleRect(local_ref< android::graphics::Rect > const&); void offsetTopAndBottom(jint); void offsetLeftAndRight(jint); local_ref< android::view::ViewGroup_::LayoutParams > getLayoutParams(); void setLayoutParams(local_ref< android::view::ViewGroup_::LayoutParams > const&); void scrollTo(jint, jint); void scrollBy(jint, jint); void invalidate(local_ref< android::graphics::Rect > const&); void invalidate(jint, jint, jint, jint); void invalidate(); jboolean isOpaque(); local_ref< android::os::Handler > getHandler(); jboolean post(local_ref< java::lang::Runnable > const&); jboolean postDelayed(local_ref< java::lang::Runnable > const&, jlong); jboolean removeCallbacks(local_ref< java::lang::Runnable > const&); void postInvalidate(); void postInvalidate(jint, jint, jint, jint); void postInvalidateDelayed(jlong); void postInvalidateDelayed(jlong, jint, jint, jint, jint); void computeScroll(); jboolean isHorizontalFadingEdgeEnabled(); void setHorizontalFadingEdgeEnabled(jboolean); jboolean isVerticalFadingEdgeEnabled(); void setVerticalFadingEdgeEnabled(jboolean); jboolean isHorizontalScrollBarEnabled(); void setHorizontalScrollBarEnabled(jboolean); jboolean isVerticalScrollBarEnabled(); void setVerticalScrollBarEnabled(jboolean); void setScrollbarFadingEnabled(jboolean); jboolean isScrollbarFadingEnabled(); void setScrollBarStyle(jint); jint getScrollBarStyle(); local_ref< android::os::IBinder > getWindowToken(); local_ref< android::os::IBinder > getApplicationWindowToken(); void saveHierarchyState(local_ref< android::util::SparseArray > const&); void restoreHierarchyState(local_ref< android::util::SparseArray > const&); jlong getDrawingTime(); void setDuplicateParentStateEnabled(jboolean); jboolean isDuplicateParentStateEnabled(); void setDrawingCacheEnabled(jboolean); jboolean isDrawingCacheEnabled(); local_ref< android::graphics::Bitmap > getDrawingCache(); local_ref< android::graphics::Bitmap > getDrawingCache(jboolean); void destroyDrawingCache(); void setDrawingCacheBackgroundColor(jint); jint getDrawingCacheBackgroundColor(); void buildDrawingCache(); void buildDrawingCache(jboolean); jboolean isInEditMode(); void draw(local_ref< android::graphics::Canvas > const&); jint getSolidColor(); jboolean isLayoutRequested(); void layout(jint, jint, jint, jint); local_ref< android::content::res::Resources > getResources(); void invalidateDrawable(local_ref< android::graphics::drawable::Drawable > const&); void scheduleDrawable(local_ref< android::graphics::drawable::Drawable > const&, local_ref< java::lang::Runnable > const&, jlong); void unscheduleDrawable(local_ref< android::graphics::drawable::Drawable > const&, local_ref< java::lang::Runnable > const&); void unscheduleDrawable(local_ref< android::graphics::drawable::Drawable > const&); void refreshDrawableState(); local_ref< array<jint,1> > getDrawableState(); void setBackgroundColor(jint); void setBackgroundResource(jint); void setBackgroundDrawable(local_ref< android::graphics::drawable::Drawable > const&); local_ref< android::graphics::drawable::Drawable > getBackground(); void setPadding(jint, jint, jint, jint); jint getPaddingTop(); jint getPaddingBottom(); jint getPaddingLeft(); jint getPaddingRight(); void setSelected(jboolean); jboolean isSelected(); local_ref< android::view::ViewTreeObserver > getViewTreeObserver(); local_ref< android::view::View > getRootView(); void getLocationOnScreen(local_ref< array<jint,1> > const&); void getLocationInWindow(local_ref< array<jint,1> > const&); local_ref< android::view::View > findViewById(jint); local_ref< android::view::View > findViewWithTag(local_ref< java::lang::Object > const&); void setId(jint); jint getId(); local_ref< java::lang::Object > getTag(); void setTag(local_ref< java::lang::Object > const&); local_ref< java::lang::Object > getTag(jint); void setTag(jint, local_ref< java::lang::Object > const&); jint getBaseline(); void requestLayout(); void forceLayout(); void measure(jint, jint); static jint resolveSize(jint, jint); static jint getDefaultSize(jint, jint); void setMinimumHeight(jint); void setMinimumWidth(jint); local_ref< android::view::animation::Animation > getAnimation(); void startAnimation(local_ref< android::view::animation::Animation > const&); void clearAnimation(); void setAnimation(local_ref< android::view::animation::Animation > const&); void playSoundEffect(jint); jboolean performHapticFeedback(jint); jboolean performHapticFeedback(jint, jint); static local_ref< android::view::View > inflate(local_ref< android::content::Context > const&, jint, local_ref< android::view::ViewGroup > const&); static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(1), J2CPP_FIELD_SIGNATURE(1), jint > NO_ID; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(2), J2CPP_FIELD_SIGNATURE(2), jint > VISIBLE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(3), J2CPP_FIELD_SIGNATURE(3), jint > INVISIBLE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(4), J2CPP_FIELD_SIGNATURE(4), jint > GONE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(5), J2CPP_FIELD_SIGNATURE(5), jint > DRAWING_CACHE_QUALITY_LOW; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(6), J2CPP_FIELD_SIGNATURE(6), jint > DRAWING_CACHE_QUALITY_HIGH; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(7), J2CPP_FIELD_SIGNATURE(7), jint > DRAWING_CACHE_QUALITY_AUTO; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(8), J2CPP_FIELD_SIGNATURE(8), jint > SCROLLBARS_INSIDE_OVERLAY; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(9), J2CPP_FIELD_SIGNATURE(9), jint > SCROLLBARS_INSIDE_INSET; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(10), J2CPP_FIELD_SIGNATURE(10), jint > SCROLLBARS_OUTSIDE_OVERLAY; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(11), J2CPP_FIELD_SIGNATURE(11), jint > SCROLLBARS_OUTSIDE_INSET; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(12), J2CPP_FIELD_SIGNATURE(12), jint > KEEP_SCREEN_ON; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(13), J2CPP_FIELD_SIGNATURE(13), jint > SOUND_EFFECTS_ENABLED; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(14), J2CPP_FIELD_SIGNATURE(14), jint > HAPTIC_FEEDBACK_ENABLED; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(15), J2CPP_FIELD_SIGNATURE(15), jint > FOCUSABLES_ALL; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(16), J2CPP_FIELD_SIGNATURE(16), jint > FOCUSABLES_TOUCH_MODE; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(17), J2CPP_FIELD_SIGNATURE(17), jint > FOCUS_BACKWARD; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(18), J2CPP_FIELD_SIGNATURE(18), jint > FOCUS_FORWARD; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(19), J2CPP_FIELD_SIGNATURE(19), jint > FOCUS_LEFT; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(20), J2CPP_FIELD_SIGNATURE(20), jint > FOCUS_UP; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(21), J2CPP_FIELD_SIGNATURE(21), jint > FOCUS_RIGHT; static static_field< J2CPP_CLASS_NAME, J2CPP_FIELD_NAME(22), J2CPP_FIELD_SIGNATURE(22), jint > FOCUS_DOWN; }; //class View } //namespace view } //namespace android } //namespace j2cpp #endif //J2CPP_ANDROID_VIEW_VIEW_HPP_DECL #else //J2CPP_INCLUDE_IMPLEMENTATION #ifndef J2CPP_ANDROID_VIEW_VIEW_HPP_IMPL #define J2CPP_ANDROID_VIEW_VIEW_HPP_IMPL namespace j2cpp { android::view::View_::OnTouchListener::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } jboolean android::view::View_::OnTouchListener::onTouch(local_ref< android::view::View > const &a0, local_ref< android::view::MotionEvent > const &a1) { return call_method< android::view::View_::OnTouchListener::J2CPP_CLASS_NAME, android::view::View_::OnTouchListener::J2CPP_METHOD_NAME(0), android::view::View_::OnTouchListener::J2CPP_METHOD_SIGNATURE(0), jboolean >(get_jobject(), a0, a1); } J2CPP_DEFINE_CLASS(android::view::View_::OnTouchListener,"android/view/View$OnTouchListener") J2CPP_DEFINE_METHOD(android::view::View_::OnTouchListener,0,"onTouch","(Landroid/view/View;Landroid/view/MotionEvent;)Z") android::view::View_::BaseSavedState::operator local_ref<android::view::AbsSavedState>() const { return local_ref<android::view::AbsSavedState>(get_jobject()); } android::view::View_::BaseSavedState::BaseSavedState(local_ref< android::os::Parcel > const &a0) : object<android::view::View_::BaseSavedState>( call_new_object< android::view::View_::BaseSavedState::J2CPP_CLASS_NAME, android::view::View_::BaseSavedState::J2CPP_METHOD_NAME(0), android::view::View_::BaseSavedState::J2CPP_METHOD_SIGNATURE(0) >(a0) ) { } android::view::View_::BaseSavedState::BaseSavedState(local_ref< android::os::Parcelable > const &a0) : object<android::view::View_::BaseSavedState>( call_new_object< android::view::View_::BaseSavedState::J2CPP_CLASS_NAME, android::view::View_::BaseSavedState::J2CPP_METHOD_NAME(1), android::view::View_::BaseSavedState::J2CPP_METHOD_SIGNATURE(1) >(a0) ) { } static_field< android::view::View_::BaseSavedState::J2CPP_CLASS_NAME, android::view::View_::BaseSavedState::J2CPP_FIELD_NAME(0), android::view::View_::BaseSavedState::J2CPP_FIELD_SIGNATURE(0), local_ref< android::os::Parcelable_::Creator > > android::view::View_::BaseSavedState::CREATOR; J2CPP_DEFINE_CLASS(android::view::View_::BaseSavedState,"android/view/View$BaseSavedState") J2CPP_DEFINE_METHOD(android::view::View_::BaseSavedState,0,"<init>","(Landroid/os/Parcel;)V") J2CPP_DEFINE_METHOD(android::view::View_::BaseSavedState,1,"<init>","(Landroid/os/Parcelable;)V") J2CPP_DEFINE_METHOD(android::view::View_::BaseSavedState,2,"<clinit>","()V") J2CPP_DEFINE_FIELD(android::view::View_::BaseSavedState,0,"CREATOR","Landroid/os/Parcelable$Creator;") android::view::View_::OnLongClickListener::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } jboolean android::view::View_::OnLongClickListener::onLongClick(local_ref< android::view::View > const &a0) { return call_method< android::view::View_::OnLongClickListener::J2CPP_CLASS_NAME, android::view::View_::OnLongClickListener::J2CPP_METHOD_NAME(0), android::view::View_::OnLongClickListener::J2CPP_METHOD_SIGNATURE(0), jboolean >(get_jobject(), a0); } J2CPP_DEFINE_CLASS(android::view::View_::OnLongClickListener,"android/view/View$OnLongClickListener") J2CPP_DEFINE_METHOD(android::view::View_::OnLongClickListener,0,"onLongClick","(Landroid/view/View;)Z") android::view::View_::OnClickListener::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } void android::view::View_::OnClickListener::onClick(local_ref< android::view::View > const &a0) { return call_method< android::view::View_::OnClickListener::J2CPP_CLASS_NAME, android::view::View_::OnClickListener::J2CPP_METHOD_NAME(0), android::view::View_::OnClickListener::J2CPP_METHOD_SIGNATURE(0), void >(get_jobject(), a0); } J2CPP_DEFINE_CLASS(android::view::View_::OnClickListener,"android/view/View$OnClickListener") J2CPP_DEFINE_METHOD(android::view::View_::OnClickListener,0,"onClick","(Landroid/view/View;)V") android::view::View_::OnFocusChangeListener::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } void android::view::View_::OnFocusChangeListener::onFocusChange(local_ref< android::view::View > const &a0, jboolean a1) { return call_method< android::view::View_::OnFocusChangeListener::J2CPP_CLASS_NAME, android::view::View_::OnFocusChangeListener::J2CPP_METHOD_NAME(0), android::view::View_::OnFocusChangeListener::J2CPP_METHOD_SIGNATURE(0), void >(get_jobject(), a0, a1); } J2CPP_DEFINE_CLASS(android::view::View_::OnFocusChangeListener,"android/view/View$OnFocusChangeListener") J2CPP_DEFINE_METHOD(android::view::View_::OnFocusChangeListener,0,"onFocusChange","(Landroid/view/View;Z)V") android::view::View_::OnKeyListener::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } jboolean android::view::View_::OnKeyListener::onKey(local_ref< android::view::View > const &a0, jint a1, local_ref< android::view::KeyEvent > const &a2) { return call_method< android::view::View_::OnKeyListener::J2CPP_CLASS_NAME, android::view::View_::OnKeyListener::J2CPP_METHOD_NAME(0), android::view::View_::OnKeyListener::J2CPP_METHOD_SIGNATURE(0), jboolean >(get_jobject(), a0, a1, a2); } J2CPP_DEFINE_CLASS(android::view::View_::OnKeyListener,"android/view/View$OnKeyListener") J2CPP_DEFINE_METHOD(android::view::View_::OnKeyListener,0,"onKey","(Landroid/view/View;ILandroid/view/KeyEvent;)Z") android::view::View_::OnCreateContextMenuListener::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } void android::view::View_::OnCreateContextMenuListener::onCreateContextMenu(local_ref< android::view::ContextMenu > const &a0, local_ref< android::view::View > const &a1, local_ref< android::view::ContextMenu_::ContextMenuInfo > const &a2) { return call_method< android::view::View_::OnCreateContextMenuListener::J2CPP_CLASS_NAME, android::view::View_::OnCreateContextMenuListener::J2CPP_METHOD_NAME(0), android::view::View_::OnCreateContextMenuListener::J2CPP_METHOD_SIGNATURE(0), void >(get_jobject(), a0, a1, a2); } J2CPP_DEFINE_CLASS(android::view::View_::OnCreateContextMenuListener,"android/view/View$OnCreateContextMenuListener") J2CPP_DEFINE_METHOD(android::view::View_::OnCreateContextMenuListener,0,"onCreateContextMenu","(Landroid/view/ContextMenu;Landroid/view/View;Landroid/view/ContextMenu$ContextMenuInfo;)V") android::view::View_::MeasureSpec::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } android::view::View_::MeasureSpec::MeasureSpec() : object<android::view::View_::MeasureSpec>( call_new_object< android::view::View_::MeasureSpec::J2CPP_CLASS_NAME, android::view::View_::MeasureSpec::J2CPP_METHOD_NAME(0), android::view::View_::MeasureSpec::J2CPP_METHOD_SIGNATURE(0) >() ) { } jint android::view::View_::MeasureSpec::makeMeasureSpec(jint a0, jint a1) { return call_static_method< android::view::View_::MeasureSpec::J2CPP_CLASS_NAME, android::view::View_::MeasureSpec::J2CPP_METHOD_NAME(1), android::view::View_::MeasureSpec::J2CPP_METHOD_SIGNATURE(1), jint >(a0, a1); } jint android::view::View_::MeasureSpec::getMode(jint a0) { return call_static_method< android::view::View_::MeasureSpec::J2CPP_CLASS_NAME, android::view::View_::MeasureSpec::J2CPP_METHOD_NAME(2), android::view::View_::MeasureSpec::J2CPP_METHOD_SIGNATURE(2), jint >(a0); } jint android::view::View_::MeasureSpec::getSize(jint a0) { return call_static_method< android::view::View_::MeasureSpec::J2CPP_CLASS_NAME, android::view::View_::MeasureSpec::J2CPP_METHOD_NAME(3), android::view::View_::MeasureSpec::J2CPP_METHOD_SIGNATURE(3), jint >(a0); } local_ref< java::lang::String > android::view::View_::MeasureSpec::toString(jint a0) { return call_static_method< android::view::View_::MeasureSpec::J2CPP_CLASS_NAME, android::view::View_::MeasureSpec::J2CPP_METHOD_NAME(4), android::view::View_::MeasureSpec::J2CPP_METHOD_SIGNATURE(4), local_ref< java::lang::String > >(a0); } static_field< android::view::View_::MeasureSpec::J2CPP_CLASS_NAME, android::view::View_::MeasureSpec::J2CPP_FIELD_NAME(0), android::view::View_::MeasureSpec::J2CPP_FIELD_SIGNATURE(0), jint > android::view::View_::MeasureSpec::UNSPECIFIED; static_field< android::view::View_::MeasureSpec::J2CPP_CLASS_NAME, android::view::View_::MeasureSpec::J2CPP_FIELD_NAME(1), android::view::View_::MeasureSpec::J2CPP_FIELD_SIGNATURE(1), jint > android::view::View_::MeasureSpec::EXACTLY; static_field< android::view::View_::MeasureSpec::J2CPP_CLASS_NAME, android::view::View_::MeasureSpec::J2CPP_FIELD_NAME(2), android::view::View_::MeasureSpec::J2CPP_FIELD_SIGNATURE(2), jint > android::view::View_::MeasureSpec::AT_MOST; J2CPP_DEFINE_CLASS(android::view::View_::MeasureSpec,"android/view/View$MeasureSpec") J2CPP_DEFINE_METHOD(android::view::View_::MeasureSpec,0,"<init>","()V") J2CPP_DEFINE_METHOD(android::view::View_::MeasureSpec,1,"makeMeasureSpec","(II)I") J2CPP_DEFINE_METHOD(android::view::View_::MeasureSpec,2,"getMode","(I)I") J2CPP_DEFINE_METHOD(android::view::View_::MeasureSpec,3,"getSize","(I)I") J2CPP_DEFINE_METHOD(android::view::View_::MeasureSpec,4,"toString","(I)Ljava/lang/String;") J2CPP_DEFINE_FIELD(android::view::View_::MeasureSpec,0,"UNSPECIFIED","I") J2CPP_DEFINE_FIELD(android::view::View_::MeasureSpec,1,"EXACTLY","I") J2CPP_DEFINE_FIELD(android::view::View_::MeasureSpec,2,"AT_MOST","I") android::view::View::operator local_ref<java::lang::Object>() const { return local_ref<java::lang::Object>(get_jobject()); } android::view::View::operator local_ref<android::graphics::drawable::Drawable_::Callback>() const { return local_ref<android::graphics::drawable::Drawable_::Callback>(get_jobject()); } android::view::View::operator local_ref<android::view::accessibility::AccessibilityEventSource>() const { return local_ref<android::view::accessibility::AccessibilityEventSource>(get_jobject()); } android::view::View::View(local_ref< android::content::Context > const &a0) : object<android::view::View>( call_new_object< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(0), android::view::View::J2CPP_METHOD_SIGNATURE(0) >(a0) ) { } android::view::View::View(local_ref< android::content::Context > const &a0, local_ref< android::util::AttributeSet > const &a1) : object<android::view::View>( call_new_object< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(1), android::view::View::J2CPP_METHOD_SIGNATURE(1) >(a0, a1) ) { } android::view::View::View(local_ref< android::content::Context > const &a0, local_ref< android::util::AttributeSet > const &a1, jint a2) : object<android::view::View>( call_new_object< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(2), android::view::View::J2CPP_METHOD_SIGNATURE(2) >(a0, a1, a2) ) { } jint android::view::View::getVerticalFadingEdgeLength() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(5), android::view::View::J2CPP_METHOD_SIGNATURE(5), jint >(get_jobject()); } void android::view::View::setFadingEdgeLength(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(6), android::view::View::J2CPP_METHOD_SIGNATURE(6), void >(get_jobject(), a0); } jint android::view::View::getHorizontalFadingEdgeLength() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(7), android::view::View::J2CPP_METHOD_SIGNATURE(7), jint >(get_jobject()); } jint android::view::View::getVerticalScrollbarWidth() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(8), android::view::View::J2CPP_METHOD_SIGNATURE(8), jint >(get_jobject()); } void android::view::View::setOnFocusChangeListener(local_ref< android::view::View_::OnFocusChangeListener > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(11), android::view::View::J2CPP_METHOD_SIGNATURE(11), void >(get_jobject(), a0); } local_ref< android::view::View_::OnFocusChangeListener > android::view::View::getOnFocusChangeListener() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(12), android::view::View::J2CPP_METHOD_SIGNATURE(12), local_ref< android::view::View_::OnFocusChangeListener > >(get_jobject()); } void android::view::View::setOnClickListener(local_ref< android::view::View_::OnClickListener > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(13), android::view::View::J2CPP_METHOD_SIGNATURE(13), void >(get_jobject(), a0); } void android::view::View::setOnLongClickListener(local_ref< android::view::View_::OnLongClickListener > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(14), android::view::View::J2CPP_METHOD_SIGNATURE(14), void >(get_jobject(), a0); } void android::view::View::setOnCreateContextMenuListener(local_ref< android::view::View_::OnCreateContextMenuListener > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(15), android::view::View::J2CPP_METHOD_SIGNATURE(15), void >(get_jobject(), a0); } jboolean android::view::View::performClick() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(16), android::view::View::J2CPP_METHOD_SIGNATURE(16), jboolean >(get_jobject()); } jboolean android::view::View::performLongClick() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(17), android::view::View::J2CPP_METHOD_SIGNATURE(17), jboolean >(get_jobject()); } jboolean android::view::View::showContextMenu() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(18), android::view::View::J2CPP_METHOD_SIGNATURE(18), jboolean >(get_jobject()); } void android::view::View::setOnKeyListener(local_ref< android::view::View_::OnKeyListener > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(19), android::view::View::J2CPP_METHOD_SIGNATURE(19), void >(get_jobject(), a0); } void android::view::View::setOnTouchListener(local_ref< android::view::View_::OnTouchListener > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(20), android::view::View::J2CPP_METHOD_SIGNATURE(20), void >(get_jobject(), a0); } jboolean android::view::View::requestRectangleOnScreen(local_ref< android::graphics::Rect > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(21), android::view::View::J2CPP_METHOD_SIGNATURE(21), jboolean >(get_jobject(), a0); } jboolean android::view::View::requestRectangleOnScreen(local_ref< android::graphics::Rect > const &a0, jboolean a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(22), android::view::View::J2CPP_METHOD_SIGNATURE(22), jboolean >(get_jobject(), a0, a1); } void android::view::View::clearFocus() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(23), android::view::View::J2CPP_METHOD_SIGNATURE(23), void >(get_jobject()); } jboolean android::view::View::hasFocus() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(24), android::view::View::J2CPP_METHOD_SIGNATURE(24), jboolean >(get_jobject()); } jboolean android::view::View::hasFocusable() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(25), android::view::View::J2CPP_METHOD_SIGNATURE(25), jboolean >(get_jobject()); } void android::view::View::sendAccessibilityEvent(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(27), android::view::View::J2CPP_METHOD_SIGNATURE(27), void >(get_jobject(), a0); } void android::view::View::sendAccessibilityEventUnchecked(local_ref< android::view::accessibility::AccessibilityEvent > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(28), android::view::View::J2CPP_METHOD_SIGNATURE(28), void >(get_jobject(), a0); } jboolean android::view::View::dispatchPopulateAccessibilityEvent(local_ref< android::view::accessibility::AccessibilityEvent > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(29), android::view::View::J2CPP_METHOD_SIGNATURE(29), jboolean >(get_jobject(), a0); } local_ref< java::lang::CharSequence > android::view::View::getContentDescription() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(30), android::view::View::J2CPP_METHOD_SIGNATURE(30), local_ref< java::lang::CharSequence > >(get_jobject()); } void android::view::View::setContentDescription(local_ref< java::lang::CharSequence > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(31), android::view::View::J2CPP_METHOD_SIGNATURE(31), void >(get_jobject(), a0); } jboolean android::view::View::isFocused() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(32), android::view::View::J2CPP_METHOD_SIGNATURE(32), jboolean >(get_jobject()); } local_ref< android::view::View > android::view::View::findFocus() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(33), android::view::View::J2CPP_METHOD_SIGNATURE(33), local_ref< android::view::View > >(get_jobject()); } void android::view::View::setScrollContainer(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(34), android::view::View::J2CPP_METHOD_SIGNATURE(34), void >(get_jobject(), a0); } jint android::view::View::getDrawingCacheQuality() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(35), android::view::View::J2CPP_METHOD_SIGNATURE(35), jint >(get_jobject()); } void android::view::View::setDrawingCacheQuality(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(36), android::view::View::J2CPP_METHOD_SIGNATURE(36), void >(get_jobject(), a0); } jboolean android::view::View::getKeepScreenOn() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(37), android::view::View::J2CPP_METHOD_SIGNATURE(37), jboolean >(get_jobject()); } void android::view::View::setKeepScreenOn(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(38), android::view::View::J2CPP_METHOD_SIGNATURE(38), void >(get_jobject(), a0); } jint android::view::View::getNextFocusLeftId() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(39), android::view::View::J2CPP_METHOD_SIGNATURE(39), jint >(get_jobject()); } void android::view::View::setNextFocusLeftId(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(40), android::view::View::J2CPP_METHOD_SIGNATURE(40), void >(get_jobject(), a0); } jint android::view::View::getNextFocusRightId() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(41), android::view::View::J2CPP_METHOD_SIGNATURE(41), jint >(get_jobject()); } void android::view::View::setNextFocusRightId(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(42), android::view::View::J2CPP_METHOD_SIGNATURE(42), void >(get_jobject(), a0); } jint android::view::View::getNextFocusUpId() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(43), android::view::View::J2CPP_METHOD_SIGNATURE(43), jint >(get_jobject()); } void android::view::View::setNextFocusUpId(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(44), android::view::View::J2CPP_METHOD_SIGNATURE(44), void >(get_jobject(), a0); } jint android::view::View::getNextFocusDownId() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(45), android::view::View::J2CPP_METHOD_SIGNATURE(45), jint >(get_jobject()); } void android::view::View::setNextFocusDownId(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(46), android::view::View::J2CPP_METHOD_SIGNATURE(46), void >(get_jobject(), a0); } jboolean android::view::View::isShown() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(47), android::view::View::J2CPP_METHOD_SIGNATURE(47), jboolean >(get_jobject()); } jint android::view::View::getVisibility() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(49), android::view::View::J2CPP_METHOD_SIGNATURE(49), jint >(get_jobject()); } void android::view::View::setVisibility(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(50), android::view::View::J2CPP_METHOD_SIGNATURE(50), void >(get_jobject(), a0); } jboolean android::view::View::isEnabled() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(51), android::view::View::J2CPP_METHOD_SIGNATURE(51), jboolean >(get_jobject()); } void android::view::View::setEnabled(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(52), android::view::View::J2CPP_METHOD_SIGNATURE(52), void >(get_jobject(), a0); } void android::view::View::setFocusable(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(53), android::view::View::J2CPP_METHOD_SIGNATURE(53), void >(get_jobject(), a0); } void android::view::View::setFocusableInTouchMode(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(54), android::view::View::J2CPP_METHOD_SIGNATURE(54), void >(get_jobject(), a0); } void android::view::View::setSoundEffectsEnabled(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(55), android::view::View::J2CPP_METHOD_SIGNATURE(55), void >(get_jobject(), a0); } jboolean android::view::View::isSoundEffectsEnabled() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(56), android::view::View::J2CPP_METHOD_SIGNATURE(56), jboolean >(get_jobject()); } void android::view::View::setHapticFeedbackEnabled(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(57), android::view::View::J2CPP_METHOD_SIGNATURE(57), void >(get_jobject(), a0); } jboolean android::view::View::isHapticFeedbackEnabled() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(58), android::view::View::J2CPP_METHOD_SIGNATURE(58), jboolean >(get_jobject()); } void android::view::View::setWillNotDraw(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(59), android::view::View::J2CPP_METHOD_SIGNATURE(59), void >(get_jobject(), a0); } jboolean android::view::View::willNotDraw() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(60), android::view::View::J2CPP_METHOD_SIGNATURE(60), jboolean >(get_jobject()); } void android::view::View::setWillNotCacheDrawing(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(61), android::view::View::J2CPP_METHOD_SIGNATURE(61), void >(get_jobject(), a0); } jboolean android::view::View::willNotCacheDrawing() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(62), android::view::View::J2CPP_METHOD_SIGNATURE(62), jboolean >(get_jobject()); } jboolean android::view::View::isClickable() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(63), android::view::View::J2CPP_METHOD_SIGNATURE(63), jboolean >(get_jobject()); } void android::view::View::setClickable(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(64), android::view::View::J2CPP_METHOD_SIGNATURE(64), void >(get_jobject(), a0); } jboolean android::view::View::isLongClickable() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(65), android::view::View::J2CPP_METHOD_SIGNATURE(65), jboolean >(get_jobject()); } void android::view::View::setLongClickable(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(66), android::view::View::J2CPP_METHOD_SIGNATURE(66), void >(get_jobject(), a0); } void android::view::View::setPressed(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(67), android::view::View::J2CPP_METHOD_SIGNATURE(67), void >(get_jobject(), a0); } jboolean android::view::View::isPressed() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(69), android::view::View::J2CPP_METHOD_SIGNATURE(69), jboolean >(get_jobject()); } jboolean android::view::View::isSaveEnabled() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(70), android::view::View::J2CPP_METHOD_SIGNATURE(70), jboolean >(get_jobject()); } void android::view::View::setSaveEnabled(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(71), android::view::View::J2CPP_METHOD_SIGNATURE(71), void >(get_jobject(), a0); } jboolean android::view::View::isFocusable() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(72), android::view::View::J2CPP_METHOD_SIGNATURE(72), jboolean >(get_jobject()); } jboolean android::view::View::isFocusableInTouchMode() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(73), android::view::View::J2CPP_METHOD_SIGNATURE(73), jboolean >(get_jobject()); } local_ref< android::view::View > android::view::View::focusSearch(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(74), android::view::View::J2CPP_METHOD_SIGNATURE(74), local_ref< android::view::View > >(get_jobject(), a0); } jboolean android::view::View::dispatchUnhandledMove(local_ref< android::view::View > const &a0, jint a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(75), android::view::View::J2CPP_METHOD_SIGNATURE(75), jboolean >(get_jobject(), a0, a1); } local_ref< java::util::ArrayList > android::view::View::getFocusables(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(76), android::view::View::J2CPP_METHOD_SIGNATURE(76), local_ref< java::util::ArrayList > >(get_jobject(), a0); } void android::view::View::addFocusables(local_ref< java::util::ArrayList > const &a0, jint a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(77), android::view::View::J2CPP_METHOD_SIGNATURE(77), void >(get_jobject(), a0, a1); } void android::view::View::addFocusables(local_ref< java::util::ArrayList > const &a0, jint a1, jint a2) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(78), android::view::View::J2CPP_METHOD_SIGNATURE(78), void >(get_jobject(), a0, a1, a2); } local_ref< java::util::ArrayList > android::view::View::getTouchables() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(79), android::view::View::J2CPP_METHOD_SIGNATURE(79), local_ref< java::util::ArrayList > >(get_jobject()); } void android::view::View::addTouchables(local_ref< java::util::ArrayList > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(80), android::view::View::J2CPP_METHOD_SIGNATURE(80), void >(get_jobject(), a0); } jboolean android::view::View::requestFocus() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(81), android::view::View::J2CPP_METHOD_SIGNATURE(81), jboolean >(get_jobject()); } jboolean android::view::View::requestFocus(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(82), android::view::View::J2CPP_METHOD_SIGNATURE(82), jboolean >(get_jobject(), a0); } jboolean android::view::View::requestFocus(jint a0, local_ref< android::graphics::Rect > const &a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(83), android::view::View::J2CPP_METHOD_SIGNATURE(83), jboolean >(get_jobject(), a0, a1); } jboolean android::view::View::requestFocusFromTouch() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(84), android::view::View::J2CPP_METHOD_SIGNATURE(84), jboolean >(get_jobject()); } void android::view::View::onStartTemporaryDetach() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(85), android::view::View::J2CPP_METHOD_SIGNATURE(85), void >(get_jobject()); } void android::view::View::onFinishTemporaryDetach() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(86), android::view::View::J2CPP_METHOD_SIGNATURE(86), void >(get_jobject()); } local_ref< android::view::KeyEvent_::DispatcherState > android::view::View::getKeyDispatcherState() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(87), android::view::View::J2CPP_METHOD_SIGNATURE(87), local_ref< android::view::KeyEvent_::DispatcherState > >(get_jobject()); } jboolean android::view::View::dispatchKeyEventPreIme(local_ref< android::view::KeyEvent > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(88), android::view::View::J2CPP_METHOD_SIGNATURE(88), jboolean >(get_jobject(), a0); } jboolean android::view::View::dispatchKeyEvent(local_ref< android::view::KeyEvent > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(89), android::view::View::J2CPP_METHOD_SIGNATURE(89), jboolean >(get_jobject(), a0); } jboolean android::view::View::dispatchKeyShortcutEvent(local_ref< android::view::KeyEvent > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(90), android::view::View::J2CPP_METHOD_SIGNATURE(90), jboolean >(get_jobject(), a0); } jboolean android::view::View::dispatchTouchEvent(local_ref< android::view::MotionEvent > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(91), android::view::View::J2CPP_METHOD_SIGNATURE(91), jboolean >(get_jobject(), a0); } jboolean android::view::View::dispatchTrackballEvent(local_ref< android::view::MotionEvent > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(92), android::view::View::J2CPP_METHOD_SIGNATURE(92), jboolean >(get_jobject(), a0); } void android::view::View::dispatchWindowFocusChanged(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(93), android::view::View::J2CPP_METHOD_SIGNATURE(93), void >(get_jobject(), a0); } void android::view::View::onWindowFocusChanged(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(94), android::view::View::J2CPP_METHOD_SIGNATURE(94), void >(get_jobject(), a0); } jboolean android::view::View::hasWindowFocus() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(95), android::view::View::J2CPP_METHOD_SIGNATURE(95), jboolean >(get_jobject()); } void android::view::View::dispatchWindowVisibilityChanged(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(96), android::view::View::J2CPP_METHOD_SIGNATURE(96), void >(get_jobject(), a0); } jint android::view::View::getWindowVisibility() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(98), android::view::View::J2CPP_METHOD_SIGNATURE(98), jint >(get_jobject()); } void android::view::View::getWindowVisibleDisplayFrame(local_ref< android::graphics::Rect > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(99), android::view::View::J2CPP_METHOD_SIGNATURE(99), void >(get_jobject(), a0); } jboolean android::view::View::isInTouchMode() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(100), android::view::View::J2CPP_METHOD_SIGNATURE(100), jboolean >(get_jobject()); } local_ref< android::content::Context > android::view::View::getContext() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(101), android::view::View::J2CPP_METHOD_SIGNATURE(101), local_ref< android::content::Context > >(get_jobject()); } jboolean android::view::View::onKeyPreIme(jint a0, local_ref< android::view::KeyEvent > const &a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(102), android::view::View::J2CPP_METHOD_SIGNATURE(102), jboolean >(get_jobject(), a0, a1); } jboolean android::view::View::onKeyDown(jint a0, local_ref< android::view::KeyEvent > const &a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(103), android::view::View::J2CPP_METHOD_SIGNATURE(103), jboolean >(get_jobject(), a0, a1); } jboolean android::view::View::onKeyLongPress(jint a0, local_ref< android::view::KeyEvent > const &a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(104), android::view::View::J2CPP_METHOD_SIGNATURE(104), jboolean >(get_jobject(), a0, a1); } jboolean android::view::View::onKeyUp(jint a0, local_ref< android::view::KeyEvent > const &a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(105), android::view::View::J2CPP_METHOD_SIGNATURE(105), jboolean >(get_jobject(), a0, a1); } jboolean android::view::View::onKeyMultiple(jint a0, jint a1, local_ref< android::view::KeyEvent > const &a2) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(106), android::view::View::J2CPP_METHOD_SIGNATURE(106), jboolean >(get_jobject(), a0, a1, a2); } jboolean android::view::View::onKeyShortcut(jint a0, local_ref< android::view::KeyEvent > const &a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(107), android::view::View::J2CPP_METHOD_SIGNATURE(107), jboolean >(get_jobject(), a0, a1); } jboolean android::view::View::onCheckIsTextEditor() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(108), android::view::View::J2CPP_METHOD_SIGNATURE(108), jboolean >(get_jobject()); } local_ref< android::view::inputmethod::InputConnection > android::view::View::onCreateInputConnection(local_ref< android::view::inputmethod::EditorInfo > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(109), android::view::View::J2CPP_METHOD_SIGNATURE(109), local_ref< android::view::inputmethod::InputConnection > >(get_jobject(), a0); } jboolean android::view::View::checkInputConnectionProxy(local_ref< android::view::View > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(110), android::view::View::J2CPP_METHOD_SIGNATURE(110), jboolean >(get_jobject(), a0); } void android::view::View::createContextMenu(local_ref< android::view::ContextMenu > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(111), android::view::View::J2CPP_METHOD_SIGNATURE(111), void >(get_jobject(), a0); } jboolean android::view::View::onTrackballEvent(local_ref< android::view::MotionEvent > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(114), android::view::View::J2CPP_METHOD_SIGNATURE(114), jboolean >(get_jobject(), a0); } jboolean android::view::View::onTouchEvent(local_ref< android::view::MotionEvent > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(115), android::view::View::J2CPP_METHOD_SIGNATURE(115), jboolean >(get_jobject(), a0); } void android::view::View::cancelLongPress() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(116), android::view::View::J2CPP_METHOD_SIGNATURE(116), void >(get_jobject()); } void android::view::View::setTouchDelegate(local_ref< android::view::TouchDelegate > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(117), android::view::View::J2CPP_METHOD_SIGNATURE(117), void >(get_jobject(), a0); } local_ref< android::view::TouchDelegate > android::view::View::getTouchDelegate() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(118), android::view::View::J2CPP_METHOD_SIGNATURE(118), local_ref< android::view::TouchDelegate > >(get_jobject()); } void android::view::View::bringToFront() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(119), android::view::View::J2CPP_METHOD_SIGNATURE(119), void >(get_jobject()); } local_ref< android::view::ViewParent > android::view::View::getParent() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(123), android::view::View::J2CPP_METHOD_SIGNATURE(123), local_ref< android::view::ViewParent > >(get_jobject()); } jint android::view::View::getScrollX() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(124), android::view::View::J2CPP_METHOD_SIGNATURE(124), jint >(get_jobject()); } jint android::view::View::getScrollY() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(125), android::view::View::J2CPP_METHOD_SIGNATURE(125), jint >(get_jobject()); } jint android::view::View::getWidth() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(126), android::view::View::J2CPP_METHOD_SIGNATURE(126), jint >(get_jobject()); } jint android::view::View::getHeight() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(127), android::view::View::J2CPP_METHOD_SIGNATURE(127), jint >(get_jobject()); } void android::view::View::getDrawingRect(local_ref< android::graphics::Rect > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(128), android::view::View::J2CPP_METHOD_SIGNATURE(128), void >(get_jobject(), a0); } jint android::view::View::getMeasuredWidth() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(129), android::view::View::J2CPP_METHOD_SIGNATURE(129), jint >(get_jobject()); } jint android::view::View::getMeasuredHeight() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(130), android::view::View::J2CPP_METHOD_SIGNATURE(130), jint >(get_jobject()); } jint android::view::View::getTop() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(131), android::view::View::J2CPP_METHOD_SIGNATURE(131), jint >(get_jobject()); } jint android::view::View::getBottom() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(132), android::view::View::J2CPP_METHOD_SIGNATURE(132), jint >(get_jobject()); } jint android::view::View::getLeft() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(133), android::view::View::J2CPP_METHOD_SIGNATURE(133), jint >(get_jobject()); } jint android::view::View::getRight() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(134), android::view::View::J2CPP_METHOD_SIGNATURE(134), jint >(get_jobject()); } void android::view::View::getHitRect(local_ref< android::graphics::Rect > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(135), android::view::View::J2CPP_METHOD_SIGNATURE(135), void >(get_jobject(), a0); } void android::view::View::getFocusedRect(local_ref< android::graphics::Rect > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(136), android::view::View::J2CPP_METHOD_SIGNATURE(136), void >(get_jobject(), a0); } jboolean android::view::View::getGlobalVisibleRect(local_ref< android::graphics::Rect > const &a0, local_ref< android::graphics::Point > const &a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(137), android::view::View::J2CPP_METHOD_SIGNATURE(137), jboolean >(get_jobject(), a0, a1); } jboolean android::view::View::getGlobalVisibleRect(local_ref< android::graphics::Rect > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(138), android::view::View::J2CPP_METHOD_SIGNATURE(138), jboolean >(get_jobject(), a0); } jboolean android::view::View::getLocalVisibleRect(local_ref< android::graphics::Rect > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(139), android::view::View::J2CPP_METHOD_SIGNATURE(139), jboolean >(get_jobject(), a0); } void android::view::View::offsetTopAndBottom(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(140), android::view::View::J2CPP_METHOD_SIGNATURE(140), void >(get_jobject(), a0); } void android::view::View::offsetLeftAndRight(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(141), android::view::View::J2CPP_METHOD_SIGNATURE(141), void >(get_jobject(), a0); } local_ref< android::view::ViewGroup_::LayoutParams > android::view::View::getLayoutParams() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(142), android::view::View::J2CPP_METHOD_SIGNATURE(142), local_ref< android::view::ViewGroup_::LayoutParams > >(get_jobject()); } void android::view::View::setLayoutParams(local_ref< android::view::ViewGroup_::LayoutParams > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(143), android::view::View::J2CPP_METHOD_SIGNATURE(143), void >(get_jobject(), a0); } void android::view::View::scrollTo(jint a0, jint a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(144), android::view::View::J2CPP_METHOD_SIGNATURE(144), void >(get_jobject(), a0, a1); } void android::view::View::scrollBy(jint a0, jint a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(145), android::view::View::J2CPP_METHOD_SIGNATURE(145), void >(get_jobject(), a0, a1); } void android::view::View::invalidate(local_ref< android::graphics::Rect > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(149), android::view::View::J2CPP_METHOD_SIGNATURE(149), void >(get_jobject(), a0); } void android::view::View::invalidate(jint a0, jint a1, jint a2, jint a3) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(150), android::view::View::J2CPP_METHOD_SIGNATURE(150), void >(get_jobject(), a0, a1, a2, a3); } void android::view::View::invalidate() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(151), android::view::View::J2CPP_METHOD_SIGNATURE(151), void >(get_jobject()); } jboolean android::view::View::isOpaque() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(152), android::view::View::J2CPP_METHOD_SIGNATURE(152), jboolean >(get_jobject()); } local_ref< android::os::Handler > android::view::View::getHandler() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(153), android::view::View::J2CPP_METHOD_SIGNATURE(153), local_ref< android::os::Handler > >(get_jobject()); } jboolean android::view::View::post(local_ref< java::lang::Runnable > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(154), android::view::View::J2CPP_METHOD_SIGNATURE(154), jboolean >(get_jobject(), a0); } jboolean android::view::View::postDelayed(local_ref< java::lang::Runnable > const &a0, jlong a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(155), android::view::View::J2CPP_METHOD_SIGNATURE(155), jboolean >(get_jobject(), a0, a1); } jboolean android::view::View::removeCallbacks(local_ref< java::lang::Runnable > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(156), android::view::View::J2CPP_METHOD_SIGNATURE(156), jboolean >(get_jobject(), a0); } void android::view::View::postInvalidate() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(157), android::view::View::J2CPP_METHOD_SIGNATURE(157), void >(get_jobject()); } void android::view::View::postInvalidate(jint a0, jint a1, jint a2, jint a3) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(158), android::view::View::J2CPP_METHOD_SIGNATURE(158), void >(get_jobject(), a0, a1, a2, a3); } void android::view::View::postInvalidateDelayed(jlong a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(159), android::view::View::J2CPP_METHOD_SIGNATURE(159), void >(get_jobject(), a0); } void android::view::View::postInvalidateDelayed(jlong a0, jint a1, jint a2, jint a3, jint a4) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(160), android::view::View::J2CPP_METHOD_SIGNATURE(160), void >(get_jobject(), a0, a1, a2, a3, a4); } void android::view::View::computeScroll() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(161), android::view::View::J2CPP_METHOD_SIGNATURE(161), void >(get_jobject()); } jboolean android::view::View::isHorizontalFadingEdgeEnabled() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(162), android::view::View::J2CPP_METHOD_SIGNATURE(162), jboolean >(get_jobject()); } void android::view::View::setHorizontalFadingEdgeEnabled(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(163), android::view::View::J2CPP_METHOD_SIGNATURE(163), void >(get_jobject(), a0); } jboolean android::view::View::isVerticalFadingEdgeEnabled() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(164), android::view::View::J2CPP_METHOD_SIGNATURE(164), jboolean >(get_jobject()); } void android::view::View::setVerticalFadingEdgeEnabled(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(165), android::view::View::J2CPP_METHOD_SIGNATURE(165), void >(get_jobject(), a0); } jboolean android::view::View::isHorizontalScrollBarEnabled() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(170), android::view::View::J2CPP_METHOD_SIGNATURE(170), jboolean >(get_jobject()); } void android::view::View::setHorizontalScrollBarEnabled(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(171), android::view::View::J2CPP_METHOD_SIGNATURE(171), void >(get_jobject(), a0); } jboolean android::view::View::isVerticalScrollBarEnabled() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(172), android::view::View::J2CPP_METHOD_SIGNATURE(172), jboolean >(get_jobject()); } void android::view::View::setVerticalScrollBarEnabled(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(173), android::view::View::J2CPP_METHOD_SIGNATURE(173), void >(get_jobject(), a0); } void android::view::View::setScrollbarFadingEnabled(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(174), android::view::View::J2CPP_METHOD_SIGNATURE(174), void >(get_jobject(), a0); } jboolean android::view::View::isScrollbarFadingEnabled() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(175), android::view::View::J2CPP_METHOD_SIGNATURE(175), jboolean >(get_jobject()); } void android::view::View::setScrollBarStyle(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(176), android::view::View::J2CPP_METHOD_SIGNATURE(176), void >(get_jobject(), a0); } jint android::view::View::getScrollBarStyle() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(177), android::view::View::J2CPP_METHOD_SIGNATURE(177), jint >(get_jobject()); } local_ref< android::os::IBinder > android::view::View::getWindowToken() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(189), android::view::View::J2CPP_METHOD_SIGNATURE(189), local_ref< android::os::IBinder > >(get_jobject()); } local_ref< android::os::IBinder > android::view::View::getApplicationWindowToken() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(190), android::view::View::J2CPP_METHOD_SIGNATURE(190), local_ref< android::os::IBinder > >(get_jobject()); } void android::view::View::saveHierarchyState(local_ref< android::util::SparseArray > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(191), android::view::View::J2CPP_METHOD_SIGNATURE(191), void >(get_jobject(), a0); } void android::view::View::restoreHierarchyState(local_ref< android::util::SparseArray > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(194), android::view::View::J2CPP_METHOD_SIGNATURE(194), void >(get_jobject(), a0); } jlong android::view::View::getDrawingTime() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(197), android::view::View::J2CPP_METHOD_SIGNATURE(197), jlong >(get_jobject()); } void android::view::View::setDuplicateParentStateEnabled(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(198), android::view::View::J2CPP_METHOD_SIGNATURE(198), void >(get_jobject(), a0); } jboolean android::view::View::isDuplicateParentStateEnabled() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(199), android::view::View::J2CPP_METHOD_SIGNATURE(199), jboolean >(get_jobject()); } void android::view::View::setDrawingCacheEnabled(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(200), android::view::View::J2CPP_METHOD_SIGNATURE(200), void >(get_jobject(), a0); } jboolean android::view::View::isDrawingCacheEnabled() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(201), android::view::View::J2CPP_METHOD_SIGNATURE(201), jboolean >(get_jobject()); } local_ref< android::graphics::Bitmap > android::view::View::getDrawingCache() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(202), android::view::View::J2CPP_METHOD_SIGNATURE(202), local_ref< android::graphics::Bitmap > >(get_jobject()); } local_ref< android::graphics::Bitmap > android::view::View::getDrawingCache(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(203), android::view::View::J2CPP_METHOD_SIGNATURE(203), local_ref< android::graphics::Bitmap > >(get_jobject(), a0); } void android::view::View::destroyDrawingCache() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(204), android::view::View::J2CPP_METHOD_SIGNATURE(204), void >(get_jobject()); } void android::view::View::setDrawingCacheBackgroundColor(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(205), android::view::View::J2CPP_METHOD_SIGNATURE(205), void >(get_jobject(), a0); } jint android::view::View::getDrawingCacheBackgroundColor() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(206), android::view::View::J2CPP_METHOD_SIGNATURE(206), jint >(get_jobject()); } void android::view::View::buildDrawingCache() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(207), android::view::View::J2CPP_METHOD_SIGNATURE(207), void >(get_jobject()); } void android::view::View::buildDrawingCache(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(208), android::view::View::J2CPP_METHOD_SIGNATURE(208), void >(get_jobject(), a0); } jboolean android::view::View::isInEditMode() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(209), android::view::View::J2CPP_METHOD_SIGNATURE(209), jboolean >(get_jobject()); } void android::view::View::draw(local_ref< android::graphics::Canvas > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(215), android::view::View::J2CPP_METHOD_SIGNATURE(215), void >(get_jobject(), a0); } jint android::view::View::getSolidColor() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(216), android::view::View::J2CPP_METHOD_SIGNATURE(216), jint >(get_jobject()); } jboolean android::view::View::isLayoutRequested() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(217), android::view::View::J2CPP_METHOD_SIGNATURE(217), jboolean >(get_jobject()); } void android::view::View::layout(jint a0, jint a1, jint a2, jint a3) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(218), android::view::View::J2CPP_METHOD_SIGNATURE(218), void >(get_jobject(), a0, a1, a2, a3); } local_ref< android::content::res::Resources > android::view::View::getResources() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(221), android::view::View::J2CPP_METHOD_SIGNATURE(221), local_ref< android::content::res::Resources > >(get_jobject()); } void android::view::View::invalidateDrawable(local_ref< android::graphics::drawable::Drawable > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(222), android::view::View::J2CPP_METHOD_SIGNATURE(222), void >(get_jobject(), a0); } void android::view::View::scheduleDrawable(local_ref< android::graphics::drawable::Drawable > const &a0, local_ref< java::lang::Runnable > const &a1, jlong a2) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(223), android::view::View::J2CPP_METHOD_SIGNATURE(223), void >(get_jobject(), a0, a1, a2); } void android::view::View::unscheduleDrawable(local_ref< android::graphics::drawable::Drawable > const &a0, local_ref< java::lang::Runnable > const &a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(224), android::view::View::J2CPP_METHOD_SIGNATURE(224), void >(get_jobject(), a0, a1); } void android::view::View::unscheduleDrawable(local_ref< android::graphics::drawable::Drawable > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(225), android::view::View::J2CPP_METHOD_SIGNATURE(225), void >(get_jobject(), a0); } void android::view::View::refreshDrawableState() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(228), android::view::View::J2CPP_METHOD_SIGNATURE(228), void >(get_jobject()); } local_ref< array<jint,1> > android::view::View::getDrawableState() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(229), android::view::View::J2CPP_METHOD_SIGNATURE(229), local_ref< array<jint,1> > >(get_jobject()); } void android::view::View::setBackgroundColor(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(232), android::view::View::J2CPP_METHOD_SIGNATURE(232), void >(get_jobject(), a0); } void android::view::View::setBackgroundResource(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(233), android::view::View::J2CPP_METHOD_SIGNATURE(233), void >(get_jobject(), a0); } void android::view::View::setBackgroundDrawable(local_ref< android::graphics::drawable::Drawable > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(234), android::view::View::J2CPP_METHOD_SIGNATURE(234), void >(get_jobject(), a0); } local_ref< android::graphics::drawable::Drawable > android::view::View::getBackground() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(235), android::view::View::J2CPP_METHOD_SIGNATURE(235), local_ref< android::graphics::drawable::Drawable > >(get_jobject()); } void android::view::View::setPadding(jint a0, jint a1, jint a2, jint a3) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(236), android::view::View::J2CPP_METHOD_SIGNATURE(236), void >(get_jobject(), a0, a1, a2, a3); } jint android::view::View::getPaddingTop() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(237), android::view::View::J2CPP_METHOD_SIGNATURE(237), jint >(get_jobject()); } jint android::view::View::getPaddingBottom() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(238), android::view::View::J2CPP_METHOD_SIGNATURE(238), jint >(get_jobject()); } jint android::view::View::getPaddingLeft() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(239), android::view::View::J2CPP_METHOD_SIGNATURE(239), jint >(get_jobject()); } jint android::view::View::getPaddingRight() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(240), android::view::View::J2CPP_METHOD_SIGNATURE(240), jint >(get_jobject()); } void android::view::View::setSelected(jboolean a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(241), android::view::View::J2CPP_METHOD_SIGNATURE(241), void >(get_jobject(), a0); } jboolean android::view::View::isSelected() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(243), android::view::View::J2CPP_METHOD_SIGNATURE(243), jboolean >(get_jobject()); } local_ref< android::view::ViewTreeObserver > android::view::View::getViewTreeObserver() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(244), android::view::View::J2CPP_METHOD_SIGNATURE(244), local_ref< android::view::ViewTreeObserver > >(get_jobject()); } local_ref< android::view::View > android::view::View::getRootView() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(245), android::view::View::J2CPP_METHOD_SIGNATURE(245), local_ref< android::view::View > >(get_jobject()); } void android::view::View::getLocationOnScreen(local_ref< array<jint,1> > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(246), android::view::View::J2CPP_METHOD_SIGNATURE(246), void >(get_jobject(), a0); } void android::view::View::getLocationInWindow(local_ref< array<jint,1> > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(247), android::view::View::J2CPP_METHOD_SIGNATURE(247), void >(get_jobject(), a0); } local_ref< android::view::View > android::view::View::findViewById(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(248), android::view::View::J2CPP_METHOD_SIGNATURE(248), local_ref< android::view::View > >(get_jobject(), a0); } local_ref< android::view::View > android::view::View::findViewWithTag(local_ref< java::lang::Object > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(249), android::view::View::J2CPP_METHOD_SIGNATURE(249), local_ref< android::view::View > >(get_jobject(), a0); } void android::view::View::setId(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(250), android::view::View::J2CPP_METHOD_SIGNATURE(250), void >(get_jobject(), a0); } jint android::view::View::getId() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(251), android::view::View::J2CPP_METHOD_SIGNATURE(251), jint >(get_jobject()); } local_ref< java::lang::Object > android::view::View::getTag() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(252), android::view::View::J2CPP_METHOD_SIGNATURE(252), local_ref< java::lang::Object > >(get_jobject()); } void android::view::View::setTag(local_ref< java::lang::Object > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(253), android::view::View::J2CPP_METHOD_SIGNATURE(253), void >(get_jobject(), a0); } local_ref< java::lang::Object > android::view::View::getTag(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(254), android::view::View::J2CPP_METHOD_SIGNATURE(254), local_ref< java::lang::Object > >(get_jobject(), a0); } void android::view::View::setTag(jint a0, local_ref< java::lang::Object > const &a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(255), android::view::View::J2CPP_METHOD_SIGNATURE(255), void >(get_jobject(), a0, a1); } jint android::view::View::getBaseline() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(256), android::view::View::J2CPP_METHOD_SIGNATURE(256), jint >(get_jobject()); } void android::view::View::requestLayout() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(257), android::view::View::J2CPP_METHOD_SIGNATURE(257), void >(get_jobject()); } void android::view::View::forceLayout() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(258), android::view::View::J2CPP_METHOD_SIGNATURE(258), void >(get_jobject()); } void android::view::View::measure(jint a0, jint a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(259), android::view::View::J2CPP_METHOD_SIGNATURE(259), void >(get_jobject(), a0, a1); } jint android::view::View::resolveSize(jint a0, jint a1) { return call_static_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(262), android::view::View::J2CPP_METHOD_SIGNATURE(262), jint >(a0, a1); } jint android::view::View::getDefaultSize(jint a0, jint a1) { return call_static_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(263), android::view::View::J2CPP_METHOD_SIGNATURE(263), jint >(a0, a1); } void android::view::View::setMinimumHeight(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(266), android::view::View::J2CPP_METHOD_SIGNATURE(266), void >(get_jobject(), a0); } void android::view::View::setMinimumWidth(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(267), android::view::View::J2CPP_METHOD_SIGNATURE(267), void >(get_jobject(), a0); } local_ref< android::view::animation::Animation > android::view::View::getAnimation() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(268), android::view::View::J2CPP_METHOD_SIGNATURE(268), local_ref< android::view::animation::Animation > >(get_jobject()); } void android::view::View::startAnimation(local_ref< android::view::animation::Animation > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(269), android::view::View::J2CPP_METHOD_SIGNATURE(269), void >(get_jobject(), a0); } void android::view::View::clearAnimation() { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(270), android::view::View::J2CPP_METHOD_SIGNATURE(270), void >(get_jobject()); } void android::view::View::setAnimation(local_ref< android::view::animation::Animation > const &a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(271), android::view::View::J2CPP_METHOD_SIGNATURE(271), void >(get_jobject(), a0); } void android::view::View::playSoundEffect(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(275), android::view::View::J2CPP_METHOD_SIGNATURE(275), void >(get_jobject(), a0); } jboolean android::view::View::performHapticFeedback(jint a0) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(276), android::view::View::J2CPP_METHOD_SIGNATURE(276), jboolean >(get_jobject(), a0); } jboolean android::view::View::performHapticFeedback(jint a0, jint a1) { return call_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(277), android::view::View::J2CPP_METHOD_SIGNATURE(277), jboolean >(get_jobject(), a0, a1); } local_ref< android::view::View > android::view::View::inflate(local_ref< android::content::Context > const &a0, jint a1, local_ref< android::view::ViewGroup > const &a2) { return call_static_method< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_METHOD_NAME(278), android::view::View::J2CPP_METHOD_SIGNATURE(278), local_ref< android::view::View > >(a0, a1, a2); } static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(1), android::view::View::J2CPP_FIELD_SIGNATURE(1), jint > android::view::View::NO_ID; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(2), android::view::View::J2CPP_FIELD_SIGNATURE(2), jint > android::view::View::VISIBLE; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(3), android::view::View::J2CPP_FIELD_SIGNATURE(3), jint > android::view::View::INVISIBLE; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(4), android::view::View::J2CPP_FIELD_SIGNATURE(4), jint > android::view::View::GONE; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(5), android::view::View::J2CPP_FIELD_SIGNATURE(5), jint > android::view::View::DRAWING_CACHE_QUALITY_LOW; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(6), android::view::View::J2CPP_FIELD_SIGNATURE(6), jint > android::view::View::DRAWING_CACHE_QUALITY_HIGH; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(7), android::view::View::J2CPP_FIELD_SIGNATURE(7), jint > android::view::View::DRAWING_CACHE_QUALITY_AUTO; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(8), android::view::View::J2CPP_FIELD_SIGNATURE(8), jint > android::view::View::SCROLLBARS_INSIDE_OVERLAY; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(9), android::view::View::J2CPP_FIELD_SIGNATURE(9), jint > android::view::View::SCROLLBARS_INSIDE_INSET; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(10), android::view::View::J2CPP_FIELD_SIGNATURE(10), jint > android::view::View::SCROLLBARS_OUTSIDE_OVERLAY; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(11), android::view::View::J2CPP_FIELD_SIGNATURE(11), jint > android::view::View::SCROLLBARS_OUTSIDE_INSET; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(12), android::view::View::J2CPP_FIELD_SIGNATURE(12), jint > android::view::View::KEEP_SCREEN_ON; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(13), android::view::View::J2CPP_FIELD_SIGNATURE(13), jint > android::view::View::SOUND_EFFECTS_ENABLED; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(14), android::view::View::J2CPP_FIELD_SIGNATURE(14), jint > android::view::View::HAPTIC_FEEDBACK_ENABLED; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(15), android::view::View::J2CPP_FIELD_SIGNATURE(15), jint > android::view::View::FOCUSABLES_ALL; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(16), android::view::View::J2CPP_FIELD_SIGNATURE(16), jint > android::view::View::FOCUSABLES_TOUCH_MODE; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(17), android::view::View::J2CPP_FIELD_SIGNATURE(17), jint > android::view::View::FOCUS_BACKWARD; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(18), android::view::View::J2CPP_FIELD_SIGNATURE(18), jint > android::view::View::FOCUS_FORWARD; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(19), android::view::View::J2CPP_FIELD_SIGNATURE(19), jint > android::view::View::FOCUS_LEFT; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(20), android::view::View::J2CPP_FIELD_SIGNATURE(20), jint > android::view::View::FOCUS_UP; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(21), android::view::View::J2CPP_FIELD_SIGNATURE(21), jint > android::view::View::FOCUS_RIGHT; static_field< android::view::View::J2CPP_CLASS_NAME, android::view::View::J2CPP_FIELD_NAME(22), android::view::View::J2CPP_FIELD_SIGNATURE(22), jint > android::view::View::FOCUS_DOWN; J2CPP_DEFINE_CLASS(android::view::View,"android/view/View") J2CPP_DEFINE_METHOD(android::view::View,0,"<init>","(Landroid/content/Context;)V") J2CPP_DEFINE_METHOD(android::view::View,1,"<init>","(Landroid/content/Context;Landroid/util/AttributeSet;)V") J2CPP_DEFINE_METHOD(android::view::View,2,"<init>","(Landroid/content/Context;Landroid/util/AttributeSet;I)V") J2CPP_DEFINE_METHOD(android::view::View,3,"finalize","()V") J2CPP_DEFINE_METHOD(android::view::View,4,"initializeFadingEdge","(Landroid/content/res/TypedArray;)V") J2CPP_DEFINE_METHOD(android::view::View,5,"getVerticalFadingEdgeLength","()I") J2CPP_DEFINE_METHOD(android::view::View,6,"setFadingEdgeLength","(I)V") J2CPP_DEFINE_METHOD(android::view::View,7,"getHorizontalFadingEdgeLength","()I") J2CPP_DEFINE_METHOD(android::view::View,8,"getVerticalScrollbarWidth","()I") J2CPP_DEFINE_METHOD(android::view::View,9,"getHorizontalScrollbarHeight","()I") J2CPP_DEFINE_METHOD(android::view::View,10,"initializeScrollbars","(Landroid/content/res/TypedArray;)V") J2CPP_DEFINE_METHOD(android::view::View,11,"setOnFocusChangeListener","(Landroid/view/View$OnFocusChangeListener;)V") J2CPP_DEFINE_METHOD(android::view::View,12,"getOnFocusChangeListener","()Landroid/view/View$OnFocusChangeListener;") J2CPP_DEFINE_METHOD(android::view::View,13,"setOnClickListener","(Landroid/view/View$OnClickListener;)V") J2CPP_DEFINE_METHOD(android::view::View,14,"setOnLongClickListener","(Landroid/view/View$OnLongClickListener;)V") J2CPP_DEFINE_METHOD(android::view::View,15,"setOnCreateContextMenuListener","(Landroid/view/View$OnCreateContextMenuListener;)V") J2CPP_DEFINE_METHOD(android::view::View,16,"performClick","()Z") J2CPP_DEFINE_METHOD(android::view::View,17,"performLongClick","()Z") J2CPP_DEFINE_METHOD(android::view::View,18,"showContextMenu","()Z") J2CPP_DEFINE_METHOD(android::view::View,19,"setOnKeyListener","(Landroid/view/View$OnKeyListener;)V") J2CPP_DEFINE_METHOD(android::view::View,20,"setOnTouchListener","(Landroid/view/View$OnTouchListener;)V") J2CPP_DEFINE_METHOD(android::view::View,21,"requestRectangleOnScreen","(Landroid/graphics/Rect;)Z") J2CPP_DEFINE_METHOD(android::view::View,22,"requestRectangleOnScreen","(Landroid/graphics/Rect;Z)Z") J2CPP_DEFINE_METHOD(android::view::View,23,"clearFocus","()V") J2CPP_DEFINE_METHOD(android::view::View,24,"hasFocus","()Z") J2CPP_DEFINE_METHOD(android::view::View,25,"hasFocusable","()Z") J2CPP_DEFINE_METHOD(android::view::View,26,"onFocusChanged","(ZILandroid/graphics/Rect;)V") J2CPP_DEFINE_METHOD(android::view::View,27,"sendAccessibilityEvent","(I)V") J2CPP_DEFINE_METHOD(android::view::View,28,"sendAccessibilityEventUnchecked","(Landroid/view/accessibility/AccessibilityEvent;)V") J2CPP_DEFINE_METHOD(android::view::View,29,"dispatchPopulateAccessibilityEvent","(Landroid/view/accessibility/AccessibilityEvent;)Z") J2CPP_DEFINE_METHOD(android::view::View,30,"getContentDescription","()Ljava/lang/CharSequence;") J2CPP_DEFINE_METHOD(android::view::View,31,"setContentDescription","(Ljava/lang/CharSequence;)V") J2CPP_DEFINE_METHOD(android::view::View,32,"isFocused","()Z") J2CPP_DEFINE_METHOD(android::view::View,33,"findFocus","()Landroid/view/View;") J2CPP_DEFINE_METHOD(android::view::View,34,"setScrollContainer","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,35,"getDrawingCacheQuality","()I") J2CPP_DEFINE_METHOD(android::view::View,36,"setDrawingCacheQuality","(I)V") J2CPP_DEFINE_METHOD(android::view::View,37,"getKeepScreenOn","()Z") J2CPP_DEFINE_METHOD(android::view::View,38,"setKeepScreenOn","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,39,"getNextFocusLeftId","()I") J2CPP_DEFINE_METHOD(android::view::View,40,"setNextFocusLeftId","(I)V") J2CPP_DEFINE_METHOD(android::view::View,41,"getNextFocusRightId","()I") J2CPP_DEFINE_METHOD(android::view::View,42,"setNextFocusRightId","(I)V") J2CPP_DEFINE_METHOD(android::view::View,43,"getNextFocusUpId","()I") J2CPP_DEFINE_METHOD(android::view::View,44,"setNextFocusUpId","(I)V") J2CPP_DEFINE_METHOD(android::view::View,45,"getNextFocusDownId","()I") J2CPP_DEFINE_METHOD(android::view::View,46,"setNextFocusDownId","(I)V") J2CPP_DEFINE_METHOD(android::view::View,47,"isShown","()Z") J2CPP_DEFINE_METHOD(android::view::View,48,"fitSystemWindows","(Landroid/graphics/Rect;)Z") J2CPP_DEFINE_METHOD(android::view::View,49,"getVisibility","()I") J2CPP_DEFINE_METHOD(android::view::View,50,"setVisibility","(I)V") J2CPP_DEFINE_METHOD(android::view::View,51,"isEnabled","()Z") J2CPP_DEFINE_METHOD(android::view::View,52,"setEnabled","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,53,"setFocusable","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,54,"setFocusableInTouchMode","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,55,"setSoundEffectsEnabled","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,56,"isSoundEffectsEnabled","()Z") J2CPP_DEFINE_METHOD(android::view::View,57,"setHapticFeedbackEnabled","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,58,"isHapticFeedbackEnabled","()Z") J2CPP_DEFINE_METHOD(android::view::View,59,"setWillNotDraw","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,60,"willNotDraw","()Z") J2CPP_DEFINE_METHOD(android::view::View,61,"setWillNotCacheDrawing","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,62,"willNotCacheDrawing","()Z") J2CPP_DEFINE_METHOD(android::view::View,63,"isClickable","()Z") J2CPP_DEFINE_METHOD(android::view::View,64,"setClickable","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,65,"isLongClickable","()Z") J2CPP_DEFINE_METHOD(android::view::View,66,"setLongClickable","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,67,"setPressed","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,68,"dispatchSetPressed","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,69,"isPressed","()Z") J2CPP_DEFINE_METHOD(android::view::View,70,"isSaveEnabled","()Z") J2CPP_DEFINE_METHOD(android::view::View,71,"setSaveEnabled","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,72,"isFocusable","()Z") J2CPP_DEFINE_METHOD(android::view::View,73,"isFocusableInTouchMode","()Z") J2CPP_DEFINE_METHOD(android::view::View,74,"focusSearch","(I)Landroid/view/View;") J2CPP_DEFINE_METHOD(android::view::View,75,"dispatchUnhandledMove","(Landroid/view/View;I)Z") J2CPP_DEFINE_METHOD(android::view::View,76,"getFocusables","(I)Ljava/util/ArrayList;") J2CPP_DEFINE_METHOD(android::view::View,77,"addFocusables","(Ljava/util/ArrayList;I)V") J2CPP_DEFINE_METHOD(android::view::View,78,"addFocusables","(Ljava/util/ArrayList;II)V") J2CPP_DEFINE_METHOD(android::view::View,79,"getTouchables","()Ljava/util/ArrayList;") J2CPP_DEFINE_METHOD(android::view::View,80,"addTouchables","(Ljava/util/ArrayList;)V") J2CPP_DEFINE_METHOD(android::view::View,81,"requestFocus","()Z") J2CPP_DEFINE_METHOD(android::view::View,82,"requestFocus","(I)Z") J2CPP_DEFINE_METHOD(android::view::View,83,"requestFocus","(ILandroid/graphics/Rect;)Z") J2CPP_DEFINE_METHOD(android::view::View,84,"requestFocusFromTouch","()Z") J2CPP_DEFINE_METHOD(android::view::View,85,"onStartTemporaryDetach","()V") J2CPP_DEFINE_METHOD(android::view::View,86,"onFinishTemporaryDetach","()V") J2CPP_DEFINE_METHOD(android::view::View,87,"getKeyDispatcherState","()Landroid/view/KeyEvent$DispatcherState;") J2CPP_DEFINE_METHOD(android::view::View,88,"dispatchKeyEventPreIme","(Landroid/view/KeyEvent;)Z") J2CPP_DEFINE_METHOD(android::view::View,89,"dispatchKeyEvent","(Landroid/view/KeyEvent;)Z") J2CPP_DEFINE_METHOD(android::view::View,90,"dispatchKeyShortcutEvent","(Landroid/view/KeyEvent;)Z") J2CPP_DEFINE_METHOD(android::view::View,91,"dispatchTouchEvent","(Landroid/view/MotionEvent;)Z") J2CPP_DEFINE_METHOD(android::view::View,92,"dispatchTrackballEvent","(Landroid/view/MotionEvent;)Z") J2CPP_DEFINE_METHOD(android::view::View,93,"dispatchWindowFocusChanged","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,94,"onWindowFocusChanged","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,95,"hasWindowFocus","()Z") J2CPP_DEFINE_METHOD(android::view::View,96,"dispatchWindowVisibilityChanged","(I)V") J2CPP_DEFINE_METHOD(android::view::View,97,"onWindowVisibilityChanged","(I)V") J2CPP_DEFINE_METHOD(android::view::View,98,"getWindowVisibility","()I") J2CPP_DEFINE_METHOD(android::view::View,99,"getWindowVisibleDisplayFrame","(Landroid/graphics/Rect;)V") J2CPP_DEFINE_METHOD(android::view::View,100,"isInTouchMode","()Z") J2CPP_DEFINE_METHOD(android::view::View,101,"getContext","()Landroid/content/Context;") J2CPP_DEFINE_METHOD(android::view::View,102,"onKeyPreIme","(ILandroid/view/KeyEvent;)Z") J2CPP_DEFINE_METHOD(android::view::View,103,"onKeyDown","(ILandroid/view/KeyEvent;)Z") J2CPP_DEFINE_METHOD(android::view::View,104,"onKeyLongPress","(ILandroid/view/KeyEvent;)Z") J2CPP_DEFINE_METHOD(android::view::View,105,"onKeyUp","(ILandroid/view/KeyEvent;)Z") J2CPP_DEFINE_METHOD(android::view::View,106,"onKeyMultiple","(IILandroid/view/KeyEvent;)Z") J2CPP_DEFINE_METHOD(android::view::View,107,"onKeyShortcut","(ILandroid/view/KeyEvent;)Z") J2CPP_DEFINE_METHOD(android::view::View,108,"onCheckIsTextEditor","()Z") J2CPP_DEFINE_METHOD(android::view::View,109,"onCreateInputConnection","(Landroid/view/inputmethod/EditorInfo;)Landroid/view/inputmethod/InputConnection;") J2CPP_DEFINE_METHOD(android::view::View,110,"checkInputConnectionProxy","(Landroid/view/View;)Z") J2CPP_DEFINE_METHOD(android::view::View,111,"createContextMenu","(Landroid/view/ContextMenu;)V") J2CPP_DEFINE_METHOD(android::view::View,112,"getContextMenuInfo","()Landroid/view/ContextMenu$ContextMenuInfo;") J2CPP_DEFINE_METHOD(android::view::View,113,"onCreateContextMenu","(Landroid/view/ContextMenu;)V") J2CPP_DEFINE_METHOD(android::view::View,114,"onTrackballEvent","(Landroid/view/MotionEvent;)Z") J2CPP_DEFINE_METHOD(android::view::View,115,"onTouchEvent","(Landroid/view/MotionEvent;)Z") J2CPP_DEFINE_METHOD(android::view::View,116,"cancelLongPress","()V") J2CPP_DEFINE_METHOD(android::view::View,117,"setTouchDelegate","(Landroid/view/TouchDelegate;)V") J2CPP_DEFINE_METHOD(android::view::View,118,"getTouchDelegate","()Landroid/view/TouchDelegate;") J2CPP_DEFINE_METHOD(android::view::View,119,"bringToFront","()V") J2CPP_DEFINE_METHOD(android::view::View,120,"onScrollChanged","(IIII)V") J2CPP_DEFINE_METHOD(android::view::View,121,"onSizeChanged","(IIII)V") J2CPP_DEFINE_METHOD(android::view::View,122,"dispatchDraw","(Landroid/graphics/Canvas;)V") J2CPP_DEFINE_METHOD(android::view::View,123,"getParent","()Landroid/view/ViewParent;") J2CPP_DEFINE_METHOD(android::view::View,124,"getScrollX","()I") J2CPP_DEFINE_METHOD(android::view::View,125,"getScrollY","()I") J2CPP_DEFINE_METHOD(android::view::View,126,"getWidth","()I") J2CPP_DEFINE_METHOD(android::view::View,127,"getHeight","()I") J2CPP_DEFINE_METHOD(android::view::View,128,"getDrawingRect","(Landroid/graphics/Rect;)V") J2CPP_DEFINE_METHOD(android::view::View,129,"getMeasuredWidth","()I") J2CPP_DEFINE_METHOD(android::view::View,130,"getMeasuredHeight","()I") J2CPP_DEFINE_METHOD(android::view::View,131,"getTop","()I") J2CPP_DEFINE_METHOD(android::view::View,132,"getBottom","()I") J2CPP_DEFINE_METHOD(android::view::View,133,"getLeft","()I") J2CPP_DEFINE_METHOD(android::view::View,134,"getRight","()I") J2CPP_DEFINE_METHOD(android::view::View,135,"getHitRect","(Landroid/graphics/Rect;)V") J2CPP_DEFINE_METHOD(android::view::View,136,"getFocusedRect","(Landroid/graphics/Rect;)V") J2CPP_DEFINE_METHOD(android::view::View,137,"getGlobalVisibleRect","(Landroid/graphics/Rect;Landroid/graphics/Point;)Z") J2CPP_DEFINE_METHOD(android::view::View,138,"getGlobalVisibleRect","(Landroid/graphics/Rect;)Z") J2CPP_DEFINE_METHOD(android::view::View,139,"getLocalVisibleRect","(Landroid/graphics/Rect;)Z") J2CPP_DEFINE_METHOD(android::view::View,140,"offsetTopAndBottom","(I)V") J2CPP_DEFINE_METHOD(android::view::View,141,"offsetLeftAndRight","(I)V") J2CPP_DEFINE_METHOD(android::view::View,142,"getLayoutParams","()Landroid/view/ViewGroup$LayoutParams;") J2CPP_DEFINE_METHOD(android::view::View,143,"setLayoutParams","(Landroid/view/ViewGroup$LayoutParams;)V") J2CPP_DEFINE_METHOD(android::view::View,144,"scrollTo","(II)V") J2CPP_DEFINE_METHOD(android::view::View,145,"scrollBy","(II)V") J2CPP_DEFINE_METHOD(android::view::View,146,"awakenScrollBars","()Z") J2CPP_DEFINE_METHOD(android::view::View,147,"awakenScrollBars","(I)Z") J2CPP_DEFINE_METHOD(android::view::View,148,"awakenScrollBars","(IZ)Z") J2CPP_DEFINE_METHOD(android::view::View,149,"invalidate","(Landroid/graphics/Rect;)V") J2CPP_DEFINE_METHOD(android::view::View,150,"invalidate","(IIII)V") J2CPP_DEFINE_METHOD(android::view::View,151,"invalidate","()V") J2CPP_DEFINE_METHOD(android::view::View,152,"isOpaque","()Z") J2CPP_DEFINE_METHOD(android::view::View,153,"getHandler","()Landroid/os/Handler;") J2CPP_DEFINE_METHOD(android::view::View,154,"post","(Ljava/lang/Runnable;)Z") J2CPP_DEFINE_METHOD(android::view::View,155,"postDelayed","(Ljava/lang/Runnable;J)Z") J2CPP_DEFINE_METHOD(android::view::View,156,"removeCallbacks","(Ljava/lang/Runnable;)Z") J2CPP_DEFINE_METHOD(android::view::View,157,"postInvalidate","()V") J2CPP_DEFINE_METHOD(android::view::View,158,"postInvalidate","(IIII)V") J2CPP_DEFINE_METHOD(android::view::View,159,"postInvalidateDelayed","(J)V") J2CPP_DEFINE_METHOD(android::view::View,160,"postInvalidateDelayed","(JIIII)V") J2CPP_DEFINE_METHOD(android::view::View,161,"computeScroll","()V") J2CPP_DEFINE_METHOD(android::view::View,162,"isHorizontalFadingEdgeEnabled","()Z") J2CPP_DEFINE_METHOD(android::view::View,163,"setHorizontalFadingEdgeEnabled","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,164,"isVerticalFadingEdgeEnabled","()Z") J2CPP_DEFINE_METHOD(android::view::View,165,"setVerticalFadingEdgeEnabled","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,166,"getTopFadingEdgeStrength","()F") J2CPP_DEFINE_METHOD(android::view::View,167,"getBottomFadingEdgeStrength","()F") J2CPP_DEFINE_METHOD(android::view::View,168,"getLeftFadingEdgeStrength","()F") J2CPP_DEFINE_METHOD(android::view::View,169,"getRightFadingEdgeStrength","()F") J2CPP_DEFINE_METHOD(android::view::View,170,"isHorizontalScrollBarEnabled","()Z") J2CPP_DEFINE_METHOD(android::view::View,171,"setHorizontalScrollBarEnabled","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,172,"isVerticalScrollBarEnabled","()Z") J2CPP_DEFINE_METHOD(android::view::View,173,"setVerticalScrollBarEnabled","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,174,"setScrollbarFadingEnabled","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,175,"isScrollbarFadingEnabled","()Z") J2CPP_DEFINE_METHOD(android::view::View,176,"setScrollBarStyle","(I)V") J2CPP_DEFINE_METHOD(android::view::View,177,"getScrollBarStyle","()I") J2CPP_DEFINE_METHOD(android::view::View,178,"computeHorizontalScrollRange","()I") J2CPP_DEFINE_METHOD(android::view::View,179,"computeHorizontalScrollOffset","()I") J2CPP_DEFINE_METHOD(android::view::View,180,"computeHorizontalScrollExtent","()I") J2CPP_DEFINE_METHOD(android::view::View,181,"computeVerticalScrollRange","()I") J2CPP_DEFINE_METHOD(android::view::View,182,"computeVerticalScrollOffset","()I") J2CPP_DEFINE_METHOD(android::view::View,183,"computeVerticalScrollExtent","()I") J2CPP_DEFINE_METHOD(android::view::View,184,"onDrawScrollBars","(Landroid/graphics/Canvas;)V") J2CPP_DEFINE_METHOD(android::view::View,185,"onDraw","(Landroid/graphics/Canvas;)V") J2CPP_DEFINE_METHOD(android::view::View,186,"onAttachedToWindow","()V") J2CPP_DEFINE_METHOD(android::view::View,187,"onDetachedFromWindow","()V") J2CPP_DEFINE_METHOD(android::view::View,188,"getWindowAttachCount","()I") J2CPP_DEFINE_METHOD(android::view::View,189,"getWindowToken","()Landroid/os/IBinder;") J2CPP_DEFINE_METHOD(android::view::View,190,"getApplicationWindowToken","()Landroid/os/IBinder;") J2CPP_DEFINE_METHOD(android::view::View,191,"saveHierarchyState","(Landroid/util/SparseArray;)V") J2CPP_DEFINE_METHOD(android::view::View,192,"dispatchSaveInstanceState","(Landroid/util/SparseArray;)V") J2CPP_DEFINE_METHOD(android::view::View,193,"onSaveInstanceState","()Landroid/os/Parcelable;") J2CPP_DEFINE_METHOD(android::view::View,194,"restoreHierarchyState","(Landroid/util/SparseArray;)V") J2CPP_DEFINE_METHOD(android::view::View,195,"dispatchRestoreInstanceState","(Landroid/util/SparseArray;)V") J2CPP_DEFINE_METHOD(android::view::View,196,"onRestoreInstanceState","(Landroid/os/Parcelable;)V") J2CPP_DEFINE_METHOD(android::view::View,197,"getDrawingTime","()J") J2CPP_DEFINE_METHOD(android::view::View,198,"setDuplicateParentStateEnabled","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,199,"isDuplicateParentStateEnabled","()Z") J2CPP_DEFINE_METHOD(android::view::View,200,"setDrawingCacheEnabled","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,201,"isDrawingCacheEnabled","()Z") J2CPP_DEFINE_METHOD(android::view::View,202,"getDrawingCache","()Landroid/graphics/Bitmap;") J2CPP_DEFINE_METHOD(android::view::View,203,"getDrawingCache","(Z)Landroid/graphics/Bitmap;") J2CPP_DEFINE_METHOD(android::view::View,204,"destroyDrawingCache","()V") J2CPP_DEFINE_METHOD(android::view::View,205,"setDrawingCacheBackgroundColor","(I)V") J2CPP_DEFINE_METHOD(android::view::View,206,"getDrawingCacheBackgroundColor","()I") J2CPP_DEFINE_METHOD(android::view::View,207,"buildDrawingCache","()V") J2CPP_DEFINE_METHOD(android::view::View,208,"buildDrawingCache","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,209,"isInEditMode","()Z") J2CPP_DEFINE_METHOD(android::view::View,210,"isPaddingOffsetRequired","()Z") J2CPP_DEFINE_METHOD(android::view::View,211,"getLeftPaddingOffset","()I") J2CPP_DEFINE_METHOD(android::view::View,212,"getRightPaddingOffset","()I") J2CPP_DEFINE_METHOD(android::view::View,213,"getTopPaddingOffset","()I") J2CPP_DEFINE_METHOD(android::view::View,214,"getBottomPaddingOffset","()I") J2CPP_DEFINE_METHOD(android::view::View,215,"draw","(Landroid/graphics/Canvas;)V") J2CPP_DEFINE_METHOD(android::view::View,216,"getSolidColor","()I") J2CPP_DEFINE_METHOD(android::view::View,217,"isLayoutRequested","()Z") J2CPP_DEFINE_METHOD(android::view::View,218,"layout","(IIII)V") J2CPP_DEFINE_METHOD(android::view::View,219,"onLayout","(ZIIII)V") J2CPP_DEFINE_METHOD(android::view::View,220,"onFinishInflate","()V") J2CPP_DEFINE_METHOD(android::view::View,221,"getResources","()Landroid/content/res/Resources;") J2CPP_DEFINE_METHOD(android::view::View,222,"invalidateDrawable","(Landroid/graphics/drawable/Drawable;)V") J2CPP_DEFINE_METHOD(android::view::View,223,"scheduleDrawable","(Landroid/graphics/drawable/Drawable;Ljava/lang/Runnable;J)V") J2CPP_DEFINE_METHOD(android::view::View,224,"unscheduleDrawable","(Landroid/graphics/drawable/Drawable;Ljava/lang/Runnable;)V") J2CPP_DEFINE_METHOD(android::view::View,225,"unscheduleDrawable","(Landroid/graphics/drawable/Drawable;)V") J2CPP_DEFINE_METHOD(android::view::View,226,"verifyDrawable","(Landroid/graphics/drawable/Drawable;)Z") J2CPP_DEFINE_METHOD(android::view::View,227,"drawableStateChanged","()V") J2CPP_DEFINE_METHOD(android::view::View,228,"refreshDrawableState","()V") J2CPP_DEFINE_METHOD(android::view::View,229,"getDrawableState","()[I") J2CPP_DEFINE_METHOD(android::view::View,230,"onCreateDrawableState","(I)[I") J2CPP_DEFINE_METHOD(android::view::View,231,"mergeDrawableStates","([I[I)[I") J2CPP_DEFINE_METHOD(android::view::View,232,"setBackgroundColor","(I)V") J2CPP_DEFINE_METHOD(android::view::View,233,"setBackgroundResource","(I)V") J2CPP_DEFINE_METHOD(android::view::View,234,"setBackgroundDrawable","(Landroid/graphics/drawable/Drawable;)V") J2CPP_DEFINE_METHOD(android::view::View,235,"getBackground","()Landroid/graphics/drawable/Drawable;") J2CPP_DEFINE_METHOD(android::view::View,236,"setPadding","(IIII)V") J2CPP_DEFINE_METHOD(android::view::View,237,"getPaddingTop","()I") J2CPP_DEFINE_METHOD(android::view::View,238,"getPaddingBottom","()I") J2CPP_DEFINE_METHOD(android::view::View,239,"getPaddingLeft","()I") J2CPP_DEFINE_METHOD(android::view::View,240,"getPaddingRight","()I") J2CPP_DEFINE_METHOD(android::view::View,241,"setSelected","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,242,"dispatchSetSelected","(Z)V") J2CPP_DEFINE_METHOD(android::view::View,243,"isSelected","()Z") J2CPP_DEFINE_METHOD(android::view::View,244,"getViewTreeObserver","()Landroid/view/ViewTreeObserver;") J2CPP_DEFINE_METHOD(android::view::View,245,"getRootView","()Landroid/view/View;") J2CPP_DEFINE_METHOD(android::view::View,246,"getLocationOnScreen","([I)V") J2CPP_DEFINE_METHOD(android::view::View,247,"getLocationInWindow","([I)V") J2CPP_DEFINE_METHOD(android::view::View,248,"findViewById","(I)Landroid/view/View;") J2CPP_DEFINE_METHOD(android::view::View,249,"findViewWithTag","(Ljava/lang/Object;)Landroid/view/View;") J2CPP_DEFINE_METHOD(android::view::View,250,"setId","(I)V") J2CPP_DEFINE_METHOD(android::view::View,251,"getId","()I") J2CPP_DEFINE_METHOD(android::view::View,252,"getTag","()Ljava/lang/Object;") J2CPP_DEFINE_METHOD(android::view::View,253,"setTag","(Ljava/lang/Object;)V") J2CPP_DEFINE_METHOD(android::view::View,254,"getTag","(I)Ljava/lang/Object;") J2CPP_DEFINE_METHOD(android::view::View,255,"setTag","(ILjava/lang/Object;)V") J2CPP_DEFINE_METHOD(android::view::View,256,"getBaseline","()I") J2CPP_DEFINE_METHOD(android::view::View,257,"requestLayout","()V") J2CPP_DEFINE_METHOD(android::view::View,258,"forceLayout","()V") J2CPP_DEFINE_METHOD(android::view::View,259,"measure","(II)V") J2CPP_DEFINE_METHOD(android::view::View,260,"onMeasure","(II)V") J2CPP_DEFINE_METHOD(android::view::View,261,"setMeasuredDimension","(II)V") J2CPP_DEFINE_METHOD(android::view::View,262,"resolveSize","(II)I") J2CPP_DEFINE_METHOD(android::view::View,263,"getDefaultSize","(II)I") J2CPP_DEFINE_METHOD(android::view::View,264,"getSuggestedMinimumHeight","()I") J2CPP_DEFINE_METHOD(android::view::View,265,"getSuggestedMinimumWidth","()I") J2CPP_DEFINE_METHOD(android::view::View,266,"setMinimumHeight","(I)V") J2CPP_DEFINE_METHOD(android::view::View,267,"setMinimumWidth","(I)V") J2CPP_DEFINE_METHOD(android::view::View,268,"getAnimation","()Landroid/view/animation/Animation;") J2CPP_DEFINE_METHOD(android::view::View,269,"startAnimation","(Landroid/view/animation/Animation;)V") J2CPP_DEFINE_METHOD(android::view::View,270,"clearAnimation","()V") J2CPP_DEFINE_METHOD(android::view::View,271,"setAnimation","(Landroid/view/animation/Animation;)V") J2CPP_DEFINE_METHOD(android::view::View,272,"onAnimationStart","()V") J2CPP_DEFINE_METHOD(android::view::View,273,"onAnimationEnd","()V") J2CPP_DEFINE_METHOD(android::view::View,274,"onSetAlpha","(I)Z") J2CPP_DEFINE_METHOD(android::view::View,275,"playSoundEffect","(I)V") J2CPP_DEFINE_METHOD(android::view::View,276,"performHapticFeedback","(I)Z") J2CPP_DEFINE_METHOD(android::view::View,277,"performHapticFeedback","(II)Z") J2CPP_DEFINE_METHOD(android::view::View,278,"inflate","(Landroid/content/Context;ILandroid/view/ViewGroup;)Landroid/view/View;") J2CPP_DEFINE_METHOD(android::view::View,279,"<clinit>","()V") J2CPP_DEFINE_FIELD(android::view::View,0,"VIEW_LOG_TAG","Ljava/lang/String;") J2CPP_DEFINE_FIELD(android::view::View,1,"NO_ID","I") J2CPP_DEFINE_FIELD(android::view::View,2,"VISIBLE","I") J2CPP_DEFINE_FIELD(android::view::View,3,"INVISIBLE","I") J2CPP_DEFINE_FIELD(android::view::View,4,"GONE","I") J2CPP_DEFINE_FIELD(android::view::View,5,"DRAWING_CACHE_QUALITY_LOW","I") J2CPP_DEFINE_FIELD(android::view::View,6,"DRAWING_CACHE_QUALITY_HIGH","I") J2CPP_DEFINE_FIELD(android::view::View,7,"DRAWING_CACHE_QUALITY_AUTO","I") J2CPP_DEFINE_FIELD(android::view::View,8,"SCROLLBARS_INSIDE_OVERLAY","I") J2CPP_DEFINE_FIELD(android::view::View,9,"SCROLLBARS_INSIDE_INSET","I") J2CPP_DEFINE_FIELD(android::view::View,10,"SCROLLBARS_OUTSIDE_OVERLAY","I") J2CPP_DEFINE_FIELD(android::view::View,11,"SCROLLBARS_OUTSIDE_INSET","I") J2CPP_DEFINE_FIELD(android::view::View,12,"KEEP_SCREEN_ON","I") J2CPP_DEFINE_FIELD(android::view::View,13,"SOUND_EFFECTS_ENABLED","I") J2CPP_DEFINE_FIELD(android::view::View,14,"HAPTIC_FEEDBACK_ENABLED","I") J2CPP_DEFINE_FIELD(android::view::View,15,"FOCUSABLES_ALL","I") J2CPP_DEFINE_FIELD(android::view::View,16,"FOCUSABLES_TOUCH_MODE","I") J2CPP_DEFINE_FIELD(android::view::View,17,"FOCUS_BACKWARD","I") J2CPP_DEFINE_FIELD(android::view::View,18,"FOCUS_FORWARD","I") J2CPP_DEFINE_FIELD(android::view::View,19,"FOCUS_LEFT","I") J2CPP_DEFINE_FIELD(android::view::View,20,"FOCUS_UP","I") J2CPP_DEFINE_FIELD(android::view::View,21,"FOCUS_RIGHT","I") J2CPP_DEFINE_FIELD(android::view::View,22,"FOCUS_DOWN","I") J2CPP_DEFINE_FIELD(android::view::View,23,"EMPTY_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,24,"ENABLED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,25,"FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,26,"SELECTED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,27,"WINDOW_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,28,"ENABLED_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,29,"ENABLED_SELECTED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,30,"ENABLED_WINDOW_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,31,"FOCUSED_SELECTED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,32,"FOCUSED_WINDOW_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,33,"SELECTED_WINDOW_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,34,"ENABLED_FOCUSED_SELECTED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,35,"ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,36,"ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,37,"FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,38,"ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,39,"PRESSED_WINDOW_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,40,"PRESSED_SELECTED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,41,"PRESSED_SELECTED_WINDOW_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,42,"PRESSED_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,43,"PRESSED_FOCUSED_WINDOW_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,44,"PRESSED_FOCUSED_SELECTED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,45,"PRESSED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,46,"PRESSED_ENABLED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,47,"PRESSED_ENABLED_WINDOW_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,48,"PRESSED_ENABLED_SELECTED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,49,"PRESSED_ENABLED_SELECTED_WINDOW_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,50,"PRESSED_ENABLED_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,51,"PRESSED_ENABLED_FOCUSED_WINDOW_FOCUSED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,52,"PRESSED_ENABLED_FOCUSED_SELECTED_STATE_SET","[I") J2CPP_DEFINE_FIELD(android::view::View,53,"PRESSED_ENABLED_FOCUSED_SELECTED_WINDOW_FOCUSED_STATE_SET","[I") } //namespace j2cpp #endif //J2CPP_ANDROID_VIEW_VIEW_HPP_IMPL #endif //J2CPP_INCLUDE_IMPLEMENTATION
35.002247
240
0.734585
[ "object" ]
70b14b15148a0b5a2712bc2115c70433add24716
38,487
cpp
C++
src/apps/icon-o-matic/MainWindow.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
1,338
2015-01-03T20:06:56.000Z
2022-03-26T13:49:54.000Z
src/apps/icon-o-matic/MainWindow.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
15
2015-01-17T22:19:32.000Z
2021-12-20T12:35:00.000Z
src/apps/icon-o-matic/MainWindow.cpp
Kirishikesan/haiku
835565c55830f2dab01e6e332cc7e2d9c015b51e
[ "MIT" ]
350
2015-01-08T14:15:27.000Z
2022-03-21T18:14:35.000Z
/* * Copyright 2006-2011, Stephan Aßmus <superstippi@gmx.de>. * All rights reserved. Distributed under the terms of the MIT License. */ #include "MainWindow.h" #include <new> #include <stdio.h> #include <Alert.h> #include <Catalog.h> #include <Clipboard.h> #include <GridLayout.h> #include <GroupLayout.h> #include <GroupView.h> #include <Directory.h> #include <Entry.h> #include <File.h> #include <fs_attr.h> #include <LayoutBuilder.h> #include <Locale.h> #include <Menu.h> #include <MenuBar.h> #include <MenuField.h> #include <MenuItem.h> #include <Message.h> #include <Screen.h> #include <ScrollView.h> #include "support_ui.h" #include "AddPathsCommand.h" #include "AddShapesCommand.h" #include "AddStylesCommand.h" #include "AttributeSaver.h" #include "BitmapExporter.h" #include "BitmapSetSaver.h" #include "CanvasView.h" #include "CommandStack.h" #include "CompoundCommand.h" #include "CurrentColor.h" #include "Document.h" #include "FlatIconExporter.h" #include "FlatIconFormat.h" #include "FlatIconImporter.h" #include "IconObjectListView.h" #include "IconEditorApp.h" #include "IconView.h" #include "MessageExporter.h" #include "MessageImporter.h" #include "MessengerSaver.h" #include "NativeSaver.h" #include "PathListView.h" #include "RDefExporter.h" #include "ScrollView.h" #include "SimpleFileSaver.h" #include "ShapeListView.h" #include "SourceExporter.h" #include "StyleListView.h" #include "StyleView.h" #include "SVGExporter.h" #include "SVGImporter.h" #include "SwatchGroup.h" #include "TransformerListView.h" #include "TransformGradientBox.h" #include "TransformShapesBox.h" #include "Util.h" // TODO: just for testing #include "AffineTransformer.h" #include "GradientTransformable.h" #include "Icon.h" #include "MultipleManipulatorState.h" #include "PathManipulator.h" #include "Shape.h" #include "ShapeContainer.h" #include "ShapeListView.h" #include "StrokeTransformer.h" #include "Style.h" #include "StyleContainer.h" #include "VectorPath.h" #include "StyledTextImporter.h" #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "Icon-O-Matic-Main" using std::nothrow; enum { MSG_UNDO = 'undo', MSG_REDO = 'redo', MSG_UNDO_STACK_CHANGED = 'usch', MSG_PATH_SELECTED = 'vpsl', MSG_STYLE_SELECTED = 'stsl', MSG_SHAPE_SELECTED = 'spsl', MSG_SHAPE_RESET_TRANSFORMATION = 'rtsh', MSG_STYLE_RESET_TRANSFORMATION = 'rtst', MSG_MOUSE_FILTER_MODE = 'mfmd', MSG_RENAME_OBJECT = 'rnam', }; MainWindow::MainWindow(BRect frame, IconEditorApp* app, const BMessage* settings) : BWindow(frame, B_TRANSLATE_SYSTEM_NAME("Icon-O-Matic"), B_DOCUMENT_WINDOW_LOOK, B_NORMAL_WINDOW_FEEL, B_ASYNCHRONOUS_CONTROLS | B_AUTO_UPDATE_SIZE_LIMITS), fApp(app), fDocument(new Document(B_TRANSLATE("Untitled"))), fCurrentColor(new CurrentColor()), fIcon(NULL), fMessageAfterSave(NULL) { _Init(); RestoreSettings(settings); } MainWindow::~MainWindow() { SetIcon(NULL); delete fState; // Make sure there are no listeners attached to the document anymore. while (BView* child = ChildAt(0L)) { child->RemoveSelf(); delete child; } fDocument->CommandStack()->RemoveObserver(this); // NOTE: it is important that the GUI has been deleted // at this point, so that all the listener/observer // stuff is properly detached delete fDocument; delete fMessageAfterSave; } // #pragma mark - void MainWindow::MessageReceived(BMessage* message) { bool discard = false; // Figure out if we need the write lock on the Document. For most // messages we do, but exporting takes place in another thread and // locking is taken care of there. bool requiresWriteLock = true; switch (message->what) { case MSG_SAVE: case MSG_EXPORT: case MSG_SAVE_AS: case MSG_EXPORT_AS: requiresWriteLock = false; break; default: break; } if (requiresWriteLock && !fDocument->WriteLock()) { BWindow::MessageReceived(message); return; } if (message->WasDropped()) { const rgb_color* color; ssize_t length; // create styles from dropped colors for (int32 i = 0; message->FindData("RGBColor", B_RGB_COLOR_TYPE, i, (const void**)&color, &length) == B_OK; i++) { if (length != sizeof(rgb_color)) continue; char name[30]; sprintf(name, B_TRANSLATE_CONTEXT("Color (#%02x%02x%02x)", "Style name after dropping a color"), color->red, color->green, color->blue); Style* style = new (nothrow) Style(*color); style->SetName(name); Style* styles[1] = { style }; AddStylesCommand* styleCommand = new (nothrow) AddStylesCommand( fDocument->Icon()->Styles(), styles, 1, fDocument->Icon()->Styles()->CountStyles()); fDocument->CommandStack()->Perform(styleCommand); // don't handle anything else, // or we might paste the clipboard on B_PASTE discard = true; } } switch (message->what) { case B_REFS_RECEIVED: case B_SIMPLE_DATA: // If our icon is empty, open the file in this window, // otherwise forward to the application which will open // it in another window, unless we append. message->what = B_REFS_RECEIVED; if (fDocument->Icon()->Styles()->CountStyles() == 0 && fDocument->Icon()->Paths()->CountPaths() == 0 && fDocument->Icon()->Shapes()->CountShapes() == 0) { entry_ref ref; if (message->FindRef("refs", &ref) == B_OK) Open(ref); break; } if (modifiers() & B_SHIFT_KEY) { // We want the icon appended to this window. message->AddBool("append", true); message->AddPointer("window", this); } be_app->PostMessage(message); break; case B_PASTE: case B_MIME_DATA: { BMessage* clip = message; status_t err; if (discard) break; if (message->what == B_PASTE) { if (!be_clipboard->Lock()) break; clip = be_clipboard->Data(); } if (!clip || !clip->HasData("text/plain", B_MIME_TYPE)) { if (message->what == B_PASTE) be_clipboard->Unlock(); break; } Icon* icon = new (std::nothrow) Icon(*fDocument->Icon()); if (icon != NULL) { StyledTextImporter importer; err = importer.Import(icon, clip); if (err >= B_OK) { AutoWriteLocker locker(fDocument); SetIcon(NULL); // incorporate the loaded icon into the document // (either replace it or append to it) fDocument->MakeEmpty(false); // if append, the document savers are preserved fDocument->SetIcon(icon); SetIcon(icon); } } if (message->what == B_PASTE) be_clipboard->Unlock(); break; } case MSG_OPEN: // If our icon is empty, we want the icon to open in this // window. if (fDocument->Icon()->Styles()->CountStyles() == 0 && fDocument->Icon()->Paths()->CountPaths() == 0 && fDocument->Icon()->Shapes()->CountShapes() == 0) { message->AddPointer("window", this); } be_app->PostMessage(message); break; case MSG_SAVE: case MSG_EXPORT: { DocumentSaver* saver; if (message->what == MSG_SAVE) saver = fDocument->NativeSaver(); else saver = fDocument->ExportSaver(); if (saver != NULL) { saver->Save(fDocument); _PickUpActionBeforeSave(); break; } // else fall through } case MSG_SAVE_AS: case MSG_EXPORT_AS: { int32 exportMode; if (message->FindInt32("export mode", &exportMode) < B_OK) exportMode = EXPORT_MODE_MESSAGE; entry_ref ref; const char* name; if (message->FindRef("directory", &ref) == B_OK && message->FindString("name", &name) == B_OK) { // this message comes from the file panel BDirectory dir(&ref); BEntry entry; if (dir.InitCheck() >= B_OK && entry.SetTo(&dir, name, true) >= B_OK && entry.GetRef(&ref) >= B_OK) { // create the document saver and remember it for later DocumentSaver* saver = _CreateSaver(ref, exportMode); if (saver != NULL) { if (fDocument->WriteLock()) { if (exportMode == EXPORT_MODE_MESSAGE) fDocument->SetNativeSaver(saver); else fDocument->SetExportSaver(saver); _UpdateWindowTitle(); fDocument->WriteUnlock(); } saver->Save(fDocument); _PickUpActionBeforeSave(); } } // TODO: ... // _SyncPanels(fSavePanel, fOpenPanel); } else { // configure the file panel uint32 requestRefWhat = MSG_SAVE_AS; bool isExportMode = message->what == MSG_EXPORT_AS || message->what == MSG_EXPORT; if (isExportMode) requestRefWhat = MSG_EXPORT_AS; const char* saveText = _FileName(isExportMode); BMessage requestRef(requestRefWhat); if (saveText != NULL) requestRef.AddString("save text", saveText); requestRef.AddMessenger("target", BMessenger(this, this)); be_app->PostMessage(&requestRef); } break; } case B_CANCEL: // FilePanel was canceled, do not execute the fMessageAfterSave // next time a file panel is used, in case it was set! delete fMessageAfterSave; fMessageAfterSave = NULL; break; case MSG_UNDO: fDocument->CommandStack()->Undo(); break; case MSG_REDO: fDocument->CommandStack()->Redo(); break; case MSG_UNDO_STACK_CHANGED: { // relable Undo item and update enabled status BString label(B_TRANSLATE("Undo")); fUndoMI->SetEnabled(fDocument->CommandStack()->GetUndoName(label)); if (fUndoMI->IsEnabled()) fUndoMI->SetLabel(label.String()); else { fUndoMI->SetLabel(B_TRANSLATE_CONTEXT("<nothing to undo>", "Icon-O-Matic-Menu-Edit")); } // relable Redo item and update enabled status label.SetTo(B_TRANSLATE("Redo")); fRedoMI->SetEnabled(fDocument->CommandStack()->GetRedoName(label)); if (fRedoMI->IsEnabled()) fRedoMI->SetLabel(label.String()); else { fRedoMI->SetLabel(B_TRANSLATE_CONTEXT("<nothing to redo>", "Icon-O-Matic-Menu-Edit")); } break; } case MSG_MOUSE_FILTER_MODE: { uint32 mode; if (message->FindInt32("mode", (int32*)&mode) == B_OK) fCanvasView->SetMouseFilterMode(mode); break; } case MSG_ADD_SHAPE: { AddStylesCommand* styleCommand = NULL; Style* style = NULL; if (message->HasBool("style")) { new_style(fCurrentColor->Color(), fDocument->Icon()->Styles(), &style, &styleCommand); } AddPathsCommand* pathCommand = NULL; VectorPath* path = NULL; if (message->HasBool("path")) { new_path(fDocument->Icon()->Paths(), &path, &pathCommand); } if (!style) { // use current or first style int32 currentStyle = fStyleListView->CurrentSelection(0); style = fDocument->Icon()->Styles()->StyleAt(currentStyle); if (!style) style = fDocument->Icon()->Styles()->StyleAt(0); } Shape* shape = new (nothrow) Shape(style); Shape* shapes[1]; shapes[0] = shape; AddShapesCommand* shapeCommand = new (nothrow) AddShapesCommand( fDocument->Icon()->Shapes(), shapes, 1, fDocument->Icon()->Shapes()->CountShapes(), fDocument->Selection()); if (path && shape) shape->Paths()->AddPath(path); ::Command* command = NULL; if (styleCommand || pathCommand) { if (styleCommand && pathCommand) { Command** commands = new Command*[3]; commands[0] = styleCommand; commands[1] = pathCommand; commands[2] = shapeCommand; command = new CompoundCommand(commands, 3, B_TRANSLATE_CONTEXT("Add shape with path & style", "Icon-O-Matic-Menu-Shape"), 0); } else if (styleCommand) { Command** commands = new Command*[2]; commands[0] = styleCommand; commands[1] = shapeCommand; command = new CompoundCommand(commands, 2, B_TRANSLATE_CONTEXT("Add shape with style", "Icon-O-Matic-Menu-Shape"), 0); } else { Command** commands = new Command*[2]; commands[0] = pathCommand; commands[1] = shapeCommand; command = new CompoundCommand(commands, 2, B_TRANSLATE_CONTEXT("Add shape with path", "Icon-O-Matic-Menu-Shape"), 0); } } else { command = shapeCommand; } fDocument->CommandStack()->Perform(command); break; } // TODO: listen to selection in CanvasView to add a manipulator case MSG_PATH_SELECTED: { VectorPath* path; if (message->FindPointer("path", (void**)&path) < B_OK) path = NULL; fPathListView->SetCurrentShape(NULL); fStyleListView->SetCurrentShape(NULL); fTransformerListView->SetShape(NULL); fState->DeleteManipulators(); if (fDocument->Icon()->Paths()->HasPath(path)) { PathManipulator* pathManipulator = new (nothrow) PathManipulator(path); fState->AddManipulator(pathManipulator); } break; } case MSG_STYLE_SELECTED: case MSG_STYLE_TYPE_CHANGED: { Style* style; if (message->FindPointer("style", (void**)&style) < B_OK) style = NULL; if (!fDocument->Icon()->Styles()->HasStyle(style)) style = NULL; fStyleView->SetStyle(style); fPathListView->SetCurrentShape(NULL); fStyleListView->SetCurrentShape(NULL); fTransformerListView->SetShape(NULL); fState->DeleteManipulators(); Gradient* gradient = style ? style->Gradient() : NULL; if (gradient != NULL) { TransformGradientBox* transformBox = new (nothrow) TransformGradientBox(fCanvasView, gradient, NULL); fState->AddManipulator(transformBox); } break; } case MSG_SHAPE_SELECTED: { Shape* shape; if (message->FindPointer("shape", (void**)&shape) < B_OK) shape = NULL; if (!fIcon || !fIcon->Shapes()->HasShape(shape)) shape = NULL; fPathListView->SetCurrentShape(shape); fStyleListView->SetCurrentShape(shape); fTransformerListView->SetShape(shape); BList selectedShapes; ShapeContainer* shapes = fDocument->Icon()->Shapes(); int32 count = shapes->CountShapes(); for (int32 i = 0; i < count; i++) { shape = shapes->ShapeAtFast(i); if (shape->IsSelected()) { selectedShapes.AddItem((void*)shape); } } fState->DeleteManipulators(); if (selectedShapes.CountItems() > 0) { TransformShapesBox* transformBox = new (nothrow) TransformShapesBox( fCanvasView, (const Shape**)selectedShapes.Items(), selectedShapes.CountItems()); fState->AddManipulator(transformBox); } break; } case MSG_RENAME_OBJECT: fPropertyListView->FocusNameProperty(); break; default: BWindow::MessageReceived(message); } if (requiresWriteLock) fDocument->WriteUnlock(); } void MainWindow::Show() { BWindow::Show(); BMenuBar* bar = static_cast<BMenuBar*>(FindView("main menu")); SetKeyMenuBar(bar); } bool MainWindow::QuitRequested() { if (!_CheckSaveIcon(CurrentMessage())) return false; BMessage message(MSG_WINDOW_CLOSED); BMessage settings; StoreSettings(&settings); message.AddMessage("settings", &settings); message.AddRect("window frame", Frame()); be_app->PostMessage(&message); return true; } void MainWindow::WorkspaceActivated(int32 workspace, bool active) { BWindow::WorkspaceActivated(workspace, active); // NOTE: hack to workaround buggy BScreen::DesktopColor() on R5 uint32 workspaces = Workspaces(); if (!active || ((1 << workspace) & workspaces) == 0) return; WorkspacesChanged(workspaces, workspaces); } void MainWindow::WorkspacesChanged(uint32 oldWorkspaces, uint32 newWorkspaces) { if (oldWorkspaces != newWorkspaces) BWindow::WorkspacesChanged(oldWorkspaces, newWorkspaces); BScreen screen(this); // Unfortunately, this is buggy on R5: screen.DesktopColor() // as well as ui_color(B_DESKTOP_COLOR) return the color // of the *active* screen, not the one on which this window // is. So this trick only works when you drag this window // from another workspace onto the current workspace, not // when you drag the window from the current workspace onto // another workspace and then switch to the other workspace. fIconPreview32Desktop->SetIconBGColor(screen.DesktopColor()); fIconPreview64->SetIconBGColor(screen.DesktopColor()); } // #pragma mark - void MainWindow::ObjectChanged(const Observable* object) { if (!fDocument || !fDocument->ReadLock()) return; if (object == fDocument->CommandStack()) PostMessage(MSG_UNDO_STACK_CHANGED); fDocument->ReadUnlock(); } // #pragma mark - void MainWindow::MakeEmpty() { fPathListView->SetCurrentShape(NULL); fStyleListView->SetCurrentShape(NULL); fStyleView->SetStyle(NULL); fTransformerListView->SetShape(NULL); fState->DeleteManipulators(); } void MainWindow::Open(const entry_ref& ref, bool append) { BFile file(&ref, B_READ_ONLY); if (file.InitCheck() < B_OK) return; Icon* icon; if (append) icon = new (nothrow) Icon(*fDocument->Icon()); else icon = new (nothrow) Icon(); if (icon == NULL) { // TODO: Report error to user. return; } enum { REF_NONE = 0, REF_MESSAGE, REF_FLAT, REF_FLAT_ATTR, REF_SVG }; uint32 refMode = REF_NONE; // try different file types FlatIconImporter flatImporter; status_t ret = flatImporter.Import(icon, &file); if (ret >= B_OK) { refMode = REF_FLAT; } else { file.Seek(0, SEEK_SET); MessageImporter msgImporter; ret = msgImporter.Import(icon, &file); if (ret >= B_OK) { refMode = REF_MESSAGE; } else { file.Seek(0, SEEK_SET); SVGImporter svgImporter; ret = svgImporter.Import(icon, &ref); if (ret >= B_OK) { refMode = REF_SVG; } else { // fall back to flat icon format but use the icon attribute ret = B_OK; attr_info attrInfo; if (file.GetAttrInfo(kVectorAttrNodeName, &attrInfo) == B_OK) { if (attrInfo.type != B_VECTOR_ICON_TYPE) ret = B_ERROR; // If the attribute is there, we must succeed in reading // an icon! Otherwise we may overwrite an existing icon // when the user saves. uint8* buffer = NULL; if (ret == B_OK) { buffer = new(nothrow) uint8[attrInfo.size]; if (buffer == NULL) ret = B_NO_MEMORY; } if (ret == B_OK) { ssize_t bytesRead = file.ReadAttr(kVectorAttrNodeName, B_VECTOR_ICON_TYPE, 0, buffer, attrInfo.size); if (bytesRead != (ssize_t)attrInfo.size) { ret = bytesRead < 0 ? (status_t)bytesRead : B_IO_ERROR; } } if (ret == B_OK) { ret = flatImporter.Import(icon, buffer, attrInfo.size); if (ret == B_OK) refMode = REF_FLAT_ATTR; } delete[] buffer; } else { // If there is no icon attribute, simply fall back // to creating an icon for this file. TODO: We may or may // not want to display an alert asking the user if that is // what he wants to do. refMode = REF_FLAT_ATTR; } } } } if (ret < B_OK) { // inform user of failure at this point BString helper(B_TRANSLATE("Opening the document failed!")); helper << "\n\n" << B_TRANSLATE("Error: ") << strerror(ret); BAlert* alert = new BAlert( B_TRANSLATE_CONTEXT("bad news", "Title of error alert"), helper.String(), B_TRANSLATE_CONTEXT("Bummer", "Cancel button - error alert"), NULL, NULL); // launch alert asynchronously alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(NULL); delete icon; return; } AutoWriteLocker locker(fDocument); // incorporate the loaded icon into the document // (either replace it or append to it) fDocument->MakeEmpty(!append); // if append, the document savers are preserved fDocument->SetIcon(icon); if (!append) { // document got replaced, but we have at // least one ref already switch (refMode) { case REF_MESSAGE: fDocument->SetNativeSaver(new NativeSaver(ref)); break; case REF_FLAT: fDocument->SetExportSaver( new SimpleFileSaver(new FlatIconExporter(), ref)); break; case REF_FLAT_ATTR: fDocument->SetNativeSaver( new AttributeSaver(ref, kVectorAttrNodeName)); break; case REF_SVG: fDocument->SetExportSaver( new SimpleFileSaver(new SVGExporter(), ref)); break; } } locker.Unlock(); SetIcon(icon); _UpdateWindowTitle(); } void MainWindow::Open(const BMessenger& externalObserver, const uint8* data, size_t size) { if (!_CheckSaveIcon(CurrentMessage())) return; if (!externalObserver.IsValid()) return; Icon* icon = new (nothrow) Icon(); if (!icon) return; if (data && size > 0) { // try to open the icon from the provided data FlatIconImporter flatImporter; status_t ret = flatImporter.Import(icon, const_cast<uint8*>(data), size); // NOTE: the const_cast is a bit ugly, but no harm is done // the reason is that the LittleEndianBuffer knows read and write // mode, in this case it is used read-only, and it does not assume // ownership of the buffer if (ret < B_OK) { // inform user of failure at this point BString helper(B_TRANSLATE("Opening the icon failed!")); helper << "\n\n" << B_TRANSLATE("Error: ") << strerror(ret); BAlert* alert = new BAlert( B_TRANSLATE_CONTEXT("bad news", "Title of error alert"), helper.String(), B_TRANSLATE_CONTEXT("Bummer", "Cancel button - error alert"), NULL, NULL); // launch alert asynchronously alert->SetFlags(alert->Flags() | B_CLOSE_ON_ESCAPE); alert->Go(NULL); delete icon; return; } } AutoWriteLocker locker(fDocument); SetIcon(NULL); // incorporate the loaded icon into the document // (either replace it or append to it) fDocument->MakeEmpty(); fDocument->SetIcon(icon); fDocument->SetNativeSaver(new MessengerSaver(externalObserver)); locker.Unlock(); SetIcon(icon); } void MainWindow::SetIcon(Icon* icon) { if (fIcon == icon) return; Icon* oldIcon = fIcon; fIcon = icon; if (fIcon != NULL) fIcon->AcquireReference(); else MakeEmpty(); fCanvasView->SetIcon(fIcon); fPathListView->SetPathContainer(fIcon != NULL ? fIcon->Paths() : NULL); fPathListView->SetShapeContainer(fIcon != NULL ? fIcon->Shapes() : NULL); fStyleListView->SetStyleContainer(fIcon != NULL ? fIcon->Styles() : NULL); fStyleListView->SetShapeContainer(fIcon != NULL ? fIcon->Shapes() : NULL); fShapeListView->SetShapeContainer(fIcon != NULL ? fIcon->Shapes() : NULL); fShapeListView->SetStyleContainer(fIcon != NULL ? fIcon->Styles() : NULL); fShapeListView->SetPathContainer(fIcon != NULL ? fIcon->Paths() : NULL); // icon previews fIconPreview16Folder->SetIcon(fIcon); fIconPreview16Menu->SetIcon(fIcon); fIconPreview32Folder->SetIcon(fIcon); fIconPreview32Desktop->SetIcon(fIcon); // fIconPreview48->SetIcon(fIcon); fIconPreview64->SetIcon(fIcon); // keep this last if (oldIcon != NULL) oldIcon->ReleaseReference(); } // #pragma mark - void MainWindow::StoreSettings(BMessage* archive) { if (archive->ReplaceUInt32("mouse filter mode", fCanvasView->MouseFilterMode()) != B_OK) { archive->AddUInt32("mouse filter mode", fCanvasView->MouseFilterMode()); } } void MainWindow::RestoreSettings(const BMessage* archive) { uint32 mouseFilterMode; if (archive->FindUInt32("mouse filter mode", &mouseFilterMode) == B_OK) { fCanvasView->SetMouseFilterMode(mouseFilterMode); fMouseFilterOffMI->SetMarked(mouseFilterMode == SNAPPING_OFF); fMouseFilter64MI->SetMarked(mouseFilterMode == SNAPPING_64); fMouseFilter32MI->SetMarked(mouseFilterMode == SNAPPING_32); fMouseFilter16MI->SetMarked(mouseFilterMode == SNAPPING_16); } } // #pragma mark - void MainWindow::_Init() { // create the GUI _CreateGUI(); // fix up scrollbar layout in listviews _ImproveScrollBarLayout(fPathListView); _ImproveScrollBarLayout(fStyleListView); _ImproveScrollBarLayout(fShapeListView); _ImproveScrollBarLayout(fTransformerListView); // TODO: move this to CanvasView? fState = new MultipleManipulatorState(fCanvasView); fCanvasView->SetState(fState); fCanvasView->SetCatchAllEvents(true); fCanvasView->SetCommandStack(fDocument->CommandStack()); fCanvasView->SetMouseFilterMode(SNAPPING_64); fMouseFilter64MI->SetMarked(true); // fCanvasView->SetSelection(fDocument->Selection()); fPathListView->SetMenu(fPathMenu); fPathListView->SetCommandStack(fDocument->CommandStack()); fPathListView->SetSelection(fDocument->Selection()); fStyleListView->SetMenu(fStyleMenu); fStyleListView->SetCommandStack(fDocument->CommandStack()); fStyleListView->SetSelection(fDocument->Selection()); fStyleListView->SetCurrentColor(fCurrentColor); fStyleView->SetCommandStack(fDocument->CommandStack()); fStyleView->SetCurrentColor(fCurrentColor); fShapeListView->SetMenu(fShapeMenu); fShapeListView->SetCommandStack(fDocument->CommandStack()); fShapeListView->SetSelection(fDocument->Selection()); fTransformerListView->SetMenu(fTransformerMenu); fTransformerListView->SetCommandStack(fDocument->CommandStack()); fTransformerListView->SetSelection(fDocument->Selection()); fPropertyListView->SetCommandStack(fDocument->CommandStack()); fPropertyListView->SetSelection(fDocument->Selection()); fPropertyListView->SetMenu(fPropertyMenu); fDocument->CommandStack()->AddObserver(this); fSwatchGroup->SetCurrentColor(fCurrentColor); SetIcon(fDocument->Icon()); AddShortcut('Y', 0, new BMessage(MSG_UNDO)); AddShortcut('Y', B_SHIFT_KEY, new BMessage(MSG_REDO)); AddShortcut('E', 0, new BMessage(MSG_RENAME_OBJECT)); } void MainWindow::_CreateGUI() { SetLayout(new BGroupLayout(B_HORIZONTAL)); BGridLayout* layout = new BGridLayout(); layout->SetSpacing(0, 0); BView* rootView = new BView("root view", 0, layout); AddChild(rootView); rootView->SetViewUIColor(B_PANEL_BACKGROUND_COLOR); BGroupView* leftTopView = new BGroupView(B_VERTICAL, 0); layout->AddView(leftTopView, 0, 0); // views along the left side BMenuBar* mainMenuBar = _CreateMenuBar(); leftTopView->AddChild(mainMenuBar); float splitWidth = 13 * be_plain_font->Size(); BSize minSize = leftTopView->MinSize(); splitWidth = std::max(splitWidth, minSize.width); leftTopView->SetExplicitMaxSize(BSize(splitWidth, B_SIZE_UNSET)); leftTopView->SetExplicitMinSize(BSize(splitWidth, B_SIZE_UNSET)); BGroupView* iconPreviews = new BGroupView(B_HORIZONTAL); iconPreviews->SetViewUIColor(B_PANEL_BACKGROUND_COLOR); iconPreviews->GroupLayout()->SetSpacing(5); // icon previews fIconPreview16Folder = new IconView(BRect(0, 0, 15, 15), "icon preview 16 folder"); fIconPreview16Menu = new IconView(BRect(0, 0, 15, 15), "icon preview 16 menu"); fIconPreview16Menu->SetLowColor(ui_color(B_MENU_BACKGROUND_COLOR)); fIconPreview32Folder = new IconView(BRect(0, 0, 31, 31), "icon preview 32 folder"); fIconPreview32Desktop = new IconView(BRect(0, 0, 31, 31), "icon preview 32 desktop"); fIconPreview32Desktop->SetLowColor(ui_color(B_DESKTOP_COLOR)); fIconPreview64 = new IconView(BRect(0, 0, 63, 63), "icon preview 64"); fIconPreview64->SetLowColor(ui_color(B_DESKTOP_COLOR)); BGroupView* smallPreviews = new BGroupView(B_VERTICAL); smallPreviews->SetViewUIColor(B_PANEL_BACKGROUND_COLOR); smallPreviews->GroupLayout()->SetSpacing(5); smallPreviews->AddChild(fIconPreview16Folder); smallPreviews->AddChild(fIconPreview16Menu); BGroupView* mediumPreviews = new BGroupView(B_VERTICAL); mediumPreviews->SetViewUIColor(B_PANEL_BACKGROUND_COLOR); mediumPreviews->GroupLayout()->SetSpacing(5); mediumPreviews->AddChild(fIconPreview32Folder); mediumPreviews->AddChild(fIconPreview32Desktop); // iconPreviews->AddChild(fIconPreview48); iconPreviews->AddChild(smallPreviews); iconPreviews->AddChild(mediumPreviews); iconPreviews->AddChild(fIconPreview64); iconPreviews->SetExplicitMaxSize(BSize(B_SIZE_UNSET, B_SIZE_UNLIMITED)); leftTopView->AddChild(iconPreviews); BGroupView* leftSideView = new BGroupView(B_VERTICAL, 0); layout->AddView(leftSideView, 0, 1); leftSideView->SetExplicitMaxSize(BSize(splitWidth, B_SIZE_UNSET)); fPathListView = new PathListView(BRect(0, 0, splitWidth, 100), "path list view", new BMessage(MSG_PATH_SELECTED), this); fShapeListView = new ShapeListView(BRect(0, 0, splitWidth, 100), "shape list view", new BMessage(MSG_SHAPE_SELECTED), this); fTransformerListView = new TransformerListView(BRect(0, 0, splitWidth, 100), "transformer list view"); fPropertyListView = new IconObjectListView(); BLayoutBuilder::Group<>(leftSideView) .AddGroup(B_VERTICAL, 0) .SetInsets(-2, -1, -1, -1) .Add(new BMenuField(NULL, fPathMenu)) .End() .Add(new BScrollView("path scroll view", fPathListView, B_FOLLOW_NONE, 0, false, true, B_NO_BORDER)) .AddGroup(B_VERTICAL, 0) .SetInsets(-2, -2, -1, -1) .Add(new BMenuField(NULL, fShapeMenu)) .End() .Add(new BScrollView("shape scroll view", fShapeListView, B_FOLLOW_NONE, 0, false, true, B_NO_BORDER)) .AddGroup(B_VERTICAL, 0) .SetInsets(-2, -2, -1, -1) .Add(new BMenuField(NULL, fTransformerMenu)) .End() .Add(new BScrollView("transformer scroll view", fTransformerListView, B_FOLLOW_NONE, 0, false, true, B_NO_BORDER)) .AddGroup(B_VERTICAL, 0) .SetInsets(-2, -2, -1, -1) .Add(new BMenuField(NULL, fPropertyMenu)) .End() .Add(new ScrollView(fPropertyListView, SCROLL_VERTICAL, BRect(0, 0, splitWidth, 100), "property scroll view", B_FOLLOW_NONE, B_WILL_DRAW | B_FRAME_EVENTS, B_PLAIN_BORDER, BORDER_RIGHT)) .End(); BGroupLayout* topSide = new BGroupLayout(B_HORIZONTAL); topSide->SetSpacing(0); BView* topSideView = new BView("top side view", 0, topSide); layout->AddView(topSideView, 1, 0); // canvas view BRect canvasBounds = BRect(0, 0, 200, 200); fCanvasView = new CanvasView(canvasBounds); // scroll view around canvas view canvasBounds.bottom += B_H_SCROLL_BAR_HEIGHT; canvasBounds.right += B_V_SCROLL_BAR_WIDTH; ScrollView* canvasScrollView = new ScrollView(fCanvasView, SCROLL_VERTICAL | SCROLL_HORIZONTAL | SCROLL_VISIBLE_RECT_IS_CHILD_BOUNDS, canvasBounds, "canvas scroll view", B_FOLLOW_NONE, B_WILL_DRAW | B_FRAME_EVENTS, B_NO_BORDER); layout->AddView(canvasScrollView, 1, 1); // views along the top BGroupView* styleGroupView = new BGroupView(B_VERTICAL, 0); topSide->AddView(styleGroupView); fStyleListView = new StyleListView(BRect(0, 0, splitWidth, 100), "style list view", new BMessage(MSG_STYLE_SELECTED), this); BScrollView* scrollView = new BScrollView("style list scroll view", fStyleListView, B_FOLLOW_NONE, 0, false, true, B_NO_BORDER); scrollView->SetExplicitMaxSize(BSize(splitWidth, B_SIZE_UNLIMITED)); BLayoutBuilder::Group<>(styleGroupView) .AddGroup(B_VERTICAL, 0) .SetInsets(-2, -2, -1, -1) .Add(new BMenuField(NULL, fStyleMenu)) .End() .Add(scrollView) .End(); // style view fStyleView = new StyleView(BRect(0, 0, 200, 100)); topSide->AddView(fStyleView); // swatch group BGroupLayout* swatchGroup = new BGroupLayout(B_VERTICAL); swatchGroup->SetSpacing(0); BView* swatchGroupView = new BView("swatch group", 0, swatchGroup); topSide->AddView(swatchGroupView); BMenuBar* menuBar = new BMenuBar("swatches menu bar"); menuBar->AddItem(fSwatchMenu); swatchGroup->AddView(menuBar); fSwatchGroup = new SwatchGroup(BRect(0, 0, 100, 100)); swatchGroup->AddView(fSwatchGroup); swatchGroupView->SetExplicitMaxSize(swatchGroupView->MinSize()); // make sure the top side has fixed height topSideView->SetExplicitMaxSize(BSize(B_SIZE_UNLIMITED, swatchGroupView->MinSize().height)); } BMenuBar* MainWindow::_CreateMenuBar() { BMenuBar* menuBar = new BMenuBar("main menu"); #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "Icon-O-Matic-Menus" BMenu* fileMenu = new BMenu(B_TRANSLATE("File")); BMenu* editMenu = new BMenu(B_TRANSLATE("Edit")); BMenu* settingsMenu = new BMenu(B_TRANSLATE("Settings")); fPathMenu = new BMenu(B_TRANSLATE("Path")); fStyleMenu = new BMenu(B_TRANSLATE("Style")); fShapeMenu = new BMenu(B_TRANSLATE("Shape")); fTransformerMenu = new BMenu(B_TRANSLATE("Transformer")); fPropertyMenu = new BMenu(B_TRANSLATE("Properties")); fSwatchMenu = new BMenu(B_TRANSLATE("Swatches")); menuBar->AddItem(fileMenu); menuBar->AddItem(editMenu); menuBar->AddItem(settingsMenu); // File #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "Icon-O-Matic-Menu-File" BMenuItem* item = new BMenuItem(B_TRANSLATE("New"), new BMessage(MSG_NEW), 'N'); fileMenu->AddItem(item); item->SetTarget(be_app); item = new BMenuItem(B_TRANSLATE("Open" B_UTF8_ELLIPSIS), new BMessage(MSG_OPEN), 'O'); fileMenu->AddItem(item); BMessage* appendMessage = new BMessage(MSG_APPEND); appendMessage->AddPointer("window", this); item = new BMenuItem(B_TRANSLATE("Append" B_UTF8_ELLIPSIS), appendMessage, 'O', B_SHIFT_KEY); fileMenu->AddItem(item); item->SetTarget(be_app); fileMenu->AddSeparatorItem(); fileMenu->AddItem(new BMenuItem(B_TRANSLATE("Save"), new BMessage(MSG_SAVE), 'S')); fileMenu->AddItem(new BMenuItem(B_TRANSLATE("Save as" B_UTF8_ELLIPSIS), new BMessage(MSG_SAVE_AS), 'S', B_SHIFT_KEY)); fileMenu->AddSeparatorItem(); fileMenu->AddItem(new BMenuItem(B_TRANSLATE("Export"), new BMessage(MSG_EXPORT), 'P')); fileMenu->AddItem(new BMenuItem(B_TRANSLATE("Export as" B_UTF8_ELLIPSIS), new BMessage(MSG_EXPORT_AS), 'P', B_SHIFT_KEY)); fileMenu->AddSeparatorItem(); fileMenu->AddItem(new BMenuItem(B_TRANSLATE("Close"), new BMessage(B_QUIT_REQUESTED), 'W')); item = new BMenuItem(B_TRANSLATE("Quit"), new BMessage(B_QUIT_REQUESTED), 'Q'); fileMenu->AddItem(item); item->SetTarget(be_app); // Edit #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "Icon-O-Matic-Menu-Edit" fUndoMI = new BMenuItem(B_TRANSLATE("<nothing to undo>"), new BMessage(MSG_UNDO), 'Z'); fRedoMI = new BMenuItem(B_TRANSLATE("<nothing to redo>"), new BMessage(MSG_REDO), 'Z', B_SHIFT_KEY); fUndoMI->SetEnabled(false); fRedoMI->SetEnabled(false); editMenu->AddItem(fUndoMI); editMenu->AddItem(fRedoMI); // Settings #undef B_TRANSLATION_CONTEXT #define B_TRANSLATION_CONTEXT "Icon-O-Matic-Menu-Settings" BMenu* filterModeMenu = new BMenu(B_TRANSLATE("Snap to grid")); BMessage* message = new BMessage(MSG_MOUSE_FILTER_MODE); message->AddInt32("mode", SNAPPING_OFF); fMouseFilterOffMI = new BMenuItem(B_TRANSLATE("Off"), message, '4'); filterModeMenu->AddItem(fMouseFilterOffMI); message = new BMessage(MSG_MOUSE_FILTER_MODE); message->AddInt32("mode", SNAPPING_64); fMouseFilter64MI = new BMenuItem("64 x 64", message, '3'); filterModeMenu->AddItem(fMouseFilter64MI); message = new BMessage(MSG_MOUSE_FILTER_MODE); message->AddInt32("mode", SNAPPING_32); fMouseFilter32MI = new BMenuItem("32 x 32", message, '2'); filterModeMenu->AddItem(fMouseFilter32MI); message = new BMessage(MSG_MOUSE_FILTER_MODE); message->AddInt32("mode", SNAPPING_16); fMouseFilter16MI = new BMenuItem("16 x 16", message, '1'); filterModeMenu->AddItem(fMouseFilter16MI); filterModeMenu->SetRadioMode(true); settingsMenu->AddItem(filterModeMenu); return menuBar; } void MainWindow::_ImproveScrollBarLayout(BView* target) { // NOTE: The BListViews for which this function is used // are directly below a BMenuBar. If the BScrollBar and // the BMenuBar share bottom/top border respectively, the // GUI looks a little more polished. This trick can be // removed if/when the BScrollViews are embedded in a // surounding border like in WonderBrush. if (BScrollBar* scrollBar = target->ScrollBar(B_VERTICAL)) { scrollBar->MoveBy(0, -1); scrollBar->ResizeBy(0, 1); } } // #pragma mark - bool MainWindow::_CheckSaveIcon(const BMessage* currentMessage) { if (fDocument->IsEmpty() || fDocument->CommandStack()->IsSaved()) return true; // Make sure the user sees us. Activate(); BAlert* alert = new BAlert("save", B_TRANSLATE("Save changes to current icon before closing?"), B_TRANSLATE("Cancel"), B_TRANSLATE("Don't save"), B_TRANSLATE("Save"), B_WIDTH_AS_USUAL, B_OFFSET_SPACING, B_WARNING_ALERT); alert->SetShortcut(0, B_ESCAPE); alert->SetShortcut(1, 'd'); alert->SetShortcut(2, 's'); int32 choice = alert->Go(); switch (choice) { case 0: // cancel return false; case 1: // don't save return true; case 2: default: // cancel (save first) but pick up what we were doing before PostMessage(MSG_SAVE); if (currentMessage != NULL) { delete fMessageAfterSave; fMessageAfterSave = new BMessage(*currentMessage); } return false; } } void MainWindow::_PickUpActionBeforeSave() { if (fDocument->WriteLock()) { fDocument->CommandStack()->Save(); fDocument->WriteUnlock(); } if (fMessageAfterSave == NULL) return; PostMessage(fMessageAfterSave); delete fMessageAfterSave; fMessageAfterSave = NULL; } // #pragma mark - void MainWindow::_MakeIconEmpty() { if (!_CheckSaveIcon(CurrentMessage())) return; AutoWriteLocker locker(fDocument); MakeEmpty(); fDocument->MakeEmpty(); locker.Unlock(); } DocumentSaver* MainWindow::_CreateSaver(const entry_ref& ref, uint32 exportMode) { DocumentSaver* saver; switch (exportMode) { case EXPORT_MODE_FLAT_ICON: saver = new SimpleFileSaver(new FlatIconExporter(), ref); break; case EXPORT_MODE_ICON_ATTR: case EXPORT_MODE_ICON_MIME_ATTR: { const char* attrName = exportMode == EXPORT_MODE_ICON_ATTR ? kVectorAttrNodeName : kVectorAttrMimeName; saver = new AttributeSaver(ref, attrName); break; } case EXPORT_MODE_ICON_RDEF: saver = new SimpleFileSaver(new RDefExporter(), ref); break; case EXPORT_MODE_ICON_SOURCE: saver = new SimpleFileSaver(new SourceExporter(), ref); break; case EXPORT_MODE_BITMAP_16: saver = new SimpleFileSaver(new BitmapExporter(16), ref); break; case EXPORT_MODE_BITMAP_32: saver = new SimpleFileSaver(new BitmapExporter(32), ref); break; case EXPORT_MODE_BITMAP_64: saver = new SimpleFileSaver(new BitmapExporter(64), ref); break; case EXPORT_MODE_BITMAP_SET: saver = new BitmapSetSaver(ref); break; case EXPORT_MODE_SVG: saver = new SimpleFileSaver(new SVGExporter(), ref); break; case EXPORT_MODE_MESSAGE: default: saver = new NativeSaver(ref); break; } return saver; } const char* MainWindow::_FileName(bool preferExporter) const { FileSaver* saver1; FileSaver* saver2; if (preferExporter) { saver1 = dynamic_cast<FileSaver*>(fDocument->ExportSaver()); saver2 = dynamic_cast<FileSaver*>(fDocument->NativeSaver()); } else { saver1 = dynamic_cast<FileSaver*>(fDocument->NativeSaver()); saver2 = dynamic_cast<FileSaver*>(fDocument->ExportSaver()); } const char* fileName = NULL; if (saver1 != NULL) fileName = saver1->Ref()->name; if ((fileName == NULL || fileName[0] == '\0') && saver2 != NULL) fileName = saver2->Ref()->name; return fileName; } void MainWindow::_UpdateWindowTitle() { const char* fileName = _FileName(false); if (fileName != NULL) SetTitle(fileName); else SetTitle(B_TRANSLATE_SYSTEM_NAME("Icon-O-Matic")); }
26.820209
77
0.707616
[ "object", "shape" ]
70bc30c1b9c099247999c1eae3417332a67b94f5
53,431
cpp
C++
copasi/sbml/unittests/test000091.cpp
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
copasi/sbml/unittests/test000091.cpp
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
copasi/sbml/unittests/test000091.cpp
bmoreau/COPASI
d0bbec8947b1266ffd2b0ecf2566da7cf2c3e5ba
[ "Artistic-2.0" ]
null
null
null
// Copyright (C) 2010 - 2014 by Pedro Mendes, Virginia Tech Intellectual // Properties, Inc., University of Heidelberg, and The University // of Manchester. // All rights reserved. #include "test000091.h" #include <sstream> #include "utilities.hpp" #include "copasi/CopasiDataModel/CCopasiDataModel.h" #include "copasi/model/CModel.h" #include "copasi/model/CMetab.h" #include "copasi/model/CCompartment.h" #include "copasi/model/CModelValue.h" #include "copasi/model/CReaction.h" #include "copasi/function/CEvaluationNode.h" #include "copasi/function/CExpression.h" #include <sbml/SBMLDocument.h> #include <sbml/Model.h> #include <sbml/Compartment.h> #include <sbml/Species.h> #include <sbml/Parameter.h> #include <sbml/Reaction.h> #include <sbml/math/ASTNode.h> #include "copasi/report/CCopasiRootContainer.h" CCopasiDataModel* test000091::pCOPASIDATAMODEL = NULL; void test000091::setUp() { // Create the root container. CCopasiRootContainer::init(0, NULL, false); // Create the global data model. pCOPASIDATAMODEL = CCopasiRootContainer::addDatamodel(); } void test000091::tearDown() { CCopasiRootContainer::destroy(); } void test000091::test_delay_in_kinetic_law() { CCopasiDataModel* pDataModel = pCOPASIDATAMODEL; CPPUNIT_ASSERT(pDataModel->importSBMLFromString(MODEL_STRING1)); CModel* pModel = pDataModel->getModel(); CPPUNIT_ASSERT(pModel != NULL); CPPUNIT_ASSERT(pModel->getQuantityUnitEnum() == CUnit::mMol); CPPUNIT_ASSERT(pModel->getVolumeUnitEnum() == CUnit::ml); CPPUNIT_ASSERT(pModel->getTimeUnitEnum() == CUnit::s); CPPUNIT_ASSERT(pModel->getCompartments().size() == 1); const CCompartment* pCompartment = pModel->getCompartments()[0]; CPPUNIT_ASSERT(pCompartment != NULL); CPPUNIT_ASSERT(pCompartment->getStatus() == CModelEntity::FIXED); CPPUNIT_ASSERT(pModel->getMetabolites().size() == 2); const CMetab* pB = pModel->getMetabolites()[1]; CPPUNIT_ASSERT(pB != NULL); CPPUNIT_ASSERT(pB->getStatus() == CModelEntity::REACTIONS); CMetab* pA = pModel->getMetabolites()[0]; CPPUNIT_ASSERT(pA != NULL); CPPUNIT_ASSERT(pA->getStatus() == CModelEntity::REACTIONS); // there should now be three model values because we created two dummy model // values that represent the two different delay expression CPPUNIT_ASSERT(pModel->getModelValues().size() == 3); const CModelValue* pK1 = NULL; const CModelValue* pDummy1 = NULL; const CModelValue* pDummy2 = NULL; unsigned int i; for (i = 0; i < 3; ++i) { if (pModel->getModelValues()[i]->getObjectName() == "K1") { pK1 = pModel->getModelValues()[i]; } else { if (pDummy1 == NULL) { pDummy1 = pModel->getModelValues()[i]; } else { pDummy2 = pModel->getModelValues()[i]; } } } CPPUNIT_ASSERT(pK1 != NULL); CPPUNIT_ASSERT(pK1->getStatus() == CModelEntity::FIXED); CPPUNIT_ASSERT(fabs((pK1->getInitialValue() - 4.0) / 4.0) < 1e-9); CPPUNIT_ASSERT(pDummy1 != NULL); CPPUNIT_ASSERT(pDummy1->getStatus() == CModelEntity::ASSIGNMENT); const CExpression* pExpr = pDummy1->getExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); const CEvaluationNode* pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(CEvaluationNode::type(pNode->getType()) == CEvaluationNode::DELAY); CPPUNIT_ASSERT(((CEvaluationNodeDelay::SubType)CEvaluationNode::subType(pNode->getType())) == CEvaluationNodeDelay::DELAY); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getChild()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(CEvaluationNode::type(pNode->getType()) == CEvaluationNode::OBJECT); CPPUNIT_ASSERT(((CEvaluationNodeObject::SubType)CEvaluationNode::subType(pNode->getType())) == CEvaluationNodeObject::CN); const CEvaluationNodeObject* pObjectNode = dynamic_cast<const CEvaluationNodeObject*>(pNode); CPPUNIT_ASSERT(pObjectNode != NULL); CCopasiObjectName objectCN = pObjectNode->getObjectCN(); CPPUNIT_ASSERT(!objectCN.empty()); std::vector<CCopasiContainer*> listOfContainers; listOfContainers.push_back(pModel); const CCopasiObject* pObject = pCOPASIDATAMODEL->ObjectFromName(listOfContainers, objectCN); CPPUNIT_ASSERT(pObject != NULL); CPPUNIT_ASSERT(pObject->isReference() == true); CPPUNIT_ASSERT(pObject->getObjectName() == std::string("Value")); CPPUNIT_ASSERT(pObject->getObjectParent() == pK1); const CEvaluationNodeNumber* pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pObjectNode->getSibling()); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeNumber::SubType)CEvaluationNode::subType(pNumberNode->getType())) == CEvaluationNodeNumber::DOUBLE); CPPUNIT_ASSERT(fabs((pNumberNode->getValue() - 0.5) / 0.5) < 1e-3); CPPUNIT_ASSERT(pNumberNode->getSibling() == NULL); CPPUNIT_ASSERT(pDummy2 != NULL); CPPUNIT_ASSERT(pDummy2->getStatus() == CModelEntity::ASSIGNMENT); pExpr = pDummy2->getExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(CEvaluationNode::type(pNode->getType()) == CEvaluationNode::DELAY); CPPUNIT_ASSERT(((CEvaluationNodeDelay::SubType)CEvaluationNode::subType(pNode->getType())) == CEvaluationNodeDelay::DELAY); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getChild()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(CEvaluationNode::type(pNode->getType()) == CEvaluationNode::OBJECT); CPPUNIT_ASSERT(((CEvaluationNodeObject::SubType)CEvaluationNode::subType(pNode->getType())) == CEvaluationNodeObject::CN); pObjectNode = dynamic_cast<const CEvaluationNodeObject*>(pNode); CPPUNIT_ASSERT(pObjectNode != NULL); objectCN = pObjectNode->getObjectCN(); CPPUNIT_ASSERT(!objectCN.empty()); pObject = pCOPASIDATAMODEL->ObjectFromName(listOfContainers, objectCN); CPPUNIT_ASSERT(pObject != NULL); CPPUNIT_ASSERT(pObject->isReference() == true); CPPUNIT_ASSERT(pObject->getObjectName() == std::string("Value")); CPPUNIT_ASSERT(pObject->getObjectParent() == pK1); pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pObjectNode->getSibling()); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeNumber::SubType)CEvaluationNode::subType(pNumberNode->getType())) == CEvaluationNodeNumber::DOUBLE); CPPUNIT_ASSERT(fabs((pNumberNode->getValue() - 0.2) / 0.2) < 1e-3); CPPUNIT_ASSERT(pNumberNode->getSibling() == NULL); CPPUNIT_ASSERT(pModel->getReactions().size() == 1); const CReaction* pReaction = pModel->getReactions()[0]; CPPUNIT_ASSERT(pReaction != NULL); CPPUNIT_ASSERT(pReaction->isReversible() == false); // check the kinetic law const CFunction* pKineticFunction = pReaction->getFunction(); CPPUNIT_ASSERT(pKineticFunction != NULL); const CChemEq* pChemEq = &pReaction->getChemEq(); CPPUNIT_ASSERT(pChemEq != NULL); CPPUNIT_ASSERT(pChemEq->getCompartmentNumber() == 1); CPPUNIT_ASSERT(pChemEq->getSubstrates().size() == 1); const CChemEqElement* pElement = pChemEq->getSubstrates()[0]; CPPUNIT_ASSERT(pElement != NULL); CPPUNIT_ASSERT(fabs(pElement->getMultiplicity() - 1.0) < 1e-3); CPPUNIT_ASSERT(pElement->getMetabolite() == pA); CPPUNIT_ASSERT(pChemEq->getProducts().size() == 1); pElement = pChemEq->getProducts()[0]; CPPUNIT_ASSERT(pElement != NULL); CPPUNIT_ASSERT(fabs(pElement->getMultiplicity() - 1.0) < 1e-3); CPPUNIT_ASSERT(pElement->getMetabolite() == pB); CPPUNIT_ASSERT(pChemEq->getModifiers().size() == 0); const std::vector<std::vector<std::string> > parameterMappings = pReaction->getParameterMappings(); CPPUNIT_ASSERT(parameterMappings.size() == 3); CPPUNIT_ASSERT(parameterMappings[0].size() == 1); CPPUNIT_ASSERT(parameterMappings[0][0] == pDummy1->getKey()); CPPUNIT_ASSERT(parameterMappings[1].size() == 1); CPPUNIT_ASSERT(parameterMappings[1][0] == pDummy2->getKey()); CPPUNIT_ASSERT(parameterMappings[2].size() == 1); CPPUNIT_ASSERT(parameterMappings[2][0] == pA->getKey()); const CFunctionParameters& funPars = pKineticFunction->getVariables(); CPPUNIT_ASSERT(funPars.size() == 3); // check the expression of the kinetic law // dummy1 * dummy2 * dummy1 * species1 pNode = pKineticFunction->getRoot(); CPPUNIT_ASSERT(pNode != NULL); const CEvaluationNodeOperator* pOpNode = dynamic_cast<const CEvaluationNodeOperator*>(pNode); CPPUNIT_ASSERT(pOpNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeOperator::SubType)CEvaluationNode::subType(pOpNode->getType())) == CEvaluationNodeOperator::MULTIPLY); const CEvaluationNode* pNode2 = dynamic_cast<const CEvaluationNode*>(pOpNode->getChild()->getSibling()); CPPUNIT_ASSERT(pNode2 != NULL); const CEvaluationNodeVariable* pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pNode2); CPPUNIT_ASSERT(pVarNode != NULL); CPPUNIT_ASSERT(pVarNode->getData() == funPars[2]->getObjectName()); CPPUNIT_ASSERT(pVarNode->getSibling() == NULL); pOpNode = dynamic_cast<const CEvaluationNodeOperator*>(pNode->getChild()); CPPUNIT_ASSERT(pOpNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeOperator::SubType)CEvaluationNode::subType(pOpNode->getType())) == CEvaluationNodeOperator::MULTIPLY); pNode2 = dynamic_cast<const CEvaluationNode*>(pOpNode->getChild()->getSibling()); CPPUNIT_ASSERT(pNode2 != NULL); pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pNode2); CPPUNIT_ASSERT(pVarNode != NULL); CPPUNIT_ASSERT(pVarNode->getData() == funPars[0]->getObjectName()); pOpNode = dynamic_cast<const CEvaluationNodeOperator*>(pOpNode->getChild()); CPPUNIT_ASSERT(pOpNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeOperator::SubType)CEvaluationNode::subType(pOpNode->getType())) == CEvaluationNodeOperator::MULTIPLY); pNode2 = dynamic_cast<const CEvaluationNode*>(pOpNode->getChild()->getSibling()); CPPUNIT_ASSERT(pNode2 != NULL); pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pNode2); CPPUNIT_ASSERT(pVarNode != NULL); CPPUNIT_ASSERT(pVarNode->getData() == funPars[1]->getObjectName()); pNode2 = dynamic_cast<const CEvaluationNode*>(pOpNode->getChild()); CPPUNIT_ASSERT(pNode2 != NULL); pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pNode2); CPPUNIT_ASSERT(pVarNode != NULL); CPPUNIT_ASSERT(pVarNode->getData() == funPars[0]->getObjectName()); // check for the two messages // we should have a message that delay is not supported and we should have a // message about replaced delay nodes CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 36)); CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 86)); // now we reexport the model and check if the changes we made during import // are exported correctly CPPUNIT_ASSERT(pCOPASIDATAMODEL->getCurrentSBMLDocument() != NULL); // export to the same level and version we imported CPPUNIT_ASSERT(pDataModel->exportSBMLToString(NULL, pCOPASIDATAMODEL->getCurrentSBMLDocument()->getLevel(), pCOPASIDATAMODEL->getCurrentSBMLDocument()->getVersion()).empty() == false); SBMLDocument* pDocument = pDataModel->getCurrentSBMLDocument(); CPPUNIT_ASSERT(pDocument != NULL); const Model* pCModel = pDocument->getModel(); CPPUNIT_ASSERT(pCModel != NULL); // assert that there is only one compartment and // assert the compartment is constant CPPUNIT_ASSERT(pCModel->getNumCompartments() == 1); const Compartment* pCCompartment = pCModel->getCompartment(0); CPPUNIT_ASSERT(pCCompartment->getConstant() == true); CPPUNIT_ASSERT(pCModel->getNumSpecies() == 2); const Species* pSpeciesA = pCModel->getSpecies(0); CPPUNIT_ASSERT(pCModel->getNumParameters() == 3); const Parameter* pParameterK1 = pCModel->getParameter(0); CPPUNIT_ASSERT(pParameterK1 != NULL); CPPUNIT_ASSERT(pParameterK1->getConstant() == true); const Parameter* pParameterDummy1 = pCModel->getParameter(1); CPPUNIT_ASSERT(pParameterDummy1 != NULL); CPPUNIT_ASSERT(pParameterDummy1->getConstant() == false); const Parameter* pParameterDummy2 = pCModel->getParameter(2); CPPUNIT_ASSERT(pParameterDummy2 != NULL); CPPUNIT_ASSERT(pParameterDummy2->getConstant() == false); // there must be two rules const AssignmentRule* pARule = dynamic_cast<const AssignmentRule*>(pCModel->getRule(pParameterDummy1->getId())); CPPUNIT_ASSERT(pARule != NULL); const ASTNode* pANode = pARule->getMath(); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_FUNCTION_DELAY); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); const ASTNode* pChild = pANode->getChild(0); CPPUNIT_ASSERT(pChild != NULL); CPPUNIT_ASSERT(pChild->getType() == AST_NAME); CPPUNIT_ASSERT(pChild->getName() == pParameterK1->getId()); pChild = pANode->getChild(1); CPPUNIT_ASSERT(pChild != NULL); CPPUNIT_ASSERT(pChild->getType() == AST_REAL); CPPUNIT_ASSERT(fabs((pChild->getReal() - 0.5) / 0.5) < 1e-9); pARule = dynamic_cast<const AssignmentRule*>(pCModel->getRule(pParameterDummy2->getId())); CPPUNIT_ASSERT(pARule != NULL); pANode = pARule->getMath(); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_FUNCTION_DELAY); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); pChild = pANode->getChild(0); CPPUNIT_ASSERT(pChild != NULL); CPPUNIT_ASSERT(pChild->getType() == AST_NAME); CPPUNIT_ASSERT(pChild->getName() == pParameterK1->getId()); pChild = pANode->getChild(1); CPPUNIT_ASSERT(pChild != NULL); CPPUNIT_ASSERT(pChild->getType() == AST_REAL); CPPUNIT_ASSERT(fabs((pChild->getReal() - 0.2) / 0.2) < 1e-9); const Reaction* pCReaction = pCModel->getReaction(0); // make sure this is reaction A -> CPPUNIT_ASSERT(pCReaction != NULL); CPPUNIT_ASSERT(pCReaction->getNumReactants() == 1); CPPUNIT_ASSERT(pCReaction->getNumProducts() == 1); CPPUNIT_ASSERT(pCReaction->isSetKineticLaw() == true); const KineticLaw* pLaw = pCReaction->getKineticLaw(); CPPUNIT_ASSERT(pLaw != NULL); CPPUNIT_ASSERT(pLaw->isSetMath() == true); pANode = pLaw->getMath(); CPPUNIT_ASSERT(pANode->getType() == AST_TIMES); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); CPPUNIT_ASSERT(pANode->getChild(0)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(0)->getName() == pCCompartment->getId()); pANode = pANode->getChild(1); CPPUNIT_ASSERT(pANode != NULL); // times a function call CPPUNIT_ASSERT(pANode->getType() == AST_FUNCTION); CPPUNIT_ASSERT(pANode->getNumChildren() == 3); CPPUNIT_ASSERT(pANode->getChild(0) != NULL); CPPUNIT_ASSERT(pANode->getChild(0)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(0)->getName() == pParameterDummy1->getId()); CPPUNIT_ASSERT(pANode->getChild(1) != NULL); CPPUNIT_ASSERT(pANode->getChild(1)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(1)->getName() == pParameterDummy2->getId()); CPPUNIT_ASSERT(pANode->getChild(2) != NULL); CPPUNIT_ASSERT(pANode->getChild(2)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(2)->getName() == pSpeciesA->getId()); CPPUNIT_ASSERT(pCModel->getListOfFunctionDefinitions()->size() == 1); const FunctionDefinition* pFunDef = pCModel->getFunctionDefinition(0); CPPUNIT_ASSERT(pFunDef != NULL); CPPUNIT_ASSERT(pFunDef->getId() == pANode->getName()); pANode = pFunDef->getMath(); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_LAMBDA); CPPUNIT_ASSERT(pANode->getNumChildren() == 4); CPPUNIT_ASSERT(pANode->getChild(0)->getType() == AST_NAME); std::string paramName1 = pANode->getChild(0)->getName(); CPPUNIT_ASSERT(!paramName1.empty()); CPPUNIT_ASSERT(pANode->getChild(1)->getType() == AST_NAME); std::string paramName2 = pANode->getChild(1)->getName(); CPPUNIT_ASSERT(!paramName2.empty()); CPPUNIT_ASSERT(pANode->getChild(2)->getType() == AST_NAME); std::string paramName3 = pANode->getChild(2)->getName(); CPPUNIT_ASSERT(!paramName3.empty()); // this is the tree of the function pANode = pANode->getChild(3); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_TIMES); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); CPPUNIT_ASSERT(pANode->getChild(1)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(1)->getName() == paramName3); pANode = pANode->getChild(0); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_TIMES); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); CPPUNIT_ASSERT(pANode->getChild(1)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(1)->getName() == paramName1); pANode = pANode->getChild(0); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_TIMES); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); CPPUNIT_ASSERT(pANode->getChild(0)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(0)->getName() == paramName1); CPPUNIT_ASSERT(pANode->getChild(1)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(1)->getName() == paramName2); } void test000091::test_delay_in_kinetic_law_local_parameter() { CCopasiDataModel* pDataModel = pCOPASIDATAMODEL; CPPUNIT_ASSERT(pDataModel->importSBMLFromString(MODEL_STRING2)); CModel* pModel = pDataModel->getModel(); CPPUNIT_ASSERT(pModel != NULL); CPPUNIT_ASSERT(pModel->getQuantityUnitEnum() == CUnit::mMol); CPPUNIT_ASSERT(pModel->getVolumeUnitEnum() == CUnit::ml); CPPUNIT_ASSERT(pModel->getTimeUnitEnum() == CUnit::s); CPPUNIT_ASSERT(pModel->getCompartments().size() == 1); const CCompartment* pCompartment = pModel->getCompartments()[0]; CPPUNIT_ASSERT(pCompartment != NULL); CPPUNIT_ASSERT(pCompartment->getStatus() == CModelEntity::FIXED); CPPUNIT_ASSERT(pModel->getMetabolites().size() == 2); const CMetab* pB = pModel->getMetabolites()[1]; CPPUNIT_ASSERT(pB != NULL); CPPUNIT_ASSERT(pB->getStatus() == CModelEntity::REACTIONS); CMetab* pA = pModel->getMetabolites()[0]; CPPUNIT_ASSERT(pA != NULL); CPPUNIT_ASSERT(pA->getStatus() == CModelEntity::REACTIONS); // there should now be three model values because we created two dummy model // values that represent the two different delay expression CPPUNIT_ASSERT(pModel->getModelValues().size() == 7); const CModelValue* pK1 = NULL; // four delay replacements const CModelValue* pDummy1 = NULL; const CModelValue* pDummy2 = NULL; const CModelValue* pDummy3 = NULL; const CModelValue* pDummy4 = NULL; // two local parameters that had to be converted to global parameters const CModelValue* pGlobalized1 = NULL; const CModelValue* pGlobalized2 = NULL; // assign all the global parameters pK1 = pModel->getModelValues()["K1"]; CPPUNIT_ASSERT(pK1 != NULL); pDummy1 = pModel->getModelValues()["delay_replacement_parameter_0"]; CPPUNIT_ASSERT(pDummy1 != NULL); pDummy2 = pModel->getModelValues()["delay_replacement_parameter_1"]; CPPUNIT_ASSERT(pDummy2 != NULL); pDummy3 = pModel->getModelValues()["delay_replacement_parameter_2"]; CPPUNIT_ASSERT(pDummy3 != NULL); pDummy4 = pModel->getModelValues()["delay_replacement_parameter_3"]; CPPUNIT_ASSERT(pDummy4 != NULL); CPPUNIT_ASSERT(pModel->getReactions().size() == 1); const CReaction* pReaction = pModel->getReactions()[0]; CPPUNIT_ASSERT(pReaction != NULL); std::string reactionId = pReaction->getSBMLId(); pGlobalized1 = pModel->getModelValues()[reactionId + "_local_0"]; CPPUNIT_ASSERT(pGlobalized1 != NULL); pGlobalized2 = pModel->getModelValues()[reactionId + "_local_1"]; CPPUNIT_ASSERT(pGlobalized2 != NULL); // check if K1 has the correct value CPPUNIT_ASSERT(pK1 != NULL); CPPUNIT_ASSERT(pK1->getStatus() == CModelEntity::FIXED); CPPUNIT_ASSERT(fabs((pK1->getInitialValue() - 4.0) / 4.0) < 1e-9); // check if pGlobalized1 (former k3) has the correct value CPPUNIT_ASSERT(pGlobalized1 != NULL); CPPUNIT_ASSERT(pGlobalized1->getStatus() == CModelEntity::FIXED); CPPUNIT_ASSERT(fabs((pGlobalized1->getInitialValue() - 0.3) / 0.3) < 1e-9); // check if pGlobalized2 (former k2) has the correct value CPPUNIT_ASSERT(pGlobalized2 != NULL); CPPUNIT_ASSERT(pGlobalized2->getStatus() == CModelEntity::FIXED); CPPUNIT_ASSERT(fabs((pGlobalized2->getInitialValue() - 0.2) / 0.2) < 1e-9); // check if pDummy1 has the correct expression CPPUNIT_ASSERT(pDummy1->getStatus() == CModelEntity::ASSIGNMENT); const CExpression* pExpr = pDummy1->getExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); const CEvaluationNode* pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(CEvaluationNode::type(pNode->getType()) == CEvaluationNode::DELAY); CPPUNIT_ASSERT(((CEvaluationNodeDelay::SubType)CEvaluationNode::subType(pNode->getType())) == CEvaluationNodeDelay::DELAY); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getChild()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(CEvaluationNode::type(pNode->getType()) == CEvaluationNode::OBJECT); CPPUNIT_ASSERT(((CEvaluationNodeObject::SubType)CEvaluationNode::subType(pNode->getType())) == CEvaluationNodeObject::CN); const CEvaluationNodeObject* pObjectNode = dynamic_cast<const CEvaluationNodeObject*>(pNode); CPPUNIT_ASSERT(pObjectNode != NULL); CCopasiObjectName objectCN = pObjectNode->getObjectCN(); CPPUNIT_ASSERT(!objectCN.empty()); std::vector<CCopasiContainer*> listOfContainers; listOfContainers.push_back(pModel); const CCopasiObject* pObject = pCOPASIDATAMODEL->ObjectFromName(listOfContainers, objectCN); CPPUNIT_ASSERT(pObject != NULL); CPPUNIT_ASSERT(pObject->isReference() == true); CPPUNIT_ASSERT(pObject->getObjectName() == std::string("Value")); CPPUNIT_ASSERT(pObject->getObjectParent() == pK1); const CEvaluationNodeNumber* pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pObjectNode->getSibling()); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeNumber::SubType)CEvaluationNode::subType(pNumberNode->getType())) == CEvaluationNodeNumber::DOUBLE); CPPUNIT_ASSERT(fabs((pNumberNode->getValue() - 0.5) / 0.5) < 1e-3); CPPUNIT_ASSERT(pNumberNode->getSibling() == NULL); // check if pDummy2 has the correct expression CPPUNIT_ASSERT(pDummy2->getStatus() == CModelEntity::ASSIGNMENT); pExpr = pDummy2->getExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(CEvaluationNode::type(pNode->getType()) == CEvaluationNode::DELAY); CPPUNIT_ASSERT(((CEvaluationNodeDelay::SubType)CEvaluationNode::subType(pNode->getType())) == CEvaluationNodeDelay::DELAY); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getChild()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(CEvaluationNode::type(pNode->getType()) == CEvaluationNode::OBJECT); CPPUNIT_ASSERT(((CEvaluationNodeObject::SubType)CEvaluationNode::subType(pNode->getType())) == CEvaluationNodeObject::CN); pObjectNode = dynamic_cast<const CEvaluationNodeObject*>(pNode); CPPUNIT_ASSERT(pObjectNode != NULL); objectCN = pObjectNode->getObjectCN(); CPPUNIT_ASSERT(!objectCN.empty()); pObject = pCOPASIDATAMODEL->ObjectFromName(listOfContainers, objectCN); CPPUNIT_ASSERT(pObject != NULL); CPPUNIT_ASSERT(pObject->isReference() == true); CPPUNIT_ASSERT(pObject->getObjectName() == std::string("Value")); CPPUNIT_ASSERT(pObject->getObjectParent() == pK1); pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pObjectNode->getSibling()); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeNumber::SubType)CEvaluationNode::subType(pNumberNode->getType())) == CEvaluationNodeNumber::DOUBLE); CPPUNIT_ASSERT(fabs((pNumberNode->getValue() - 0.2) / 0.2) < 1e-3); CPPUNIT_ASSERT(pNumberNode->getSibling() == NULL); // check if pDummy3 has the correct expression CPPUNIT_ASSERT(pDummy3->getStatus() == CModelEntity::ASSIGNMENT); pExpr = pDummy3->getExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(CEvaluationNode::type(pNode->getType()) == CEvaluationNode::DELAY); CPPUNIT_ASSERT(((CEvaluationNodeDelay::SubType)CEvaluationNode::subType(pNode->getType())) == CEvaluationNodeDelay::DELAY); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getChild()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(CEvaluationNode::type(pNode->getType()) == CEvaluationNode::OBJECT); CPPUNIT_ASSERT(((CEvaluationNodeObject::SubType)CEvaluationNode::subType(pNode->getType())) == CEvaluationNodeObject::CN); pObjectNode = dynamic_cast<const CEvaluationNodeObject*>(pNode); CPPUNIT_ASSERT(pObjectNode != NULL); objectCN = pObjectNode->getObjectCN(); CPPUNIT_ASSERT(!objectCN.empty()); pObject = pCOPASIDATAMODEL->ObjectFromName(listOfContainers, objectCN); CPPUNIT_ASSERT(pObject != NULL); CPPUNIT_ASSERT(pObject->isReference() == true); CPPUNIT_ASSERT(pObject->getObjectName() == std::string("Value")); CPPUNIT_ASSERT(pObject->getObjectParent() == pGlobalized1); pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pObjectNode->getSibling()); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeNumber::SubType)CEvaluationNode::subType(pNumberNode->getType())) == CEvaluationNodeNumber::DOUBLE); CPPUNIT_ASSERT(fabs((pNumberNode->getValue() - 0.5) / 0.5) < 1e-3); CPPUNIT_ASSERT(pNumberNode->getSibling() == NULL); // check if pDummy4 has the correct expression CPPUNIT_ASSERT(pDummy4->getStatus() == CModelEntity::ASSIGNMENT); pExpr = pDummy4->getExpressionPtr(); CPPUNIT_ASSERT(pExpr != NULL); pNode = pExpr->getRoot(); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(CEvaluationNode::type(pNode->getType()) == CEvaluationNode::DELAY); CPPUNIT_ASSERT(((CEvaluationNodeDelay::SubType)CEvaluationNode::subType(pNode->getType())) == CEvaluationNodeDelay::DELAY); pNode = dynamic_cast<const CEvaluationNode*>(pNode->getChild()); CPPUNIT_ASSERT(pNode != NULL); CPPUNIT_ASSERT(CEvaluationNode::type(pNode->getType()) == CEvaluationNode::OBJECT); CPPUNIT_ASSERT(((CEvaluationNodeObject::SubType)CEvaluationNode::subType(pNode->getType())) == CEvaluationNodeObject::CN); pObjectNode = dynamic_cast<const CEvaluationNodeObject*>(pNode); CPPUNIT_ASSERT(pObjectNode != NULL); objectCN = pObjectNode->getObjectCN(); CPPUNIT_ASSERT(!objectCN.empty()); pObject = pCOPASIDATAMODEL->ObjectFromName(listOfContainers, objectCN); CPPUNIT_ASSERT(pObject != NULL); CPPUNIT_ASSERT(pObject->isReference() == true); CPPUNIT_ASSERT(pObject->getObjectName() == std::string("Value")); CPPUNIT_ASSERT(pObject->getObjectParent() == pGlobalized2); pNumberNode = dynamic_cast<const CEvaluationNodeNumber*>(pObjectNode->getSibling()); CPPUNIT_ASSERT(pNumberNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeNumber::SubType)CEvaluationNode::subType(pNumberNode->getType())) == CEvaluationNodeNumber::DOUBLE); CPPUNIT_ASSERT(fabs((pNumberNode->getValue() - 0.5) / 0.5) < 1e-3); CPPUNIT_ASSERT(pNumberNode->getSibling() == NULL); CPPUNIT_ASSERT(pReaction->isReversible() == false); // check the kinetic law const CFunction* pKineticFunction = pReaction->getFunction(); CPPUNIT_ASSERT(pKineticFunction != NULL); const CChemEq* pChemEq = &pReaction->getChemEq(); CPPUNIT_ASSERT(pChemEq != NULL); CPPUNIT_ASSERT(pChemEq->getCompartmentNumber() == 1); CPPUNIT_ASSERT(pChemEq->getSubstrates().size() == 1); const CChemEqElement* pElement = pChemEq->getSubstrates()[0]; CPPUNIT_ASSERT(pElement != NULL); CPPUNIT_ASSERT(fabs(pElement->getMultiplicity() - 1.0) < 1e-3); CPPUNIT_ASSERT(pElement->getMetabolite() == pA); CPPUNIT_ASSERT(pChemEq->getProducts().size() == 1); pElement = pChemEq->getProducts()[0]; CPPUNIT_ASSERT(pElement != NULL); CPPUNIT_ASSERT(fabs(pElement->getMultiplicity() - 1.0) < 1e-3); CPPUNIT_ASSERT(pElement->getMetabolite() == pB); CPPUNIT_ASSERT(pChemEq->getModifiers().size() == 0); const std::vector<std::vector<std::string> > parameterMappings = pReaction->getParameterMappings(); CPPUNIT_ASSERT(parameterMappings.size() == 7); CPPUNIT_ASSERT(parameterMappings[0].size() == 1); CPPUNIT_ASSERT(pReaction->isLocalParameter(0) == false); CPPUNIT_ASSERT(parameterMappings[0][0] == pDummy1->getKey()); CPPUNIT_ASSERT(parameterMappings[1].size() == 1); CPPUNIT_ASSERT(pReaction->isLocalParameter(1) == false); CPPUNIT_ASSERT(parameterMappings[1][0] == pDummy2->getKey()); CPPUNIT_ASSERT(parameterMappings[2].size() == 1); CPPUNIT_ASSERT(pReaction->isLocalParameter(2) == false); CPPUNIT_ASSERT(parameterMappings[2][0] == pDummy3->getKey()); CPPUNIT_ASSERT(parameterMappings[3].size() == 1); CPPUNIT_ASSERT(pReaction->isLocalParameter(3) == false); CPPUNIT_ASSERT(parameterMappings[3][0] == pDummy4->getKey()); CPPUNIT_ASSERT(parameterMappings[4].size() == 1); CPPUNIT_ASSERT(pReaction->isLocalParameter(4) == true); const CCopasiParameter* pLocalParam = pReaction->getParameters().getParameter("k1"); CPPUNIT_ASSERT(pLocalParam != NULL); CPPUNIT_ASSERT(parameterMappings[5].size() == 1); CPPUNIT_ASSERT(pReaction->isLocalParameter(5) == false); CPPUNIT_ASSERT(parameterMappings[5][0] == pGlobalized1->getKey()); CPPUNIT_ASSERT(parameterMappings[6].size() == 1); CPPUNIT_ASSERT(parameterMappings[6][0] == pA->getKey()); const CFunctionParameters& funPars = pKineticFunction->getVariables(); CPPUNIT_ASSERT(funPars.size() == 7); // check the expression of the kinetic law // dummy1 * dummy2 * dummy1 * species1 * k1 * dummy3 * dummy4 * dummy3 * globalized1 pNode = pKineticFunction->getRoot(); CPPUNIT_ASSERT(pNode != NULL); const CEvaluationNodeOperator* pOpNode = dynamic_cast<const CEvaluationNodeOperator*>(pNode); CPPUNIT_ASSERT(pOpNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeOperator::SubType)CEvaluationNode::subType(pOpNode->getType())) == CEvaluationNodeOperator::MULTIPLY); const CEvaluationNode* pNode2 = dynamic_cast<const CEvaluationNode*>(pOpNode->getChild()->getSibling()); CPPUNIT_ASSERT(pNode2 != NULL); const CEvaluationNodeVariable* pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pNode2); CPPUNIT_ASSERT(pVarNode != NULL); CPPUNIT_ASSERT(pVarNode->getData() == funPars[5]->getObjectName()); CPPUNIT_ASSERT(pVarNode->getSibling() == NULL); pOpNode = dynamic_cast<const CEvaluationNodeOperator*>(pNode->getChild()); CPPUNIT_ASSERT(pOpNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeOperator::SubType)CEvaluationNode::subType(pOpNode->getType())) == CEvaluationNodeOperator::MULTIPLY); pNode2 = dynamic_cast<const CEvaluationNode*>(pOpNode->getChild()->getSibling()); CPPUNIT_ASSERT(pNode2 != NULL); pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pNode2); CPPUNIT_ASSERT(pVarNode != NULL); CPPUNIT_ASSERT(pVarNode->getData() == funPars[2]->getObjectName()); pOpNode = dynamic_cast<const CEvaluationNodeOperator*>(pOpNode->getChild()); CPPUNIT_ASSERT(pOpNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeOperator::SubType)CEvaluationNode::subType(pOpNode->getType())) == CEvaluationNodeOperator::MULTIPLY); pNode2 = dynamic_cast<const CEvaluationNode*>(pOpNode->getChild()->getSibling()); CPPUNIT_ASSERT(pNode2 != NULL); pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pNode2); CPPUNIT_ASSERT(pVarNode != NULL); CPPUNIT_ASSERT(pVarNode->getData() == funPars[3]->getObjectName()); pOpNode = dynamic_cast<const CEvaluationNodeOperator*>(pOpNode->getChild()); CPPUNIT_ASSERT(pOpNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeOperator::SubType)CEvaluationNode::subType(pOpNode->getType())) == CEvaluationNodeOperator::MULTIPLY); pNode2 = dynamic_cast<const CEvaluationNode*>(pOpNode->getChild()->getSibling()); CPPUNIT_ASSERT(pNode2 != NULL); pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pNode2); CPPUNIT_ASSERT(pVarNode != NULL); CPPUNIT_ASSERT(pVarNode->getData() == funPars[2]->getObjectName()); pOpNode = dynamic_cast<const CEvaluationNodeOperator*>(pOpNode->getChild()); CPPUNIT_ASSERT(pOpNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeOperator::SubType)CEvaluationNode::subType(pOpNode->getType())) == CEvaluationNodeOperator::MULTIPLY); pNode2 = dynamic_cast<const CEvaluationNode*>(pOpNode->getChild()->getSibling()); CPPUNIT_ASSERT(pNode2 != NULL); pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pNode2); CPPUNIT_ASSERT(pVarNode != NULL); CPPUNIT_ASSERT(pVarNode->getData() == funPars[4]->getObjectName()); pOpNode = dynamic_cast<const CEvaluationNodeOperator*>(pOpNode->getChild()); CPPUNIT_ASSERT(pOpNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeOperator::SubType)CEvaluationNode::subType(pOpNode->getType())) == CEvaluationNodeOperator::MULTIPLY); pNode2 = dynamic_cast<const CEvaluationNode*>(pOpNode->getChild()->getSibling()); CPPUNIT_ASSERT(pNode2 != NULL); pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pNode2); CPPUNIT_ASSERT(pVarNode != NULL); CPPUNIT_ASSERT(pVarNode->getData() == funPars[6]->getObjectName()); pOpNode = dynamic_cast<const CEvaluationNodeOperator*>(pOpNode->getChild()); CPPUNIT_ASSERT(pOpNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeOperator::SubType)CEvaluationNode::subType(pOpNode->getType())) == CEvaluationNodeOperator::MULTIPLY); pNode2 = dynamic_cast<const CEvaluationNode*>(pOpNode->getChild()->getSibling()); CPPUNIT_ASSERT(pNode2 != NULL); pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pNode2); CPPUNIT_ASSERT(pVarNode != NULL); CPPUNIT_ASSERT(pVarNode->getData() == funPars[0]->getObjectName()); pOpNode = dynamic_cast<const CEvaluationNodeOperator*>(pOpNode->getChild()); CPPUNIT_ASSERT(pOpNode != NULL); CPPUNIT_ASSERT(((CEvaluationNodeOperator::SubType)CEvaluationNode::subType(pOpNode->getType())) == CEvaluationNodeOperator::MULTIPLY); pNode2 = dynamic_cast<const CEvaluationNode*>(pOpNode->getChild()->getSibling()); CPPUNIT_ASSERT(pNode2 != NULL); pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pNode2); CPPUNIT_ASSERT(pVarNode != NULL); CPPUNIT_ASSERT(pVarNode->getData() == funPars[1]->getObjectName()); pNode2 = dynamic_cast<const CEvaluationNode*>(pOpNode->getChild()); CPPUNIT_ASSERT(pNode2 != NULL); pVarNode = dynamic_cast<const CEvaluationNodeVariable*>(pNode2); CPPUNIT_ASSERT(pVarNode != NULL); CPPUNIT_ASSERT(pVarNode->getData() == funPars[0]->getObjectName()); // check for the two messages // we should have a message that delay is not supported and we should have a // message about replaced delay nodes CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 36)); CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 86)); CPPUNIT_ASSERT(CCopasiMessage::checkForMessage(MCSBML + 87)); // now we reexport the model and check if the changes we made during import // are exported correctly CPPUNIT_ASSERT(pCOPASIDATAMODEL->getCurrentSBMLDocument() != NULL); // export to the same level and version we imported CPPUNIT_ASSERT(pDataModel->exportSBMLToString(NULL, pCOPASIDATAMODEL->getCurrentSBMLDocument()->getLevel(), pCOPASIDATAMODEL->getCurrentSBMLDocument()->getVersion()).empty() == false); SBMLDocument* pDocument = pDataModel->getCurrentSBMLDocument(); CPPUNIT_ASSERT(pDocument != NULL); const Model* pCModel = pDocument->getModel(); CPPUNIT_ASSERT(pCModel != NULL); // assert that there is only one compartment and // assert the compartment is constant CPPUNIT_ASSERT(pCModel->getNumCompartments() == 1); const Compartment* pCCompartment = pCModel->getCompartment(0); CPPUNIT_ASSERT(pCCompartment->getConstant() == true); CPPUNIT_ASSERT(pCModel->getNumSpecies() == 2); const Species* pSpeciesA = pCModel->getSpecies(0); CPPUNIT_ASSERT(pCModel->getNumParameters() == 7); const Parameter* pParameterK1 = pCModel->getParameter(0); CPPUNIT_ASSERT(pParameterK1 != NULL); CPPUNIT_ASSERT(pParameterK1->getConstant() == true); CPPUNIT_ASSERT(fabs((pParameterK1->getValue() - 4.0) / 4.0) < 1e-9); const Parameter* pParameterDummy1 = pCModel->getParameter(1); CPPUNIT_ASSERT(pParameterDummy1 != NULL); CPPUNIT_ASSERT(pParameterDummy1->getConstant() == false); const Parameter* pParameterDummy2 = pCModel->getParameter(2); CPPUNIT_ASSERT(pParameterDummy2 != NULL); CPPUNIT_ASSERT(pParameterDummy2->getConstant() == false); const Parameter* pParameterDummy3 = pCModel->getParameter(3); CPPUNIT_ASSERT(pParameterDummy3 != NULL); CPPUNIT_ASSERT(pParameterDummy3->getConstant() == false); const Parameter* pGlobalizedParam1 = pCModel->getParameter(4); CPPUNIT_ASSERT(pGlobalizedParam1 != NULL); CPPUNIT_ASSERT(pGlobalizedParam1->getConstant() == true); CPPUNIT_ASSERT(fabs((pGlobalizedParam1->getValue() - 0.3) / 0.3) < 1e-9); const Parameter* pParameterDummy4 = pCModel->getParameter(5); CPPUNIT_ASSERT(pParameterDummy4 != NULL); CPPUNIT_ASSERT(pParameterDummy4->getConstant() == false); const Parameter* pGlobalizedParam2 = pCModel->getParameter(6); CPPUNIT_ASSERT(pGlobalizedParam2 != NULL); CPPUNIT_ASSERT(pGlobalizedParam2->getConstant() == true); CPPUNIT_ASSERT(fabs((pGlobalizedParam2->getValue() - 0.2) / 0.2) < 1e-9); // // there must be four rules const AssignmentRule* pARule = dynamic_cast<const AssignmentRule*>(pCModel->getRule(pParameterDummy1->getId())); CPPUNIT_ASSERT(pARule != NULL); const ASTNode* pANode = pARule->getMath(); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_FUNCTION_DELAY); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); const ASTNode* pChild = pANode->getChild(0); CPPUNIT_ASSERT(pChild != NULL); CPPUNIT_ASSERT(pChild->getType() == AST_NAME); CPPUNIT_ASSERT(pChild->getName() == pParameterK1->getId()); pChild = pANode->getChild(1); CPPUNIT_ASSERT(pChild != NULL); CPPUNIT_ASSERT(pChild->getType() == AST_REAL); CPPUNIT_ASSERT(fabs((pChild->getReal() - 0.5) / 0.5) < 1e-9); pARule = dynamic_cast<const AssignmentRule*>(pCModel->getRule(pParameterDummy2->getId())); CPPUNIT_ASSERT(pARule != NULL); pANode = pARule->getMath(); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_FUNCTION_DELAY); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); pChild = pANode->getChild(0); CPPUNIT_ASSERT(pChild != NULL); CPPUNIT_ASSERT(pChild->getType() == AST_NAME); CPPUNIT_ASSERT(pChild->getName() == pParameterK1->getId()); pChild = pANode->getChild(1); CPPUNIT_ASSERT(pChild != NULL); CPPUNIT_ASSERT(pChild->getType() == AST_REAL); CPPUNIT_ASSERT(fabs((pChild->getReal() - 0.2) / 0.2) < 1e-9); // rule for dummy3 pARule = dynamic_cast<const AssignmentRule*>(pCModel->getRule(pParameterDummy3->getId())); CPPUNIT_ASSERT(pARule != NULL); pANode = pARule->getMath(); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_FUNCTION_DELAY); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); pChild = pANode->getChild(0); CPPUNIT_ASSERT(pChild != NULL); CPPUNIT_ASSERT(pChild->getType() == AST_NAME); CPPUNIT_ASSERT(pChild->getName() == pGlobalizedParam1->getId()); pChild = pANode->getChild(1); CPPUNIT_ASSERT(pChild != NULL); CPPUNIT_ASSERT(pChild->getType() == AST_REAL); CPPUNIT_ASSERT(fabs((pChild->getReal() - 0.5) / 0.5) < 1e-9); // rule for dummy4 pARule = dynamic_cast<const AssignmentRule*>(pCModel->getRule(pParameterDummy4->getId())); CPPUNIT_ASSERT(pARule != NULL); pANode = pARule->getMath(); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_FUNCTION_DELAY); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); pChild = pANode->getChild(0); CPPUNIT_ASSERT(pChild != NULL); CPPUNIT_ASSERT(pChild->getType() == AST_NAME); CPPUNIT_ASSERT(pChild->getName() == pGlobalizedParam2->getId()); pChild = pANode->getChild(1); CPPUNIT_ASSERT(pChild != NULL); CPPUNIT_ASSERT(pChild->getType() == AST_REAL); CPPUNIT_ASSERT(fabs((pChild->getReal() - 0.5) / 0.5) < 1e-9); const Reaction* pCReaction = pCModel->getReaction(0); // make sure this is reaction A -> CPPUNIT_ASSERT(pCReaction != NULL); CPPUNIT_ASSERT(pCReaction->getNumReactants() == 1); CPPUNIT_ASSERT(pCReaction->getNumProducts() == 1); CPPUNIT_ASSERT(pCReaction->isSetKineticLaw() == true); const KineticLaw* pLaw = pCReaction->getKineticLaw(); CPPUNIT_ASSERT(pLaw != NULL); CPPUNIT_ASSERT(pLaw->getNumParameters() == 1); const Parameter* pLocalP = pLaw->getParameter(0); CPPUNIT_ASSERT(pLocalP != NULL); CPPUNIT_ASSERT(fabs((pLocalP->getValue() - 0.1) / 0.1) < 1e-9); CPPUNIT_ASSERT(pLaw->isSetMath() == true); pANode = pLaw->getMath(); CPPUNIT_ASSERT(pANode->getType() == AST_TIMES); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); CPPUNIT_ASSERT(pANode->getChild(0)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(0)->getName() == pCCompartment->getId()); pANode = pANode->getChild(1); CPPUNIT_ASSERT(pANode != NULL); // times a function call CPPUNIT_ASSERT(pANode->getType() == AST_FUNCTION); CPPUNIT_ASSERT(pANode->getNumChildren() == 7); CPPUNIT_ASSERT(pANode->getChild(0) != NULL); CPPUNIT_ASSERT(pANode->getChild(0)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(0)->getName() == pParameterDummy1->getId()); CPPUNIT_ASSERT(pANode->getChild(1) != NULL); CPPUNIT_ASSERT(pANode->getChild(1)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(1)->getName() == pParameterDummy2->getId()); CPPUNIT_ASSERT(pANode->getChild(2) != NULL); CPPUNIT_ASSERT(pANode->getChild(2)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(2)->getName() == pParameterDummy3->getId()); CPPUNIT_ASSERT(pANode->getChild(3) != NULL); CPPUNIT_ASSERT(pANode->getChild(3)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(3)->getName() == pParameterDummy4->getId()); CPPUNIT_ASSERT(pANode->getChild(4) != NULL); CPPUNIT_ASSERT(pANode->getChild(4)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(4)->getName() == pLocalP->getId()); CPPUNIT_ASSERT(pANode->getChild(5) != NULL); CPPUNIT_ASSERT(pANode->getChild(5)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(5)->getName() == pGlobalizedParam1->getId()); CPPUNIT_ASSERT(pANode->getChild(6) != NULL); CPPUNIT_ASSERT(pANode->getChild(6)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(6)->getName() == pSpeciesA->getId()); CPPUNIT_ASSERT(pCModel->getListOfFunctionDefinitions()->size() == 1); const FunctionDefinition* pFunDef = pCModel->getFunctionDefinition(0); CPPUNIT_ASSERT(pFunDef != NULL); CPPUNIT_ASSERT(pFunDef->getId() == pANode->getName()); pANode = pFunDef->getMath(); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_LAMBDA); CPPUNIT_ASSERT(pANode->getNumChildren() == 8); CPPUNIT_ASSERT(pANode->getChild(0)->getType() == AST_NAME); std::string paramName1 = pANode->getChild(0)->getName(); CPPUNIT_ASSERT(!paramName1.empty()); CPPUNIT_ASSERT(pANode->getChild(1)->getType() == AST_NAME); std::string paramName2 = pANode->getChild(1)->getName(); CPPUNIT_ASSERT(!paramName2.empty()); CPPUNIT_ASSERT(pANode->getChild(2)->getType() == AST_NAME); std::string paramName3 = pANode->getChild(2)->getName(); CPPUNIT_ASSERT(!paramName3.empty()); CPPUNIT_ASSERT(pANode->getChild(3)->getType() == AST_NAME); std::string paramName4 = pANode->getChild(3)->getName(); CPPUNIT_ASSERT(!paramName4.empty()); CPPUNIT_ASSERT(pANode->getChild(4)->getType() == AST_NAME); std::string paramName5 = pANode->getChild(4)->getName(); CPPUNIT_ASSERT(!paramName5.empty()); CPPUNIT_ASSERT(pANode->getChild(5)->getType() == AST_NAME); std::string paramName6 = pANode->getChild(5)->getName(); CPPUNIT_ASSERT(!paramName6.empty()); CPPUNIT_ASSERT(pANode->getChild(6)->getType() == AST_NAME); std::string paramName7 = pANode->getChild(6)->getName(); CPPUNIT_ASSERT(!paramName7.empty()); // // this is the tree of the function pANode = pANode->getChild(7); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_TIMES); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); CPPUNIT_ASSERT(pANode->getChild(1)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(1)->getName() == paramName6); pANode = pANode->getChild(0); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_TIMES); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); CPPUNIT_ASSERT(pANode->getChild(1)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(1)->getName() == paramName3); pANode = pANode->getChild(0); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_TIMES); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); CPPUNIT_ASSERT(pANode->getChild(1)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(1)->getName() == paramName4); pANode = pANode->getChild(0); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_TIMES); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); CPPUNIT_ASSERT(pANode->getChild(1)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(1)->getName() == paramName3); pANode = pANode->getChild(0); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_TIMES); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); CPPUNIT_ASSERT(pANode->getChild(1)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(1)->getName() == paramName5); pANode = pANode->getChild(0); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_TIMES); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); CPPUNIT_ASSERT(pANode->getChild(1)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(1)->getName() == paramName7); pANode = pANode->getChild(0); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_TIMES); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); CPPUNIT_ASSERT(pANode->getChild(1)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(1)->getName() == paramName1); pANode = pANode->getChild(0); CPPUNIT_ASSERT(pANode != NULL); CPPUNIT_ASSERT(pANode->getType() == AST_TIMES); CPPUNIT_ASSERT(pANode->getNumChildren() == 2); CPPUNIT_ASSERT(pANode->getChild(0)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(0)->getName() == paramName1); CPPUNIT_ASSERT(pANode->getChild(1)->getType() == AST_NAME); CPPUNIT_ASSERT(pANode->getChild(1)->getName() == paramName2); } const char* test000091::MODEL_STRING1 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<sbml xmlns=\"http://www.sbml.org/sbml/level2/version3\" level=\"2\" version=\"3\">\n" " <model id=\"Model_1\" name=\"New Model\">\n" " <notes>\n" " <body xmlns=\"http://www.w3.org/1999/xhtml\">\n" " <p>Model with delay in kinetic law</p>\n" " </body>\n" " </notes>\n" " <listOfUnitDefinitions>\n" " <unitDefinition id=\"volume\">\n" " <listOfUnits>\n" " <unit kind=\"litre\" scale=\"-3\"/>\n" " </listOfUnits>\n" " </unitDefinition>\n" " <unitDefinition id=\"substance\">\n" " <listOfUnits>\n" " <unit kind=\"mole\" scale=\"-3\"/>\n" " </listOfUnits>\n" " </unitDefinition>\n" " </listOfUnitDefinitions>\n" " <listOfCompartments>\n" " <compartment id=\"compartment_1\" name=\"compartment\" size=\"1\"/>\n" " </listOfCompartments>\n" " <listOfSpecies>\n" " <species id=\"species_1\" name=\"A\" compartment=\"compartment_1\" initialConcentration=\"1\"/>\n" " <species id=\"species_2\" name=\"B\" compartment=\"compartment_1\" initialConcentration=\"1\"/>\n" " </listOfSpecies>\n" " <listOfParameters>\n" " <parameter id=\"parameter_1\" name=\"K1\" value=\"4\"/>\n" " </listOfParameters>\n" " <listOfReactions>\n" " <reaction id=\"reaction_1\" name=\"reaction_0\" reversible=\"false\">\n" " <listOfReactants>\n" " <speciesReference species=\"species_1\"/>\n" " </listOfReactants>\n" " <listOfProducts>\n" " <speciesReference species=\"species_2\"/>\n" " </listOfProducts>\n" " <kineticLaw>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <times/>\n" " <ci> compartment_1 </ci>i\n" " <apply>\n" " <csymbol encoding=\"text\" definitionURL=\"http://www.sbml.org/sbml/symbols/delay\">\n" " delay\n" " </csymbol>\n" " <ci> parameter_1 </ci>\n" " <cn> 0.5 </cn>\n" " </apply>\n" " <apply>\n" " <csymbol encoding=\"text\" definitionURL=\"http://www.sbml.org/sbml/symbols/delay\">\n" " delay\n" " </csymbol>\n" " <ci> parameter_1 </ci>\n" " <cn> 0.2 </cn>\n" " </apply>\n" " <apply>\n" " <csymbol encoding=\"text\" definitionURL=\"http://www.sbml.org/sbml/symbols/delay\">\n" " delay\n" " </csymbol>\n" " <ci> parameter_1 </ci>\n" " <cn> 0.5 </cn>\n" " </apply>\n" " <ci> species_1 </ci>\n" " </apply>\n" " </math>\n" " </kineticLaw>\n" " </reaction>\n" " </listOfReactions>\n" " </model>\n" "</sbml>\n" ; const char* test000091::MODEL_STRING2 = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" "<sbml xmlns=\"http://www.sbml.org/sbml/level2/version3\" level=\"2\" version=\"3\">\n" " <model id=\"Model_1\" name=\"New Model\">\n" " <notes>\n" " <body xmlns=\"http://www.w3.org/1999/xhtml\">\n" " <p>Model with delay in kinetic law as well as local parameters in delay expression</p>\n" " </body>\n" " </notes>\n" " <listOfUnitDefinitions>\n" " <unitDefinition id=\"volume\">\n" " <listOfUnits>\n" " <unit kind=\"litre\" scale=\"-3\"/>\n" " </listOfUnits>\n" " </unitDefinition>\n" " <unitDefinition id=\"substance\">\n" " <listOfUnits>\n" " <unit kind=\"mole\" scale=\"-3\"/>\n" " </listOfUnits>\n" " </unitDefinition>\n" " </listOfUnitDefinitions>\n" " <listOfCompartments>\n" " <compartment id=\"compartment_1\" name=\"compartment\" size=\"1\"/>\n" " </listOfCompartments>\n" " <listOfSpecies>\n" " <species id=\"species_1\" name=\"A\" compartment=\"compartment_1\" initialConcentration=\"1\"/>\n" " <species id=\"species_2\" name=\"B\" compartment=\"compartment_1\" initialConcentration=\"1\"/>\n" " </listOfSpecies>\n" " <listOfParameters>\n" " <parameter id=\"parameter_1\" name=\"K1\" value=\"4\"/>\n" " </listOfParameters>\n" " <listOfReactions>\n" " <reaction id=\"reaction_1\" name=\"reaction_0\" reversible=\"false\">\n" " <listOfReactants>\n" " <speciesReference species=\"species_1\"/>\n" " </listOfReactants>\n" " <listOfProducts>\n" " <speciesReference species=\"species_2\"/>\n" " </listOfProducts>\n" " <kineticLaw>\n" " <math xmlns=\"http://www.w3.org/1998/Math/MathML\">\n" " <apply>\n" " <times/>\n" " <ci> compartment_1 </ci>i\n" " <apply>\n" " <csymbol encoding=\"text\" definitionURL=\"http://www.sbml.org/sbml/symbols/delay\">\n" " delay\n" " </csymbol>\n" " <ci> parameter_1 </ci>\n" " <cn> 0.5 </cn>\n" " </apply>\n" " <apply>\n" " <csymbol encoding=\"text\" definitionURL=\"http://www.sbml.org/sbml/symbols/delay\">\n" " delay\n" " </csymbol>\n" " <ci> parameter_1 </ci>\n" " <cn> 0.2 </cn>\n" " </apply>\n" " <apply>\n" " <csymbol encoding=\"text\" definitionURL=\"http://www.sbml.org/sbml/symbols/delay\">\n" " delay\n" " </csymbol>\n" " <ci> parameter_1 </ci>\n" " <cn> 0.5 </cn>\n" " </apply>\n" " <ci> species_1 </ci>\n" " <ci> k1 </ci>\n" " <apply>\n" " <csymbol encoding=\"text\" definitionURL=\"http://www.sbml.org/sbml/symbols/delay\">\n" " delay\n" " </csymbol>\n" " <ci> k3 </ci>\n" " <cn> 0.5 </cn>\n" " </apply>\n" " <apply>\n" " <csymbol encoding=\"text\" definitionURL=\"http://www.sbml.org/sbml/symbols/delay\">\n" " delay\n" " </csymbol>\n" " <ci> k2 </ci>\n" " <cn> 0.5 </cn>\n" " </apply>\n" " <apply>\n" " <csymbol encoding=\"text\" definitionURL=\"http://www.sbml.org/sbml/symbols/delay\">\n" " delay\n" " </csymbol>\n" " <ci> k3 </ci>\n" " <cn> 0.5 </cn>\n" " </apply>\n" " <ci> k3 </ci>\n" " </apply>\n" " </math>\n" " <listOfParameters>" " <parameter id=\"k1\" value=\"0.1\"/>" " <parameter id=\"k2\" value=\"0.2\"/>" " <parameter id=\"k3\" value=\"0.3\"/>" " </listOfParameters>" " </kineticLaw>\n" " </reaction>\n" " </listOfReactions>\n" " </model>\n" "</sbml>\n" ;
49.888889
186
0.696188
[ "object", "vector", "model" ]
70be83eabd46826966a1146685018a699dbf4ba5
8,462
cpp
C++
inference-engine/src/vpu/graph_transformer/src/stages/priorbox.cpp
zhoub/dldt
e42c01cf6e1d3aefa55e2c5df91f1054daddc575
[ "Apache-2.0" ]
3
2020-02-09T23:25:37.000Z
2021-01-19T09:44:12.000Z
inference-engine/src/vpu/graph_transformer/src/stages/priorbox.cpp
zhoub/dldt
e42c01cf6e1d3aefa55e2c5df91f1054daddc575
[ "Apache-2.0" ]
null
null
null
inference-engine/src/vpu/graph_transformer/src/stages/priorbox.cpp
zhoub/dldt
e42c01cf6e1d3aefa55e2c5df91f1054daddc575
[ "Apache-2.0" ]
2
2020-04-18T16:24:39.000Z
2021-01-19T09:42:19.000Z
// Copyright (C) 2018-2019 Intel Corporation // SPDX-License-Identifier: Apache-2.0 // #include <vpu/frontend/frontend.hpp> #include <cmath> #include <algorithm> #include <vector> #include <memory> #include <precision_utils.h> #include <ie_parallel.hpp> #include <vpu/utils/numeric.hpp> #include <vpu/utils/profiling.hpp> namespace vpu { namespace { class PriorBoxContent final : public CalculatedDataContent { public: PriorBoxContent( const DataDesc& inDesc0, const DataDesc& inDesc1, const DataDesc& outDesc, const ie::CNNLayerPtr& layer) : _inDesc0(inDesc0), _inDesc1(inDesc1), _outDesc(outDesc), _layer(layer) { IE_ASSERT(layer != nullptr); } protected: void fillTempBuf(const SmallVector<DataContent::Ptr, 2>&, void* tempBuf) const override { VPU_PROFILE(PriorBoxContent); auto tempPtr = static_cast<fp16_t*>(tempBuf); auto _min_sizes = _layer->GetParamAsFloats("min_size", {}); auto _max_sizes = _layer->GetParamAsFloats("max_size", {}); auto aspect_ratios = _layer->GetParamAsFloats("aspect_ratio"); auto _flip = static_cast<bool>(_layer->GetParamAsInt("flip")); auto _clip = static_cast<bool>(_layer->GetParamAsInt("clip")); auto _variance = _layer->GetParamAsFloats("variance"); auto _img_h = _layer->GetParamAsInt("img_h", 0); auto _img_w = _layer->GetParamAsInt("img_w", 0); auto _step = _layer->GetParamAsFloat("step", 0); auto _offset = _layer->GetParamAsFloat("offset", 0); auto _scale_all_sizes = static_cast<bool>(_layer->GetParamAsInt("scale_all_sizes", 1)); SmallVector<float> _aspect_ratios; _aspect_ratios.reserve(aspect_ratios.size() + 1); _aspect_ratios.push_back(1.0f); for (auto aspect_ratio : aspect_ratios) { bool exist = false; for (float _aspect_ratio : _aspect_ratios) { if (fabs(aspect_ratio - _aspect_ratio) < 1e-6) { exist = true; break; } } if (!exist) { _aspect_ratios.push_back(aspect_ratio); if (_flip) { if (isFloatEqual(aspect_ratio, 0.f)) { THROW_IE_EXCEPTION << "[VPU] PriorBox has 0.0 aspect ratio param in flip mode, " << " possible division by zero"; } _aspect_ratios.push_back(1.0f / aspect_ratio); } } } int _num_priors; if (_scale_all_sizes) { _num_priors = static_cast<int>(_aspect_ratios.size() * _min_sizes.size()); } else { _num_priors = static_cast<int>(_aspect_ratios.size() + _min_sizes.size() - 1); } for (auto it = _max_sizes.begin(); it != _max_sizes.end(); it++) { _num_priors += 1; } auto W = _inDesc0.dim(Dim::W); auto H = _inDesc0.dim(Dim::H); auto IW = _img_w == 0 ? _inDesc1.dim(Dim::W) : _img_w; auto IH = _img_h == 0 ? _inDesc1.dim(Dim::H) : _img_h; auto OW = (_outDesc.numDims() >= 4) ? _outDesc.dim(Dim::N) : 1; auto OH = _outDesc.dim(Dim::W); float step_x = 0.0f; float step_y = 0.0f; if (_step == 0) { step_x = static_cast<float>(IW) / W; step_y = static_cast<float>(IH) / H; } else { step_x = _step; step_y = _step; } auto dst_data = tempPtr; int dim = H * W * _num_priors * 4; float center_x = 0.0f; float center_y = 0.0f; float box_width; float box_height; if (_outDesc.dim(Dim::W) != dim || _outDesc.dim(Dim::H) != 2) { THROW_IE_EXCEPTION << "[VPU] PriorBox output have invalid dimension, exptected " << dim << "x2" << ", got " << _outDesc.dim(Dim::W) << "x" << _outDesc.dim(Dim::H) << ", layer name is: " << _layer->name; } int idx = 0; for (int h = 0; h < H; ++h) { for (int w = 0; w < W; ++w) { for (size_t msIdx = 0; msIdx < _min_sizes.size(); msIdx++) { if (_step == 0) { center_x = (w + 0.5f) * step_x; center_y = (h + 0.5f) * step_y; } else { center_x = (_offset + w) * _step; center_y = (_offset + h) * _step; } box_width = _min_sizes[msIdx]; box_height = _min_sizes[msIdx]; dst_data[idx++] = ie::PrecisionUtils::f32tof16((center_x - box_width / 2.0f) / IW); dst_data[idx++] = ie::PrecisionUtils::f32tof16((center_y - box_height / 2.0f) / IH); dst_data[idx++] = ie::PrecisionUtils::f32tof16((center_x + box_width / 2.0f) / IW); dst_data[idx++] = ie::PrecisionUtils::f32tof16((center_y + box_height / 2.0f) / IH); if (_max_sizes.size() > msIdx) { box_width = box_height = sqrt(_min_sizes[msIdx] * _max_sizes[msIdx]); dst_data[idx++] = ie::PrecisionUtils::f32tof16((center_x - box_width / 2.0f) / IW); dst_data[idx++] = ie::PrecisionUtils::f32tof16((center_y - box_height / 2.0f) / IH); dst_data[idx++] = ie::PrecisionUtils::f32tof16((center_x + box_width / 2.0f) / IW); dst_data[idx++] = ie::PrecisionUtils::f32tof16((center_y + box_height / 2.0f) / IH); } if (_scale_all_sizes || (!_scale_all_sizes && (msIdx == _min_sizes.size() - 1))) { size_t sIdx = _scale_all_sizes ? msIdx : 0; for (float ar : _aspect_ratios) { if (fabs(ar - 1.0f) < 1e-6) { continue; } box_width = _min_sizes[sIdx] * sqrt(ar); box_height = _min_sizes[sIdx] / sqrt(ar); dst_data[idx++] = ie::PrecisionUtils::f32tof16((center_x - box_width / 2.0f) / IW); dst_data[idx++] = ie::PrecisionUtils::f32tof16((center_y - box_height / 2.0f) / IH); dst_data[idx++] = ie::PrecisionUtils::f32tof16((center_x + box_width / 2.0f) / IW); dst_data[idx++] = ie::PrecisionUtils::f32tof16((center_y + box_height / 2.0f) / IH); } } } } } if (_clip) { for (int d = 0; d < dim; ++d) { dst_data[d] = (std::min)((std::max)(dst_data[d], ie::PrecisionUtils::f32tof16(0.0f)), ie::PrecisionUtils::f32tof16(1.0f)); } } int channel_size = OH * OW; dst_data += channel_size; if (_variance.size() == 1) { ie::parallel_for(channel_size, [&](int i) { dst_data[i] = ie::PrecisionUtils::f32tof16(_variance[0]); }); } else { ie::parallel_for4d(H, W, _num_priors, 4, [&](int h, int w, int i, int j) { dst_data[j + 4 * (i + _num_priors * (w + W * h))] = ie::PrecisionUtils::f32tof16(_variance[j]); }); } } private: DataDesc _inDesc0; DataDesc _inDesc1; DataDesc _outDesc; ie::CNNLayerPtr _layer; }; } // namespace void FrontEnd::parsePriorBox( const Model::Ptr& model, const ie::CNNLayerPtr& layer, const DataVector& inputs, const DataVector& outputs) { IE_ASSERT(inputs.size() == 2); IE_ASSERT(outputs.size() == 1); auto input0 = inputs[0]; auto input1 = inputs[1]; auto output = outputs[0]; auto resultData = model->addConstData( output->name(), output->desc(), std::make_shared<PriorBoxContent>(input0->desc(), input1->desc(), output->desc(), layer)); if (output->usage() == DataUsage::Output || output->numConsumers() > 0) { _stageBuilder->addCopyStage(model, layer->name, layer, resultData, output); } else { IE_ASSERT(output->usage() == DataUsage::Intermediate); bindData(resultData, output->origData()); } } } // namespace vpu
37.114035
138
0.518672
[ "vector", "model" ]
70c35be075a8f1b6fa1943ff3711058a33956cf8
13,712
cc
C++
mysql-server/unittest/gunit/innodb/lob/lob0int.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/unittest/gunit/innodb/lob/lob0int.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/unittest/gunit/innodb/lob/lob0int.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/***************************************************************************** Copyright (c) 2016, 2020, Oracle and/or its affiliates. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. 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, version 2.0, 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 "lob0int.h" #ifdef UNIV_DEBUG #define Fname(x) const char *fname = x; #define LOG(x) \ { std::cout << fname << ":" << x << std::endl; } #else #define Fname(x) #define LOG(x) #endif /* UNIV_DEBUG */ namespace lob { static buf_block_t *create_first_page() { Fname("lob::create_first_page"); /* Allocate the page. */ buf_block_t *block = btr_page_alloc(); base_node_page_t page(block); byte *free_list = page.free_list(); byte *index_list = page.index_list(); flst_init(index_list); flst_init(free_list); ulint node_count = page.node_count(); LOG("Number of LOB index entries = " << node_count); byte *cur = page.nodes_begin(); for (ulint i = 0; i < node_count; ++i) { flst_add_last(free_list, cur); cur += index_entry_t::SIZE; } ut_a(flst_validate(free_list)); return (block); } buf_block_t *base_node_page_t::alloc() { ut_ad(m_block == nullptr); m_block = create_first_page(); set_page_type(); set_next_page_null(); return (m_block); } /** Insert data in the middle of the given LOB page. @param[in] lob_page A large object page of type FIL_PAGE_TYPE_LOB_FIRST or FIL_PAGE_TYPE_LOB_DATA. @param[in] trxid The transaction identifier. @param[in] offset The given data must be inserted at this offset within the given page. @param[in] data The new data that needs to be inserted in the middle. @param[in] len The length of the new data in bytes. @param[out] new_block The new version of the page. We do copy-on-write. @return Saved data and its length. Some data from the current page that needs to be inserted at the end of the given new data. */ template <typename T> std::pair<ulint, byte *> insert_middle_page(T *lob_page, trx_id_t trxid, ulint offset, byte *&data, ulint &len, buf_block_t *&new_block); /** Insert data in the middle of the given LOB page. @param[in] trxid The transaction identifier. @param[in] offset The given data must be inserted at this offset within the given page. @param[in] data The new data that needs to be inserted in the middle. @param[in] len The length of the new data in bytes. @param[out] new_block The new version of the page. We do copy-on-write. @return Saved data and its length. Some data from the current page that needs to be inserted at the end of the given new data. */ std::pair<ulint, byte *> base_node_page_t::insert_middle( trx_id_t trxid, ulint offset, byte *&data, ulint &len, buf_block_t *&new_block) { ut_ad(trxid >= get_trx_id()); return (insert_middle_page(this, trxid, offset, data, len, new_block)); } /** Insert data in the middle of the given LOB page. @param[in] trxid The transaction identifier. @param[in] offset The given data must be inserted at this offset within the given page. @param[in] data The new data that needs to be inserted in the middle. @param[in] len The length of the new data in bytes. @param[out] new_block The new version of the page. We do copy-on-write. @return Saved data and its length. Some data from the current page that needs to be inserted at the end of the given new data. */ std::pair<ulint, byte *> data_page_t::insert_middle(trx_id_t trxid, ulint offset, byte *&data, ulint &len, buf_block_t *&new_block) { ut_ad(trxid >= get_trx_id()); return (insert_middle_page(this, trxid, offset, data, len, new_block)); } /** Insert data in the middle of an LOB. @param[in] lob_page A large object page of type FIL_PAGE_TYPE_LOB_FIRST or FIL_PAGE_TYPE_LOB_DATA. @param[in] trxid The transaction identifier. @param[in] offset The given data must be inserted at this offset. @param[in] data The new data that needs to be inserted in the middle. @param[in] len The length of the new data in bytes. @param[out] new_block The new version of the page. We do copy-on-write. @return Saved data and its length. Some data from the current page that needs to be inserted at the end of the given new data. */ template <typename T> std::pair<ulint, byte *> insert_middle_page(T *lob_page, trx_id_t trxid, ulint offset, byte *&data, ulint &len, buf_block_t *&new_block) { Fname("insert_middle_page"); ut_ad(trxid >= lob_page->get_trx_id()); std::pair<ulint, byte *> result(0, nullptr); ulint data_len = lob_page->get_data_len(); ulint save_len = data_len - offset; /* Don't modify existing page. Create new page. */ data_page_t page; new_block = page.alloc(); ulint avail = page.max_space_available(); byte *old_page_begin = lob_page->data_begin(); byte *new_page_begin = page.data_begin(); /* Copy the old data in the beginning. */ memcpy(new_page_begin, old_page_begin, offset); if (data_len + len <= avail) { /* Insert will complete within this page. */ /* Copy new data in middle. */ memcpy(new_page_begin + offset, data, len); /* Copy remaining old data in end. */ memcpy(new_page_begin + offset + len, old_page_begin + offset, save_len); ut_a((data_len + len) == (offset + len + save_len)); page.set_data_len(data_len + len); data += len; len = 0; } else { /* Will span multiple pages. */ /* Save the existing data that will be over-written. */ LOG("spanning multiple pages"); byte *from = lob_page->data_begin() + offset; byte *save_mem = new byte[save_len]; memcpy(save_mem, from, save_len); page.set_data_len(offset); /* Over-write the existing data with new data. */ page.append(trxid, data, len); /* There maybe some space left. */ result = std::pair<ulint, byte *>(save_len, save_mem); } return (result); } template <typename PageType> ulint append_page(PageType *page, trx_id_t trxid, byte *&data, ulint &len) { Fname("append_page"); LOG("Need to append bytes: " << len); ulint old_data_len = page->get_data_len(); byte *ptr = page->data_begin() + old_data_len; ulint space_available = page->max_space_available() - old_data_len; if (space_available == 0 || len == 0) { return (0); } ulint written = (len > space_available) ? space_available : len; memcpy(ptr, data, written); page->set_data_len(old_data_len + written); page->set_trx_id(trxid); data += written; len -= written; LOG("Written " << written << " bytes into page_no=" << page->get_page_no()); LOG("remaining=" << len); return (written); } ulint base_node_page_t::append(trx_id_t trxid, byte *&data, ulint &len) { return (append_page(this, trxid, data, len)); } ulint data_page_t::append(trx_id_t trxid, byte *&data, ulint &len) { return (append_page(this, trxid, data, len)); } template <typename PageType> buf_block_t *remove_middle_page(PageType *page, trx_id_t trxid, ulint offset, ulint &len) { buf_block_t *new_block = nullptr; /* Total data available in the given page. */ ulint data_len = page->get_data_len(); /* Data that can be removed from the given page. */ ulint can_be_removed = data_len - offset; /* Don't modify existing page. Create new page. */ data_page_t new_page; new_block = new_page.alloc(); byte *to = new_page.data_begin(); byte *from = page->data_begin(); /* Copy the beginning portion. */ if (offset > 0) { memcpy(to, from, offset); } if (len < can_be_removed) { /* Only a single page modification. */ to += offset; from += (offset + len); ulint trail = data_len - offset - len; /* Copy the end portion. */ memcpy(to, from, trail); new_page.set_data_len(data_len - len); len = 0; } else { new_page.set_data_len(data_len - can_be_removed); len -= can_be_removed; } return (new_block); } buf_block_t *base_node_page_t::remove_middle(trx_id_t trxid, ulint offset, ulint &len) { return (remove_middle_page(this, trxid, offset, len)); } buf_block_t *data_page_t::remove_middle(trx_id_t trxid, ulint offset, ulint &len) { return (remove_middle_page(this, trxid, offset, len)); } /** The current index entry points to a latest LOB page. It may or may not have older versions. If older version is there, bring it back to the index list from the versions list. Then remove the current entry from the index list. Move the versions list from current entry to older entry. @param[in] trxid The transaction identifier. @param[in] first_page The first lob page containing index list and free list. */ void index_entry_t::make_old_version_current(trx_id_t trxid, base_node_page_t &first_page) { flst_base_node_t *base = first_page.index_list(); flst_base_node_t *free_list = first_page.free_list(); flst_base_node_t *version_list = get_versions_ptr(); if (flst_get_len(version_list) > 0) { /* Remove the old version from versions list. */ fil_addr_t old_node_addr = flst_get_first(version_list); flst_node_t *old_node = fut_get_ptr(old_node_addr); flst_remove(version_list, old_node); /* Copy the version base node from current to old entry. */ index_entry_t old_entry(old_node); move_version_base_node(old_entry); flst_insert_before(base, old_node, m_node); } purge_version(trxid, base, free_list); ut_ad(flst_validate(base)); } /** Move the version base node from current entry to the given entry. @param[in] old_entry The index entry to which the version base node is moved to. */ void index_entry_t::move_version_base_node(index_entry_t &old_entry) { flst_base_node_t *from_node = get_versions_list(); flst_base_node_t *to_node = old_entry.get_versions_list(); memcpy(to_node, from_node, FLST_BASE_NODE_SIZE); ut_ad(flst_get_len(from_node) == flst_get_len(to_node)); flst_init(from_node); } /** Purge the current index entry. An index entry points to either a FIRST page or DATA page. That LOB page will be freed if it is DATA page. A FIRST page should not be freed. */ void index_entry_t::purge() { page_no_t page_no = get_page_no(); buf_block_t *block = buf_page_get(page_no); page_type_t type = fil_page_get_type(block->m_frame); if (type != FIL_PAGE_TYPE_LOB_FIRST) { btr_page_free(block); } set_prev_null(); set_next_null(); set_versions_null(); set_page_no(0); set_trx_id(0); set_data_len(0); } fil_addr_t index_entry_t::purge_version(trx_id_t trxid, flst_base_node_t *lst, flst_base_node_t *free_list) { /* Save the location of next node. */ fil_addr_t next_loc = flst_get_next_addr(m_node); /* Remove the current node from the list it belongs. */ flst_remove(lst, m_node); /* Purge the current node. */ purge(); /* Add the current node to the free list. */ flst_add_first(free_list, m_node); /* Return the next node location. */ return (next_loc); } buf_block_t *node_page_t::alloc(base_node_page_t &first_page) { /* Allocate the page. */ m_block = btr_page_alloc(); set_page_type(); set_next_page(first_page.get_next_page()); first_page.set_next_page(get_page_no()); /* Use fully for the LOB index contents */ ulint lob_metadata_len = payload(); ulint node_count = lob_metadata_len / index_entry_t::SIZE; flst_base_node_t *free_list = first_page.free_list(); byte *cur = nodes_begin(); for (ulint i = 0; i < node_count; ++i) { flst_add_last(free_list, cur); cur += index_entry_t::SIZE; } ut_a(flst_validate(free_list)); return (m_block); } /** Allocate one index entry. */ flst_node_t *base_node_page_t::alloc_index_entry() { flst_base_node_t *f_list = free_list(); fil_addr_t node_addr = flst_get_first(f_list); if (fil_addr_is_null(node_addr)) { node_page_t node_page; node_page.alloc(*this); node_addr = flst_get_first(f_list); } flst_node_t *node = fut_get_ptr(node_addr); flst_remove(f_list, node); return (node); } } // namespace lob
34.979592
78
0.665257
[ "object" ]
70ca364f2b588b9be802f07a76ab3e2d800d7dd8
3,640
cc
C++
src/compiler/codegen/codegen.cc
enderdzz/verona
e0cf0b4f9fb13a9f8787e60edb3f816863b94427
[ "MIT" ]
1
2020-01-21T05:04:26.000Z
2020-01-21T05:04:26.000Z
src/compiler/codegen/codegen.cc
enderdzz/verona
e0cf0b4f9fb13a9f8787e60edb3f816863b94427
[ "MIT" ]
null
null
null
src/compiler/codegen/codegen.cc
enderdzz/verona
e0cf0b4f9fb13a9f8787e60edb3f816863b94427
[ "MIT" ]
null
null
null
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. #include "compiler/codegen/codegen.h" #include "compiler/ast.h" #include "compiler/codegen/builtins.h" #include "compiler/codegen/descriptor.h" #include "compiler/codegen/function.h" #include "compiler/codegen/generator.h" #include "compiler/codegen/reachability.h" #include "compiler/instantiation.h" #include "compiler/resolution.h" #include "ds/helpers.h" #include "interpreter/bytecode.h" namespace verona::compiler { using bytecode::Opcode; using bytecode::SelectorIdx; bool is_valid_main_signature(Context& context, const FnSignature& signature) { return signature.generics->types.empty() && signature.receiver == nullptr && signature.types.arguments.empty() && signature.types.return_type == context.mk_unit(); } /** * Search for the program entrypoint and check it has the right signature. * * Returns nullopt and raises errors in the context if the entrypoint isn't * found or is invalid. */ std::optional<std::pair<CodegenItem<Entity>, CodegenItem<Method>>> find_entry(Context& context, const Program& program) { const Entity* main_class = program.find_entity("Main"); if (!main_class) { context.print_global_diagnostic( std::cerr, DiagnosticKind::Error, Diagnostic::NoMainClass); return std::nullopt; } if (main_class->kind->value() != Entity::Class) { context.print_diagnostic( std::cerr, main_class->name.source_range.first, DiagnosticKind::Error, Diagnostic::MainNotAClass); context.print_line_diagnostic(std::cerr, main_class->name.source_range); return std::nullopt; } if (!main_class->generics->types.empty()) { context.print_diagnostic( std::cerr, main_class->name.source_range.first, DiagnosticKind::Error, Diagnostic::MainClassIsGeneric); context.print_line_diagnostic(std::cerr, main_class->name.source_range); return std::nullopt; } const Method* main_method = lookup_member<Method>(main_class, "main"); if (!main_method) { context.print_diagnostic( std::cerr, main_class->name.source_range.first, DiagnosticKind::Error, Diagnostic::NoMainMethod); context.print_line_diagnostic(std::cerr, main_class->name.source_range); return std::nullopt; } if (!is_valid_main_signature(context, *main_method->signature)) { context.print_diagnostic( std::cerr, main_method->name.source_range.first, DiagnosticKind::Error, Diagnostic::InvalidMainSignature); context.print_line_diagnostic(std::cerr, main_method->name.source_range); return std::nullopt; } CodegenItem<Entity> class_item(main_class, Instantiation::empty()); CodegenItem<Method> method_item(main_method, Instantiation::empty()); return std::make_pair(class_item, method_item); } std::vector<uint8_t> codegen( Context& context, const Program& program, const AnalysisResults& analysis) { auto entry = find_entry(context, program); if (!entry) return {}; std::vector<uint8_t> code; Generator gen(code); Reachability reachability = compute_reachability( context, program, gen, entry->first, entry->second, analysis); SelectorTable selectors = SelectorTable::build(reachability); emit_program_header(program, reachability, selectors, gen, entry->first); emit_functions(context, analysis, reachability, selectors, gen); gen.finish(); return code; } }
31.111111
80
0.693132
[ "vector" ]
70d105255ce33d233c30b2f0d73de0afdb1531fd
5,422
cpp
C++
external/skia/gm/bitmapscroll.cpp
gordonjohnpatrick/XobotOS
888ed3b8cc8d8e0a54b1858bfa5a3572545f4d2f
[ "Apache-2.0" ]
263
2015-01-04T16:39:18.000Z
2022-01-05T17:52:38.000Z
external/skia/gm/bitmapscroll.cpp
DooMLoRD/XobotOS
f20db6295e878a2f298c5e3896528e240785805b
[ "Apache-2.0" ]
3
2015-09-06T09:06:39.000Z
2019-10-15T00:52:49.000Z
external/skia/gm/bitmapscroll.cpp
DooMLoRD/XobotOS
f20db6295e878a2f298c5e3896528e240785805b
[ "Apache-2.0" ]
105
2015-01-11T11:45:12.000Z
2022-02-22T07:26:36.000Z
/* * Copyright 2011 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "gm.h" namespace skiagm { /** Create a bitmap image suitable for testing SkBitmap::scrollRect(). * * @param quarterWidth bitmap will be 4x this many pixels wide * @param quarterHeight bitmap will be 4x this many pixels tall * @param bitmap the bitmap data is written into this object */ static void make_bitmap(int quarterWidth, int quarterHeight, SkBitmap *bitmap) { SkPaint pRed, pWhite, pGreen, pBlue, pLine, pAlphaGray; pRed.setColor(0xFFFF9999); pWhite.setColor(0xFFFFFFFF); pGreen.setColor(0xFF99FF99); pBlue.setColor(0xFF9999FF); pLine.setColor(0xFF000000); pLine.setStyle(SkPaint::kStroke_Style); pAlphaGray.setColor(0x66888888); // Prepare bitmap, and a canvas that draws into it. bitmap->reset(); bitmap->setConfig(SkBitmap::kARGB_8888_Config, quarterWidth*4, quarterHeight*4); bitmap->allocPixels(); SkCanvas canvas(*bitmap); SkScalar w = SkIntToScalar(quarterWidth); SkScalar h = SkIntToScalar(quarterHeight); canvas.drawRectCoords( 0, 0, w*2, h*2, pRed); canvas.drawRectCoords(w*2, 0, w*4, h*2, pGreen); canvas.drawRectCoords( 0, h*2, w*2, h*4, pBlue); canvas.drawRectCoords(w*2, h*2, w*4, h*4, pWhite); canvas.drawRectCoords(w, h, w*3, h*3, pAlphaGray); canvas.drawLine(w*2, 0, w*2, h*4, pLine); canvas.drawLine( 0, h*2, w*4, h*2, pLine); canvas.drawRectCoords(w, h, w*3, h*3, pLine); } class BitmapScrollGM : public GM { public: BitmapScrollGM() { // Create the original bitmap. make_bitmap(quarterWidth, quarterHeight, &origBitmap); this->setBGColor(0xFFDDDDDD); } protected: virtual SkString onShortName() { return SkString("bitmapscroll"); } virtual SkISize onISize() { return make_isize(800, 600); } virtual void onDraw(SkCanvas* canvas) { SkIRect scrollCenterRegion = SkIRect::MakeXYWH( quarterWidth, quarterHeight, quarterWidth*2+1, quarterHeight*2+1); int x = quarterWidth; int y = quarterHeight; int xSpacing = quarterWidth * 20; int ySpacing = quarterHeight * 16; // Draw left-hand text labels. drawLabel(canvas, "scroll entire bitmap", x, y, x, y + ySpacing); drawLabel(canvas, "scroll part of bitmap", x, y + ySpacing, x, y + ySpacing*2); x += 30; // Draw various permutations of scrolled bitmaps, scrolling a bit // further each time. draw9(canvas, x, y, NULL, quarterWidth*1/2, quarterHeight*1/2); draw9(canvas, x, y+ySpacing, &scrollCenterRegion, quarterWidth*1/2, quarterHeight*1/2); x += xSpacing; draw9(canvas, x, y, NULL, quarterWidth*3/2, quarterHeight*3/2); draw9(canvas, x, y+ySpacing, &scrollCenterRegion, quarterWidth*3/2, quarterHeight*3/2); x += xSpacing; draw9(canvas, x, y, NULL, quarterWidth*5/2, quarterHeight*5/2); draw9(canvas, x, y+ySpacing, &scrollCenterRegion, quarterWidth*5/2, quarterHeight*5/2); x += xSpacing; draw9(canvas, x, y, NULL, quarterWidth*9/2, quarterHeight*9/2); draw9(canvas, x, y+ySpacing, &scrollCenterRegion, quarterWidth*9/2, quarterHeight*9/2); } void drawLabel(SkCanvas* canvas, const char *text, int startX, int startY, int endX, int endY) { SkPaint paint; paint.setColor(0xFF000000); SkPath path; path.moveTo(SkIntToScalar(startX), SkIntToScalar(startY)); path.lineTo(SkIntToScalar(endX), SkIntToScalar(endY)); canvas->drawTextOnPath(text, strlen(text), path, NULL, paint); } /** Stamp out 9 copies of origBitmap, scrolled in each direction (and * not scrolled at all). */ void draw9(SkCanvas* canvas, int x, int y, SkIRect* subset, int scrollX, int scrollY) { for (int yMult=-1; yMult<=1; yMult++) { for (int xMult=-1; xMult<=1; xMult++) { // Figure out the (x,y) to draw this copy at SkScalar bitmapX = SkIntToScalar( x + quarterWidth * 5 * (xMult+1)); SkScalar bitmapY = SkIntToScalar( y + quarterHeight * 5 * (yMult+1)); // Scroll a new copy of the bitmap, and then draw it. // scrollRect() should always return true, even if it's a no-op SkBitmap scrolledBitmap; bool copyToReturnValue = origBitmap.copyTo( &scrolledBitmap, origBitmap.config()); SkASSERT(copyToReturnValue); bool scrollRectReturnValue = scrolledBitmap.scrollRect( subset, scrollX * xMult, scrollY * yMult); SkASSERT(scrollRectReturnValue); canvas->drawBitmap(scrolledBitmap, bitmapX, bitmapY); } } } private: typedef GM INHERITED; static const int quarterWidth = 10; static const int quarterHeight = 14; SkBitmap origBitmap; }; ////////////////////////////////////////////////////////////////////////////// static GM* MyFactory(void*) { return new BitmapScrollGM; } static GMRegistry reg(MyFactory); }
36.635135
80
0.607156
[ "object" ]
70d567c90575038e1b1ead97a319c26f703734ce
2,024
cpp
C++
src/ir/hlir/ops/k210/fake_kpu_conv2d.cpp
kartben/nncase
d2c7aa96035d48aa06ecd0af5496e019cc7124b8
[ "Apache-2.0" ]
1
2020-02-29T08:30:39.000Z
2020-02-29T08:30:39.000Z
src/ir/hlir/ops/k210/fake_kpu_conv2d.cpp
kartben/nncase
d2c7aa96035d48aa06ecd0af5496e019cc7124b8
[ "Apache-2.0" ]
null
null
null
src/ir/hlir/ops/k210/fake_kpu_conv2d.cpp
kartben/nncase
d2c7aa96035d48aa06ecd0af5496e019cc7124b8
[ "Apache-2.0" ]
null
null
null
/* Copyright 2019 Canaan Inc. * * 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 <hlir/op_utils.h> #include <hlir/ops/k210/fake_kpu_conv2d.h> #include <llir/ops/k210/fake_kpu_conv2d.h> #include <runtime/k210/k210_runtime_op_utility.h> using namespace nncase; using namespace nncase::hlir; using namespace nncase::hlir::k210; using namespace nncase::runtime::k210; fake_kpu_conv2d::fake_kpu_conv2d(shape_t input_shape, bool is_depthwise, runtime::k210::kpu_filter_type_t filter_type, runtime::k210::kpu_pool_type_t pool_type, xt::xtensor<float, 4> weights, xt::xtensor<float, 1> bias, xt::svector<runtime::k210::piecewise_linear_segment> fused_activation) : weights_(std::move(weights)), bias_(std::move(bias)), is_depthwise_(is_depthwise), filter_type_(filter_type), pool_type_(pool_type), fused_activation_(fused_activation) { add_input("input", dt_float32, input_shape); add_output("output", dt_float32, shape_t { input_shape[0], (size_t)output_channels(), (size_t)get_kpu_pool_output_size((int32_t)input_shape[2], pool_type_), (size_t)get_kpu_pool_output_size((int32_t)input_shape[3], pool_type_) }); } void fake_kpu_conv2d::compile(hlir_compile_context &context) { auto l_c = context.graph.emplace<llir::k210::fake_kpu_conv2d>(input().shape(), is_depthwise(), filter_type(), pool_type(), weights(), bias(), fused_activation()); context.add_input(input(), l_c->input()); context.add_output(output(), l_c->output()); }
47.069767
290
0.740613
[ "shape" ]
70d5b4e298cb638f77af58fe50e50ad7efb98995
6,346
hpp
C++
orbslam3_runner/src/system_ext.hpp
AaltoML/vio_benchmark
cb2277026f824f88f3bc131057ebc687cb19d648
[ "Apache-2.0" ]
32
2021-04-23T15:07:04.000Z
2022-03-30T08:04:28.000Z
orbslam3_runner/src/system_ext.hpp
AaltoML/vio_benchmark
cb2277026f824f88f3bc131057ebc687cb19d648
[ "Apache-2.0" ]
3
2021-02-10T18:54:06.000Z
2022-03-12T16:58:19.000Z
orbslam3_runner/src/system_ext.hpp
AaltoML/vio_benchmark
cb2277026f824f88f3bc131057ebc687cb19d648
[ "Apache-2.0" ]
4
2021-02-08T11:11:09.000Z
2022-03-15T12:45:05.000Z
/** * This file is part of ORB-SLAM3 * * Copyright (C) 2017-2020 Carlos Campos, Richard Elvira, Juan J. Gómez Rodríguez, José M.M. Montiel and Juan D. Tardós, University of Zaragoza. * Copyright (C) 2014-2016 Raúl Mur-Artal, José M.M. Montiel and Juan D. Tardós, University of Zaragoza. * * ORB-SLAM3 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. * * ORB-SLAM3 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 ORB-SLAM3. * If not, see <http://www.gnu.org/licenses/>. */ #include "System.h" #include "Converter.h" #include <thread> #include <pangolin/pangolin.h> #include <iomanip> // #include <openssl/md5.h> #include <boost/serialization/base_object.hpp> #include <boost/serialization/string.hpp> #include <boost/archive/text_iarchive.hpp> #include <boost/archive/text_oarchive.hpp> #include <boost/archive/binary_iarchive.hpp> #include <boost/archive/binary_oarchive.hpp> #include <boost/archive/xml_iarchive.hpp> #include <boost/archive/xml_oarchive.hpp> #include <functional> namespace ORB_SLAM3 { Verbose::eLevel Verbose::th = Verbose::VERBOSITY_NORMAL; class SystemExt : public System { public: using System::System; // Exports final estimated trajectory to the given function void ExportMap(std::function<void( double time, double posX, double posY, double posZ, double rotW, double rotX, double rotY, double rotZ )> onPose) { /*if(mSensor==MONOCULAR) { cerr << "ERROR: SaveTrajectoryEuRoC cannot be used for monocular." << endl; return; }*/ vector<Map*> vpMaps = mpAtlas->GetAllMaps(); Map* pBiggerMap; int numMaxKFs = 0; for(Map* pMap :vpMaps) { if(pMap->GetAllKeyFrames().size() > numMaxKFs) { numMaxKFs = pMap->GetAllKeyFrames().size(); pBiggerMap = pMap; } } vector<KeyFrame*> vpKFs = pBiggerMap->GetAllKeyFrames(); sort(vpKFs.begin(),vpKFs.end(),KeyFrame::lId); // Transform all keyframes so that the first keyframe is at the origin. // After a loop closure the first keyframe might not be at the origin. cv::Mat Twb; // Can be word to cam0 or world to b dependingo on IMU or not. if (mSensor==IMU_MONOCULAR || mSensor==IMU_STEREO) Twb = vpKFs[0]->GetImuPose(); else Twb = vpKFs[0]->GetPoseInverse(); // Frame pose is stored relative to its reference keyframe (which is optimized by BA and pose graph). // We need to get first the keyframe pose and then concatenate the relative transformation. // Frames not localized (tracking failure) are not saved. // For each frame we have a reference keyframe (lRit), the timestamp (lT) and a flag // which is true when tracking failed (lbL). list<ORB_SLAM3::KeyFrame*>::iterator lRit = mpTracker->mlpReferences.begin(); list<double>::iterator lT = mpTracker->mlFrameTimes.begin(); list<bool>::iterator lbL = mpTracker->mlbLost.begin(); //cout << "size mlpReferences: " << mpTracker->mlpReferences.size() << endl; //cout << "size mlRelativeFramePoses: " << mpTracker->mlRelativeFramePoses.size() << endl; //cout << "size mpTracker->mlFrameTimes: " << mpTracker->mlFrameTimes.size() << endl; //cout << "size mpTracker->mlbLost: " << mpTracker->mlbLost.size() << endl; for(list<cv::Mat>::iterator lit=mpTracker->mlRelativeFramePoses.begin(), lend=mpTracker->mlRelativeFramePoses.end();lit!=lend;lit++, lRit++, lT++, lbL++) { //cout << "1" << endl; if(*lbL) continue; KeyFrame* pKF = *lRit; //cout << "KF: " << pKF->mnId << endl; cv::Mat Trw = cv::Mat::eye(4,4,CV_32F); /*cout << "2" << endl; cout << "KF id: " << pKF->mnId << endl;*/ // If the reference keyframe was culled, traverse the spanning tree to get a suitable keyframe. if (!pKF) continue; //cout << "2.5" << endl; while(pKF->isBad()) { //cout << " 2.bad" << endl; Trw = Trw*pKF->mTcp; pKF = pKF->GetParent(); //cout << "--Parent KF: " << pKF->mnId << endl; } if(!pKF || pKF->GetMap() != pBiggerMap) { //cout << "--Parent KF is from another map" << endl; /*if(pKF) cout << "--Parent KF " << pKF->mnId << " is from another map " << pKF->GetMap()->GetId() << endl;*/ continue; } //cout << "3" << endl; Trw = Trw*pKF->GetPose()*Twb; // Tcp*Tpw*Twb0=Tcb0 where b0 is the new world reference // cout << "4" << endl; if (mSensor == IMU_MONOCULAR || mSensor == IMU_STEREO) { cv::Mat Tbw = pKF->mImuCalib.Tbc*(*lit)*Trw; cv::Mat Rwb = Tbw.rowRange(0,3).colRange(0,3).t(); cv::Mat twb = -Rwb*Tbw.rowRange(0,3).col(3); vector<float> q = Converter::toQuaternion(Rwb); onPose( *lT, twb.at<float>(0), twb.at<float>(1), twb.at<float>(2), q[3], q[0], q[1], q[2]); } else { cv::Mat Tcw = (*lit)*Trw; cv::Mat Rwc = Tcw.rowRange(0,3).colRange(0,3).t(); cv::Mat twc = -Rwc*Tcw.rowRange(0,3).col(3); vector<float> q = Converter::toQuaternion(Rwc); onPose( *lT, twc.at<float>(0), twc.at<float>(1), twc.at<float>(2), q[3], q[0], q[1], q[2]); } // cout << "5" << endl; } //cout << "end saving trajectory" << endl; } }; } // namespace
37.329412
143
0.566971
[ "vector", "transform" ]
70d6b2d0756a0cd3b7a1b991162516adeece1a1f
6,269
cc
C++
RecoTracker/TkMSParametrization/src/MSLayersAtAngle.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
RecoTracker/TkMSParametrization/src/MSLayersAtAngle.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
RecoTracker/TkMSParametrization/src/MSLayersAtAngle.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
#include "MSLayersAtAngle.h" #include "RecoTracker/TkMSParametrization/interface/PixelRecoLineRZ.h" #include "DataFormats/Math/interface/approx_log.h" using namespace std; namespace { template <class T> inline T sqr(T t) { return t * t; } } // namespace void MSLayersAtAngle::init() { std::sort(theLayers.begin(), theLayers.end()); int i = -1; indeces.clear(); for (auto const& l : theLayers) { ++i; int sq = l.seqNum(); if (sq < 0) continue; if (sq >= int(indeces.size())) indeces.resize(sq + 1, -1); indeces[sq] = i; } } //------------------------------------------------------------------------------ MSLayersAtAngle::MSLayersAtAngle(const vector<MSLayer>& layers) : theLayers(layers) { init(); } //------------------------------------------------------------------------------ const MSLayer* MSLayersAtAngle::findLayer(const MSLayer& layer) const { vector<MSLayer>::const_iterator it = find(theLayers.begin(), theLayers.end(), layer); return it == theLayers.end() ? nullptr : &(*it); } //------------------------------------------------------------------------------ void MSLayersAtAngle::update(const MSLayer& layer) { vector<MSLayer>::iterator it = find(theLayers.begin(), theLayers.end(), layer); if (it == theLayers.end()) { theLayers.push_back(layer); init(); } else { *it = layer; } } //------------------------------------------------------------------------------ float MSLayersAtAngle::sumX0D(const PixelRecoPointRZ& pointI, const PixelRecoPointRZ& pointO) const { LayerItr iO = findLayer(pointO, theLayers.begin(), theLayers.end()); // cout << "outer Layer: "<<*iO<<endl; LayerItr iI = findLayer(pointI, theLayers.begin(), iO); // cout << "inner Layer: "<<*iI<<endl; return sqrt(sum2RmRn(iI, iO, pointO.r(), SimpleLineRZ(pointI, pointO))); } float MSLayersAtAngle::sumX0D(int il, int ol, const PixelRecoPointRZ& pointI, const PixelRecoPointRZ& pointO) const { // if layer not at this angle (WHY???) revert to slow comp if (il >= int(indeces.size()) || ol >= int(indeces.size()) || indeces[il] < 0 || indeces[ol] < 0) return sumX0D(pointI, pointO); LayerItr iI = theLayers.begin() + indeces[il]; LayerItr iO = theLayers.begin() + indeces[ol]; return sqrt(sum2RmRn(iI, iO, pointO.r(), SimpleLineRZ(pointI, pointO))); } //------------------------------------------------------------------------------ static const bool doPrint = false; float MSLayersAtAngle::sumX0D(const PixelRecoPointRZ& pointI, const PixelRecoPointRZ& pointM, const PixelRecoPointRZ& pointO) const { LayerItr iO = findLayer(pointO, theLayers.begin(), theLayers.end()); LayerItr iI = findLayer(pointI, theLayers.begin(), iO); LayerItr iM = findLayer(pointM, iI, iO); float drOI = pointO.r() - pointI.r(); float drMO = pointO.r() - pointM.r(); float drMI = pointM.r() - pointI.r(); SimpleLineRZ line(pointI, pointO); float sum2I = sum2RmRn(iI + 1, iM, pointI.r(), line); float sum2O = sum2RmRn(iM, iO, pointO.r(), line); float sum = std::sqrt(sum2I * sqr(drMO) + sum2O * sqr(drMI)) / drOI; // if (iI!=theLayers.begin() ) // doPrint = ((*iM).seqNum()<0 || (*iO).seqNum()<0); if (doPrint) std::cout << "old " << (*iI).seqNum() << " " << iI - theLayers.begin() << ", " << (*iM).seqNum() << " " << iM - theLayers.begin() << ", " << (*iO).seqNum() << " " << iO - theLayers.begin() << " " << pointI.r() << " " << pointI.z() << " " << sum << std::endl; return sum; } float MSLayersAtAngle::sumX0D( float zV, int il, int ol, const PixelRecoPointRZ& pointI, const PixelRecoPointRZ& pointO) const { PixelRecoPointRZ pointV(0.f, zV); // if layer not at this angle (WHY???) revert to slow comp if (il >= int(indeces.size()) || ol >= int(indeces.size()) || indeces[il] < 0 || indeces[ol] < 0) return sumX0D(pointV, pointI, pointO); LayerItr iI = theLayers.begin() + indeces[il]; LayerItr iO = theLayers.begin() + indeces[ol]; float drOI = pointO.r(); float drMO = pointO.r() - pointI.r(); float drMI = pointI.r(); SimpleLineRZ line(pointV, pointO); float sum2I = sum2RmRn(theLayers.begin() + 1, iI, pointV.r(), line); float sum2O = sum2RmRn(iI, iO, pointO.r(), line); float sum = std::sqrt(sum2I * sqr(drMO) + sum2O * sqr(drMI)) / drOI; if (doPrint) std::cout << "new " << il << " " << (*iI).seqNum() << " " << iI - theLayers.begin() << ", " << ol << " " << (*iO).seqNum() << " " << iO - theLayers.begin() << " " << zV << " " << sum << std::endl; return sum; } //------------------------------------------------------------------------------ float MSLayersAtAngle::sum2RmRn(MSLayersAtAngle::LayerItr i1, MSLayersAtAngle::LayerItr i2, float rTarget, const SimpleLineRZ& line) const { float sum2 = 0.f; float cotTh = line.cotLine(); for (LayerItr it = i1; it < i2; it++) { std::pair<PixelRecoPointRZ, bool> cross = it->crossing(line); if (cross.second) { float x0 = it->x0(cotTh); float dr = rTarget - cross.first.r(); if (x0 > 1.e-5f) dr *= 1.f + 0.038f * unsafe_logf<2>(x0); sum2 += x0 * dr * dr; } // cout << *it << " crossing: "<<cross.second<<endl; } return sum2; } //------------------------------------------------------------------------------ MSLayersAtAngle::LayerItr MSLayersAtAngle::findLayer(const PixelRecoPointRZ& point, MSLayersAtAngle::LayerItr ibeg, MSLayersAtAngle::LayerItr iend) const { const float BIG = 99999.f; const float EPSILON = 1.e-8f; LayerItr theIt = ibeg; float dist = BIG; for (LayerItr it = ibeg; it < iend; it++) { float d = it->distance2(point); if (d < dist) { if (d < EPSILON) return it; dist = d; theIt = it; } } return theIt; } //------------------------------------------------------------------------------ void MSLayersAtAngle::print() const { for (LayerItr it = theLayers.begin(); it != theLayers.end(); it++) cout << *it << endl; }
35.822857
120
0.529271
[ "vector" ]
70d88ebf4116eec65f974986d8573243df2a8659
5,405
cpp
C++
src/mongo/db/update/addtoset_node.cpp
marcelodsx/mongo
324839c0c0c2b294a44d130105797ccdbb3b17a9
[ "Apache-2.0" ]
null
null
null
src/mongo/db/update/addtoset_node.cpp
marcelodsx/mongo
324839c0c0c2b294a44d130105797ccdbb3b17a9
[ "Apache-2.0" ]
null
null
null
src/mongo/db/update/addtoset_node.cpp
marcelodsx/mongo
324839c0c0c2b294a44d130105797ccdbb3b17a9
[ "Apache-2.0" ]
null
null
null
/** * Copyright (C) 2017 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #include "mongo/platform/basic.h" #include "mongo/db/update/addtoset_node.h" #include "mongo/bson/bsonelement_comparator.h" #include "mongo/db/query/collation/collator_interface.h" namespace mongo { namespace { /** * Deduplicates 'elements' using 'collator' for comparisons. */ void deduplicate(std::vector<BSONElement>& elements, const CollatorInterface* collator) { // Copy 'elements' into a new vector. std::vector<BSONElement> elementsCopy = elements; elements.clear(); // Keep track of which elements were already added. BSONElementSet added(collator); // Copy all non-duplicate elements back into 'elements'. Ensure that the original order of // elements is preserved. for (auto&& elem : elementsCopy) { if (added.find(elem) == added.end()) { elements.push_back(elem); } added.insert(elem); } } } // namespace Status AddToSetNode::init(BSONElement modExpr, const CollatorInterface* collator) { invariant(modExpr.ok()); bool isEach = false; // If the value of 'modExpr' is an object whose first field is '$each', treat it as an $each. if (modExpr.type() == BSONType::Object) { auto firstElement = modExpr.Obj().firstElement(); if (firstElement && firstElement.fieldNameStringData() == "$each") { isEach = true; if (firstElement.type() != BSONType::Array) { return Status( ErrorCodes::TypeMismatch, str::stream() << "The argument to $each in $addToSet must be an array but it was of type " << typeName(firstElement.type())); } if (modExpr.Obj().nFields() > 1) { return Status(ErrorCodes::BadValue, str::stream() << "Found unexpected fields after $each in $addToSet: " << modExpr.Obj()); } _elements = firstElement.Array(); } } // If the value of 'modExpr' was not an $each, we append the entire element. if (!isEach) { _elements.push_back(modExpr); } setCollator(collator); return Status::OK(); } void AddToSetNode::setCollator(const CollatorInterface* collator) { invariant(!_collator); _collator = collator; deduplicate(_elements, _collator); } bool AddToSetNode::updateExistingElement(mutablebson::Element* element) const { uassert(ErrorCodes::BadValue, str::stream() << "Cannot apply $addToSet to non-array field. Field named '" << element->getFieldName() << "' has non-array type " << typeName(element->getType()), element->getType() == BSONType::Array); // Find the set of elements that do not already exist in the array 'element'. std::vector<BSONElement> elementsToAdd; for (auto&& elem : _elements) { auto shouldAdd = true; for (auto existingElem = element->leftChild(); existingElem.ok(); existingElem = existingElem.rightSibling()) { if (existingElem.compareWithBSONElement(elem, _collator, false) == 0) { shouldAdd = false; break; } } if (shouldAdd) { elementsToAdd.push_back(elem); } } if (elementsToAdd.empty()) { return false; } for (auto&& elem : elementsToAdd) { auto toAdd = element->getDocument().makeElement(elem); invariantOK(element->pushBack(toAdd)); } return true; } void AddToSetNode::setValueForNewElement(mutablebson::Element* element) const { BSONObj emptyArray; invariantOK(element->setValueArray(emptyArray)); for (auto&& elem : _elements) { auto toAdd = element->getDocument().makeElement(elem); invariantOK(element->pushBack(toAdd)); } } } // namespace mongo
35.794702
100
0.638668
[ "object", "vector" ]
70d9601cd0f9be78570cabab1ce23d7b6413917e
47,303
cc
C++
base/tracked_objects_unittest.cc
xzhan96/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
41
2017-04-19T19:38:10.000Z
2021-09-07T02:40:27.000Z
base/tracked_objects_unittest.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
8
2017-04-21T16:40:09.000Z
2019-12-09T19:48:40.000Z
base/tracked_objects_unittest.cc
emilio/chromium.src
1bd0cf3997f947746c0fc5406a2466e7b5f6159e
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
19
2017-04-24T14:43:18.000Z
2022-03-17T19:13:45.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Test of classes in the tracked_objects.h classes. #include "base/tracked_objects.h" #include <stddef.h> #include <stdint.h> #include <memory> #include "base/process/process_handle.h" #include "base/time/time.h" #include "base/tracking_info.h" #include "testing/gtest/include/gtest/gtest.h" const int kLineNumber = 1776; const char kFile[] = "FixedUnitTestFileName"; const char kWorkerThreadName[] = "WorkerThread-1"; const char kMainThreadName[] = "SomeMainThreadName"; const char kStillAlive[] = "Still_Alive"; namespace tracked_objects { class TrackedObjectsTest : public testing::Test { protected: TrackedObjectsTest() { // On entry, leak any database structures in case they are still in use by // prior threads. ThreadData::ShutdownSingleThreadedCleanup(true); test_time_ = 0; ThreadData::now_function_for_testing_ = &TrackedObjectsTest::GetTestTime; } ~TrackedObjectsTest() override { // We should not need to leak any structures we create, since we are // single threaded, and carefully accounting for items. ThreadData::ShutdownSingleThreadedCleanup(false); } // Reset the profiler state. void Reset() { ThreadData::ShutdownSingleThreadedCleanup(false); test_time_ = 0; } // Simulate a birth on the thread named |thread_name|, at the given // |location|. void TallyABirth(const Location& location, const std::string& thread_name) { // If the |thread_name| is empty, we don't initialize system with a thread // name, so we're viewed as a worker thread. if (!thread_name.empty()) ThreadData::InitializeThreadContext(kMainThreadName); // Do not delete |birth|. We don't own it. Births* birth = ThreadData::TallyABirthIfActive(location); if (ThreadData::status() == ThreadData::DEACTIVATED) EXPECT_EQ(reinterpret_cast<Births*>(NULL), birth); else EXPECT_NE(reinterpret_cast<Births*>(NULL), birth); } // Helper function to verify the most common test expectations. void ExpectSimpleProcessData(const ProcessDataSnapshot& process_data, const std::string& function_name, const std::string& birth_thread, const std::string& death_thread, int count, int run_ms, int queue_ms) { ASSERT_EQ(1u, process_data.phased_snapshots.size()); auto it = process_data.phased_snapshots.find(0); ASSERT_TRUE(it != process_data.phased_snapshots.end()); const ProcessDataPhaseSnapshot& process_data_phase = it->second; ASSERT_EQ(1u, process_data_phase.tasks.size()); EXPECT_EQ(kFile, process_data_phase.tasks[0].birth.location.file_name); EXPECT_EQ(function_name, process_data_phase.tasks[0].birth.location.function_name); EXPECT_EQ(kLineNumber, process_data_phase.tasks[0].birth.location.line_number); EXPECT_EQ(birth_thread, process_data_phase.tasks[0].birth.thread_name); EXPECT_EQ(count, process_data_phase.tasks[0].death_data.count); EXPECT_EQ(count * run_ms, process_data_phase.tasks[0].death_data.run_duration_sum); EXPECT_EQ(run_ms, process_data_phase.tasks[0].death_data.run_duration_max); EXPECT_EQ(run_ms, process_data_phase.tasks[0].death_data.run_duration_sample); EXPECT_EQ(count * queue_ms, process_data_phase.tasks[0].death_data.queue_duration_sum); EXPECT_EQ(queue_ms, process_data_phase.tasks[0].death_data.queue_duration_max); EXPECT_EQ(queue_ms, process_data_phase.tasks[0].death_data.queue_duration_sample); EXPECT_EQ(death_thread, process_data_phase.tasks[0].death_thread_name); EXPECT_EQ(base::GetCurrentProcId(), process_data.process_id); } // Sets time that will be returned by ThreadData::Now(). static void SetTestTime(unsigned int test_time) { test_time_ = test_time; } private: // Returns test time in milliseconds. static unsigned int GetTestTime() { return test_time_; } // Test time in milliseconds. static unsigned int test_time_; }; // static unsigned int TrackedObjectsTest::test_time_; TEST_F(TrackedObjectsTest, TaskStopwatchNoStartStop) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); // Check that creating and destroying a stopwatch without starting it doesn't // crash. TaskStopwatch stopwatch; } TEST_F(TrackedObjectsTest, MinimalStartupShutdown) { // Minimal test doesn't even create any tasks. ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); EXPECT_FALSE(ThreadData::first()); // No activity even on this thread. ThreadData* data = ThreadData::Get(); EXPECT_TRUE(ThreadData::first()); // Now class was constructed. ASSERT_TRUE(data); EXPECT_FALSE(data->next()); EXPECT_EQ(data, ThreadData::Get()); ThreadData::BirthMap birth_map; ThreadData::DeathsSnapshot deaths; data->SnapshotMaps(0, &birth_map, &deaths); EXPECT_EQ(0u, birth_map.size()); EXPECT_EQ(0u, deaths.size()); // Clean up with no leaking. Reset(); // Do it again, just to be sure we reset state completely. ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); EXPECT_FALSE(ThreadData::first()); // No activity even on this thread. data = ThreadData::Get(); EXPECT_TRUE(ThreadData::first()); // Now class was constructed. ASSERT_TRUE(data); EXPECT_FALSE(data->next()); EXPECT_EQ(data, ThreadData::Get()); birth_map.clear(); deaths.clear(); data->SnapshotMaps(0, &birth_map, &deaths); EXPECT_EQ(0u, birth_map.size()); EXPECT_EQ(0u, deaths.size()); } TEST_F(TrackedObjectsTest, TinyStartupShutdown) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); // Instigate tracking on a single tracked object, on our thread. const char kFunction[] = "TinyStartupShutdown"; Location location(kFunction, kFile, kLineNumber, NULL); ThreadData::TallyABirthIfActive(location); ThreadData* data = ThreadData::first(); ASSERT_TRUE(data); EXPECT_FALSE(data->next()); EXPECT_EQ(data, ThreadData::Get()); ThreadData::BirthMap birth_map; ThreadData::DeathsSnapshot deaths; data->SnapshotMaps(0, &birth_map, &deaths); EXPECT_EQ(1u, birth_map.size()); // 1 birth location. EXPECT_EQ(1, birth_map.begin()->second->birth_count()); // 1 birth. EXPECT_EQ(0u, deaths.size()); // No deaths. // Now instigate another birth, while we are timing the run of the first // execution. // Create a child (using the same birth location). // TrackingInfo will call TallyABirth() during construction. const int32_t start_time = 1; base::TimeTicks kBogusBirthTime = base::TimeTicks() + base::TimeDelta::FromMilliseconds(start_time); base::TrackingInfo pending_task(location, kBogusBirthTime); SetTestTime(1); TaskStopwatch stopwatch; stopwatch.Start(); // Finally conclude the outer run. const int32_t time_elapsed = 1000; SetTestTime(start_time + time_elapsed); stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task, stopwatch); birth_map.clear(); deaths.clear(); data->SnapshotMaps(0, &birth_map, &deaths); EXPECT_EQ(1u, birth_map.size()); // 1 birth location. EXPECT_EQ(2, birth_map.begin()->second->birth_count()); // 2 births. EXPECT_EQ(1u, deaths.size()); // 1 location. EXPECT_EQ(1, deaths.begin()->second.death_data.count); // 1 death. // The births were at the same location as the one known death. EXPECT_EQ(birth_map.begin()->second, deaths.begin()->first); ProcessDataSnapshot process_data; ThreadData::Snapshot(0, &process_data); ASSERT_EQ(1u, process_data.phased_snapshots.size()); auto it = process_data.phased_snapshots.find(0); ASSERT_TRUE(it != process_data.phased_snapshots.end()); const ProcessDataPhaseSnapshot& process_data_phase = it->second; ASSERT_EQ(1u, process_data_phase.tasks.size()); EXPECT_EQ(kFile, process_data_phase.tasks[0].birth.location.file_name); EXPECT_EQ(kFunction, process_data_phase.tasks[0].birth.location.function_name); EXPECT_EQ(kLineNumber, process_data_phase.tasks[0].birth.location.line_number); EXPECT_EQ(kWorkerThreadName, process_data_phase.tasks[0].birth.thread_name); EXPECT_EQ(1, process_data_phase.tasks[0].death_data.count); EXPECT_EQ(time_elapsed, process_data_phase.tasks[0].death_data.run_duration_sum); EXPECT_EQ(time_elapsed, process_data_phase.tasks[0].death_data.run_duration_max); EXPECT_EQ(time_elapsed, process_data_phase.tasks[0].death_data.run_duration_sample); EXPECT_EQ(0, process_data_phase.tasks[0].death_data.queue_duration_sum); EXPECT_EQ(0, process_data_phase.tasks[0].death_data.queue_duration_max); EXPECT_EQ(0, process_data_phase.tasks[0].death_data.queue_duration_sample); EXPECT_EQ(kWorkerThreadName, process_data_phase.tasks[0].death_thread_name); } TEST_F(TrackedObjectsTest, DeathDataTestRecordDeath) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); std::unique_ptr<DeathData> data(new DeathData()); ASSERT_NE(data, nullptr); EXPECT_EQ(data->run_duration_sum(), 0); EXPECT_EQ(data->run_duration_max(), 0); EXPECT_EQ(data->run_duration_sample(), 0); EXPECT_EQ(data->queue_duration_sum(), 0); EXPECT_EQ(data->queue_duration_max(), 0); EXPECT_EQ(data->queue_duration_sample(), 0); EXPECT_EQ(data->count(), 0); EXPECT_EQ(nullptr, data->last_phase_snapshot()); int32_t run_ms = 42; int32_t queue_ms = 8; const int kUnrandomInt = 0; // Fake random int that ensure we sample data. data->RecordDeath(queue_ms, run_ms, kUnrandomInt); EXPECT_EQ(data->run_duration_sum(), run_ms); EXPECT_EQ(data->run_duration_max(), run_ms); EXPECT_EQ(data->run_duration_sample(), run_ms); EXPECT_EQ(data->queue_duration_sum(), queue_ms); EXPECT_EQ(data->queue_duration_max(), queue_ms); EXPECT_EQ(data->queue_duration_sample(), queue_ms); EXPECT_EQ(data->count(), 1); EXPECT_EQ(nullptr, data->last_phase_snapshot()); data->RecordDeath(queue_ms, run_ms, kUnrandomInt); EXPECT_EQ(data->run_duration_sum(), run_ms + run_ms); EXPECT_EQ(data->run_duration_max(), run_ms); EXPECT_EQ(data->run_duration_sample(), run_ms); EXPECT_EQ(data->queue_duration_sum(), queue_ms + queue_ms); EXPECT_EQ(data->queue_duration_max(), queue_ms); EXPECT_EQ(data->queue_duration_sample(), queue_ms); EXPECT_EQ(data->count(), 2); EXPECT_EQ(nullptr, data->last_phase_snapshot()); } TEST_F(TrackedObjectsTest, DeathDataTest2Phases) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); std::unique_ptr<DeathData> data(new DeathData()); ASSERT_NE(data, nullptr); int32_t run_ms = 42; int32_t queue_ms = 8; const int kUnrandomInt = 0; // Fake random int that ensure we sample data. data->RecordDeath(queue_ms, run_ms, kUnrandomInt); data->RecordDeath(queue_ms, run_ms, kUnrandomInt); data->OnProfilingPhaseCompleted(123); EXPECT_EQ(data->run_duration_sum(), run_ms + run_ms); EXPECT_EQ(data->run_duration_max(), 0); EXPECT_EQ(data->run_duration_sample(), run_ms); EXPECT_EQ(data->queue_duration_sum(), queue_ms + queue_ms); EXPECT_EQ(data->queue_duration_max(), 0); EXPECT_EQ(data->queue_duration_sample(), queue_ms); EXPECT_EQ(data->count(), 2); ASSERT_NE(nullptr, data->last_phase_snapshot()); EXPECT_EQ(123, data->last_phase_snapshot()->profiling_phase); EXPECT_EQ(2, data->last_phase_snapshot()->death_data.count); EXPECT_EQ(2 * run_ms, data->last_phase_snapshot()->death_data.run_duration_sum); EXPECT_EQ(run_ms, data->last_phase_snapshot()->death_data.run_duration_max); EXPECT_EQ(run_ms, data->last_phase_snapshot()->death_data.run_duration_sample); EXPECT_EQ(2 * queue_ms, data->last_phase_snapshot()->death_data.queue_duration_sum); EXPECT_EQ(queue_ms, data->last_phase_snapshot()->death_data.queue_duration_max); EXPECT_EQ(queue_ms, data->last_phase_snapshot()->death_data.queue_duration_sample); EXPECT_EQ(nullptr, data->last_phase_snapshot()->prev); int32_t run_ms1 = 21; int32_t queue_ms1 = 4; data->RecordDeath(queue_ms1, run_ms1, kUnrandomInt); EXPECT_EQ(data->run_duration_sum(), run_ms + run_ms + run_ms1); EXPECT_EQ(data->run_duration_max(), run_ms1); EXPECT_EQ(data->run_duration_sample(), run_ms1); EXPECT_EQ(data->queue_duration_sum(), queue_ms + queue_ms + queue_ms1); EXPECT_EQ(data->queue_duration_max(), queue_ms1); EXPECT_EQ(data->queue_duration_sample(), queue_ms1); EXPECT_EQ(data->count(), 3); ASSERT_NE(nullptr, data->last_phase_snapshot()); EXPECT_EQ(123, data->last_phase_snapshot()->profiling_phase); EXPECT_EQ(2, data->last_phase_snapshot()->death_data.count); EXPECT_EQ(2 * run_ms, data->last_phase_snapshot()->death_data.run_duration_sum); EXPECT_EQ(run_ms, data->last_phase_snapshot()->death_data.run_duration_max); EXPECT_EQ(run_ms, data->last_phase_snapshot()->death_data.run_duration_sample); EXPECT_EQ(2 * queue_ms, data->last_phase_snapshot()->death_data.queue_duration_sum); EXPECT_EQ(queue_ms, data->last_phase_snapshot()->death_data.queue_duration_max); EXPECT_EQ(queue_ms, data->last_phase_snapshot()->death_data.queue_duration_sample); EXPECT_EQ(nullptr, data->last_phase_snapshot()->prev); } TEST_F(TrackedObjectsTest, Delta) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); DeathDataSnapshot snapshot; snapshot.count = 10; snapshot.run_duration_sum = 100; snapshot.run_duration_max = 50; snapshot.run_duration_sample = 25; snapshot.queue_duration_sum = 200; snapshot.queue_duration_max = 101; snapshot.queue_duration_sample = 26; DeathDataSnapshot older_snapshot; older_snapshot.count = 2; older_snapshot.run_duration_sum = 95; older_snapshot.run_duration_max = 48; older_snapshot.run_duration_sample = 22; older_snapshot.queue_duration_sum = 190; older_snapshot.queue_duration_max = 99; older_snapshot.queue_duration_sample = 21; const DeathDataSnapshot& delta = snapshot.Delta(older_snapshot); EXPECT_EQ(8, delta.count); EXPECT_EQ(5, delta.run_duration_sum); EXPECT_EQ(50, delta.run_duration_max); EXPECT_EQ(25, delta.run_duration_sample); EXPECT_EQ(10, delta.queue_duration_sum); EXPECT_EQ(101, delta.queue_duration_max); EXPECT_EQ(26, delta.queue_duration_sample); } TEST_F(TrackedObjectsTest, DeactivatedBirthOnlyToSnapshotWorkerThread) { // Start in the deactivated state. ThreadData::InitializeAndSetTrackingStatus(ThreadData::DEACTIVATED); const char kFunction[] = "DeactivatedBirthOnlyToSnapshotWorkerThread"; Location location(kFunction, kFile, kLineNumber, NULL); TallyABirth(location, std::string()); ProcessDataSnapshot process_data; ThreadData::Snapshot(0, &process_data); ASSERT_EQ(1u, process_data.phased_snapshots.size()); auto it = process_data.phased_snapshots.find(0); ASSERT_TRUE(it != process_data.phased_snapshots.end()); const ProcessDataPhaseSnapshot& process_data_phase = it->second; ASSERT_EQ(0u, process_data_phase.tasks.size()); EXPECT_EQ(base::GetCurrentProcId(), process_data.process_id); } TEST_F(TrackedObjectsTest, DeactivatedBirthOnlyToSnapshotMainThread) { // Start in the deactivated state. ThreadData::InitializeAndSetTrackingStatus(ThreadData::DEACTIVATED); const char kFunction[] = "DeactivatedBirthOnlyToSnapshotMainThread"; Location location(kFunction, kFile, kLineNumber, NULL); TallyABirth(location, kMainThreadName); ProcessDataSnapshot process_data; ThreadData::Snapshot(0, &process_data); ASSERT_EQ(1u, process_data.phased_snapshots.size()); auto it = process_data.phased_snapshots.find(0); ASSERT_TRUE(it != process_data.phased_snapshots.end()); const ProcessDataPhaseSnapshot& process_data_phase = it->second; ASSERT_EQ(0u, process_data_phase.tasks.size()); EXPECT_EQ(base::GetCurrentProcId(), process_data.process_id); } TEST_F(TrackedObjectsTest, BirthOnlyToSnapshotWorkerThread) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); const char kFunction[] = "BirthOnlyToSnapshotWorkerThread"; Location location(kFunction, kFile, kLineNumber, NULL); TallyABirth(location, std::string()); ProcessDataSnapshot process_data; ThreadData::Snapshot(0, &process_data); ExpectSimpleProcessData(process_data, kFunction, kWorkerThreadName, kStillAlive, 1, 0, 0); } TEST_F(TrackedObjectsTest, BirthOnlyToSnapshotMainThread) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); const char kFunction[] = "BirthOnlyToSnapshotMainThread"; Location location(kFunction, kFile, kLineNumber, NULL); TallyABirth(location, kMainThreadName); ProcessDataSnapshot process_data; ThreadData::Snapshot(0, &process_data); ExpectSimpleProcessData(process_data, kFunction, kMainThreadName, kStillAlive, 1, 0, 0); } TEST_F(TrackedObjectsTest, LifeCycleToSnapshotMainThread) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); const char kFunction[] = "LifeCycleToSnapshotMainThread"; Location location(kFunction, kFile, kLineNumber, NULL); TallyABirth(location, kMainThreadName); const TrackedTime kTimePosted = TrackedTime::FromMilliseconds(1); const base::TimeTicks kDelayedStartTime = base::TimeTicks(); // TrackingInfo will call TallyABirth() during construction. base::TrackingInfo pending_task(location, kDelayedStartTime); pending_task.time_posted = kTimePosted; // Overwrite implied Now(). const unsigned int kStartOfRun = 5; const unsigned int kEndOfRun = 7; SetTestTime(kStartOfRun); TaskStopwatch stopwatch; stopwatch.Start(); SetTestTime(kEndOfRun); stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task, stopwatch); ProcessDataSnapshot process_data; ThreadData::Snapshot(0, &process_data); ExpectSimpleProcessData(process_data, kFunction, kMainThreadName, kMainThreadName, 1, 2, 4); } TEST_F(TrackedObjectsTest, TwoPhases) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); const char kFunction[] = "TwoPhases"; Location location(kFunction, kFile, kLineNumber, NULL); TallyABirth(location, kMainThreadName); const TrackedTime kTimePosted = TrackedTime::FromMilliseconds(1); const base::TimeTicks kDelayedStartTime = base::TimeTicks(); // TrackingInfo will call TallyABirth() during construction. base::TrackingInfo pending_task(location, kDelayedStartTime); pending_task.time_posted = kTimePosted; // Overwrite implied Now(). const unsigned int kStartOfRun = 5; const unsigned int kEndOfRun = 7; SetTestTime(kStartOfRun); TaskStopwatch stopwatch; stopwatch.Start(); SetTestTime(kEndOfRun); stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task, stopwatch); ThreadData::OnProfilingPhaseCompleted(0); TallyABirth(location, kMainThreadName); const TrackedTime kTimePosted1 = TrackedTime::FromMilliseconds(9); const base::TimeTicks kDelayedStartTime1 = base::TimeTicks(); // TrackingInfo will call TallyABirth() during construction. base::TrackingInfo pending_task1(location, kDelayedStartTime1); pending_task1.time_posted = kTimePosted1; // Overwrite implied Now(). const unsigned int kStartOfRun1 = 11; const unsigned int kEndOfRun1 = 21; SetTestTime(kStartOfRun1); TaskStopwatch stopwatch1; stopwatch1.Start(); SetTestTime(kEndOfRun1); stopwatch1.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task1, stopwatch1); ProcessDataSnapshot process_data; ThreadData::Snapshot(1, &process_data); ASSERT_EQ(2u, process_data.phased_snapshots.size()); auto it0 = process_data.phased_snapshots.find(0); ASSERT_TRUE(it0 != process_data.phased_snapshots.end()); const ProcessDataPhaseSnapshot& process_data_phase0 = it0->second; ASSERT_EQ(1u, process_data_phase0.tasks.size()); EXPECT_EQ(kFile, process_data_phase0.tasks[0].birth.location.file_name); EXPECT_EQ(kFunction, process_data_phase0.tasks[0].birth.location.function_name); EXPECT_EQ(kLineNumber, process_data_phase0.tasks[0].birth.location.line_number); EXPECT_EQ(kMainThreadName, process_data_phase0.tasks[0].birth.thread_name); EXPECT_EQ(1, process_data_phase0.tasks[0].death_data.count); EXPECT_EQ(2, process_data_phase0.tasks[0].death_data.run_duration_sum); EXPECT_EQ(2, process_data_phase0.tasks[0].death_data.run_duration_max); EXPECT_EQ(2, process_data_phase0.tasks[0].death_data.run_duration_sample); EXPECT_EQ(4, process_data_phase0.tasks[0].death_data.queue_duration_sum); EXPECT_EQ(4, process_data_phase0.tasks[0].death_data.queue_duration_max); EXPECT_EQ(4, process_data_phase0.tasks[0].death_data.queue_duration_sample); EXPECT_EQ(kMainThreadName, process_data_phase0.tasks[0].death_thread_name); auto it1 = process_data.phased_snapshots.find(1); ASSERT_TRUE(it1 != process_data.phased_snapshots.end()); const ProcessDataPhaseSnapshot& process_data_phase1 = it1->second; ASSERT_EQ(1u, process_data_phase1.tasks.size()); EXPECT_EQ(kFile, process_data_phase1.tasks[0].birth.location.file_name); EXPECT_EQ(kFunction, process_data_phase1.tasks[0].birth.location.function_name); EXPECT_EQ(kLineNumber, process_data_phase1.tasks[0].birth.location.line_number); EXPECT_EQ(kMainThreadName, process_data_phase1.tasks[0].birth.thread_name); EXPECT_EQ(1, process_data_phase1.tasks[0].death_data.count); EXPECT_EQ(10, process_data_phase1.tasks[0].death_data.run_duration_sum); EXPECT_EQ(10, process_data_phase1.tasks[0].death_data.run_duration_max); EXPECT_EQ(10, process_data_phase1.tasks[0].death_data.run_duration_sample); EXPECT_EQ(2, process_data_phase1.tasks[0].death_data.queue_duration_sum); EXPECT_EQ(2, process_data_phase1.tasks[0].death_data.queue_duration_max); EXPECT_EQ(2, process_data_phase1.tasks[0].death_data.queue_duration_sample); EXPECT_EQ(kMainThreadName, process_data_phase1.tasks[0].death_thread_name); EXPECT_EQ(base::GetCurrentProcId(), process_data.process_id); } TEST_F(TrackedObjectsTest, ThreePhases) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); const char kFunction[] = "ThreePhases"; Location location(kFunction, kFile, kLineNumber, NULL); // Phase 0 { TallyABirth(location, kMainThreadName); // TrackingInfo will call TallyABirth() during construction. SetTestTime(10); base::TrackingInfo pending_task(location, base::TimeTicks()); SetTestTime(17); TaskStopwatch stopwatch; stopwatch.Start(); SetTestTime(23); stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task, stopwatch); } ThreadData::OnProfilingPhaseCompleted(0); // Phase 1 { TallyABirth(location, kMainThreadName); SetTestTime(30); base::TrackingInfo pending_task(location, base::TimeTicks()); SetTestTime(35); TaskStopwatch stopwatch; stopwatch.Start(); SetTestTime(39); stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task, stopwatch); } ThreadData::OnProfilingPhaseCompleted(1); // Phase 2 { TallyABirth(location, kMainThreadName); // TrackingInfo will call TallyABirth() during construction. SetTestTime(40); base::TrackingInfo pending_task(location, base::TimeTicks()); SetTestTime(43); TaskStopwatch stopwatch; stopwatch.Start(); SetTestTime(45); stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task, stopwatch); } // Snapshot and check results. ProcessDataSnapshot process_data; ThreadData::Snapshot(2, &process_data); ASSERT_EQ(3u, process_data.phased_snapshots.size()); auto it0 = process_data.phased_snapshots.find(0); ASSERT_TRUE(it0 != process_data.phased_snapshots.end()); const ProcessDataPhaseSnapshot& process_data_phase0 = it0->second; ASSERT_EQ(1u, process_data_phase0.tasks.size()); EXPECT_EQ(kFile, process_data_phase0.tasks[0].birth.location.file_name); EXPECT_EQ(kFunction, process_data_phase0.tasks[0].birth.location.function_name); EXPECT_EQ(kLineNumber, process_data_phase0.tasks[0].birth.location.line_number); EXPECT_EQ(kMainThreadName, process_data_phase0.tasks[0].birth.thread_name); EXPECT_EQ(1, process_data_phase0.tasks[0].death_data.count); EXPECT_EQ(6, process_data_phase0.tasks[0].death_data.run_duration_sum); EXPECT_EQ(6, process_data_phase0.tasks[0].death_data.run_duration_max); EXPECT_EQ(6, process_data_phase0.tasks[0].death_data.run_duration_sample); EXPECT_EQ(7, process_data_phase0.tasks[0].death_data.queue_duration_sum); EXPECT_EQ(7, process_data_phase0.tasks[0].death_data.queue_duration_max); EXPECT_EQ(7, process_data_phase0.tasks[0].death_data.queue_duration_sample); EXPECT_EQ(kMainThreadName, process_data_phase0.tasks[0].death_thread_name); auto it1 = process_data.phased_snapshots.find(1); ASSERT_TRUE(it1 != process_data.phased_snapshots.end()); const ProcessDataPhaseSnapshot& process_data_phase1 = it1->second; ASSERT_EQ(1u, process_data_phase1.tasks.size()); EXPECT_EQ(kFile, process_data_phase1.tasks[0].birth.location.file_name); EXPECT_EQ(kFunction, process_data_phase1.tasks[0].birth.location.function_name); EXPECT_EQ(kLineNumber, process_data_phase1.tasks[0].birth.location.line_number); EXPECT_EQ(kMainThreadName, process_data_phase1.tasks[0].birth.thread_name); EXPECT_EQ(1, process_data_phase1.tasks[0].death_data.count); EXPECT_EQ(4, process_data_phase1.tasks[0].death_data.run_duration_sum); EXPECT_EQ(4, process_data_phase1.tasks[0].death_data.run_duration_max); EXPECT_EQ(4, process_data_phase1.tasks[0].death_data.run_duration_sample); EXPECT_EQ(5, process_data_phase1.tasks[0].death_data.queue_duration_sum); EXPECT_EQ(5, process_data_phase1.tasks[0].death_data.queue_duration_max); EXPECT_EQ(5, process_data_phase1.tasks[0].death_data.queue_duration_sample); EXPECT_EQ(kMainThreadName, process_data_phase1.tasks[0].death_thread_name); auto it2 = process_data.phased_snapshots.find(2); ASSERT_TRUE(it2 != process_data.phased_snapshots.end()); const ProcessDataPhaseSnapshot& process_data_phase2 = it2->second; ASSERT_EQ(1u, process_data_phase2.tasks.size()); EXPECT_EQ(kFile, process_data_phase2.tasks[0].birth.location.file_name); EXPECT_EQ(kFunction, process_data_phase2.tasks[0].birth.location.function_name); EXPECT_EQ(kLineNumber, process_data_phase2.tasks[0].birth.location.line_number); EXPECT_EQ(kMainThreadName, process_data_phase2.tasks[0].birth.thread_name); EXPECT_EQ(1, process_data_phase2.tasks[0].death_data.count); EXPECT_EQ(2, process_data_phase2.tasks[0].death_data.run_duration_sum); EXPECT_EQ(2, process_data_phase2.tasks[0].death_data.run_duration_max); EXPECT_EQ(2, process_data_phase2.tasks[0].death_data.run_duration_sample); EXPECT_EQ(3, process_data_phase2.tasks[0].death_data.queue_duration_sum); EXPECT_EQ(3, process_data_phase2.tasks[0].death_data.queue_duration_max); EXPECT_EQ(3, process_data_phase2.tasks[0].death_data.queue_duration_sample); EXPECT_EQ(kMainThreadName, process_data_phase2.tasks[0].death_thread_name); EXPECT_EQ(base::GetCurrentProcId(), process_data.process_id); } TEST_F(TrackedObjectsTest, TwoPhasesSecondEmpty) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); const char kFunction[] = "TwoPhasesSecondEmpty"; Location location(kFunction, kFile, kLineNumber, NULL); ThreadData::InitializeThreadContext(kMainThreadName); const TrackedTime kTimePosted = TrackedTime::FromMilliseconds(1); const base::TimeTicks kDelayedStartTime = base::TimeTicks(); // TrackingInfo will call TallyABirth() during construction. base::TrackingInfo pending_task(location, kDelayedStartTime); pending_task.time_posted = kTimePosted; // Overwrite implied Now(). const unsigned int kStartOfRun = 5; const unsigned int kEndOfRun = 7; SetTestTime(kStartOfRun); TaskStopwatch stopwatch; stopwatch.Start(); SetTestTime(kEndOfRun); stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task, stopwatch); ThreadData::OnProfilingPhaseCompleted(0); ProcessDataSnapshot process_data; ThreadData::Snapshot(1, &process_data); ASSERT_EQ(2u, process_data.phased_snapshots.size()); auto it0 = process_data.phased_snapshots.find(0); ASSERT_TRUE(it0 != process_data.phased_snapshots.end()); const ProcessDataPhaseSnapshot& process_data_phase0 = it0->second; ASSERT_EQ(1u, process_data_phase0.tasks.size()); EXPECT_EQ(kFile, process_data_phase0.tasks[0].birth.location.file_name); EXPECT_EQ(kFunction, process_data_phase0.tasks[0].birth.location.function_name); EXPECT_EQ(kLineNumber, process_data_phase0.tasks[0].birth.location.line_number); EXPECT_EQ(kMainThreadName, process_data_phase0.tasks[0].birth.thread_name); EXPECT_EQ(1, process_data_phase0.tasks[0].death_data.count); EXPECT_EQ(2, process_data_phase0.tasks[0].death_data.run_duration_sum); EXPECT_EQ(2, process_data_phase0.tasks[0].death_data.run_duration_max); EXPECT_EQ(2, process_data_phase0.tasks[0].death_data.run_duration_sample); EXPECT_EQ(4, process_data_phase0.tasks[0].death_data.queue_duration_sum); EXPECT_EQ(4, process_data_phase0.tasks[0].death_data.queue_duration_max); EXPECT_EQ(4, process_data_phase0.tasks[0].death_data.queue_duration_sample); EXPECT_EQ(kMainThreadName, process_data_phase0.tasks[0].death_thread_name); auto it1 = process_data.phased_snapshots.find(1); ASSERT_TRUE(it1 != process_data.phased_snapshots.end()); const ProcessDataPhaseSnapshot& process_data_phase1 = it1->second; ASSERT_EQ(0u, process_data_phase1.tasks.size()); EXPECT_EQ(base::GetCurrentProcId(), process_data.process_id); } TEST_F(TrackedObjectsTest, TwoPhasesFirstEmpty) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); ThreadData::OnProfilingPhaseCompleted(0); const char kFunction[] = "TwoPhasesSecondEmpty"; Location location(kFunction, kFile, kLineNumber, NULL); ThreadData::InitializeThreadContext(kMainThreadName); const TrackedTime kTimePosted = TrackedTime::FromMilliseconds(1); const base::TimeTicks kDelayedStartTime = base::TimeTicks(); // TrackingInfo will call TallyABirth() during construction. base::TrackingInfo pending_task(location, kDelayedStartTime); pending_task.time_posted = kTimePosted; // Overwrite implied Now(). const unsigned int kStartOfRun = 5; const unsigned int kEndOfRun = 7; SetTestTime(kStartOfRun); TaskStopwatch stopwatch; stopwatch.Start(); SetTestTime(kEndOfRun); stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task, stopwatch); ProcessDataSnapshot process_data; ThreadData::Snapshot(1, &process_data); ASSERT_EQ(1u, process_data.phased_snapshots.size()); auto it1 = process_data.phased_snapshots.find(1); ASSERT_TRUE(it1 != process_data.phased_snapshots.end()); const ProcessDataPhaseSnapshot& process_data_phase1 = it1->second; ASSERT_EQ(1u, process_data_phase1.tasks.size()); EXPECT_EQ(kFile, process_data_phase1.tasks[0].birth.location.file_name); EXPECT_EQ(kFunction, process_data_phase1.tasks[0].birth.location.function_name); EXPECT_EQ(kLineNumber, process_data_phase1.tasks[0].birth.location.line_number); EXPECT_EQ(kMainThreadName, process_data_phase1.tasks[0].birth.thread_name); EXPECT_EQ(1, process_data_phase1.tasks[0].death_data.count); EXPECT_EQ(2, process_data_phase1.tasks[0].death_data.run_duration_sum); EXPECT_EQ(2, process_data_phase1.tasks[0].death_data.run_duration_max); EXPECT_EQ(2, process_data_phase1.tasks[0].death_data.run_duration_sample); EXPECT_EQ(4, process_data_phase1.tasks[0].death_data.queue_duration_sum); EXPECT_EQ(4, process_data_phase1.tasks[0].death_data.queue_duration_max); EXPECT_EQ(4, process_data_phase1.tasks[0].death_data.queue_duration_sample); EXPECT_EQ(kMainThreadName, process_data_phase1.tasks[0].death_thread_name); EXPECT_EQ(base::GetCurrentProcId(), process_data.process_id); } // We will deactivate tracking after the birth, and before the death, and // demonstrate that the lifecycle is completely tallied. This ensures that // our tallied births are matched by tallied deaths (except for when the // task is still running, or is queued). TEST_F(TrackedObjectsTest, LifeCycleMidDeactivatedToSnapshotMainThread) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); const char kFunction[] = "LifeCycleMidDeactivatedToSnapshotMainThread"; Location location(kFunction, kFile, kLineNumber, NULL); TallyABirth(location, kMainThreadName); const TrackedTime kTimePosted = TrackedTime::FromMilliseconds(1); const base::TimeTicks kDelayedStartTime = base::TimeTicks(); // TrackingInfo will call TallyABirth() during construction. base::TrackingInfo pending_task(location, kDelayedStartTime); pending_task.time_posted = kTimePosted; // Overwrite implied Now(). // Turn off tracking now that we have births. ThreadData::InitializeAndSetTrackingStatus(ThreadData::DEACTIVATED); const unsigned int kStartOfRun = 5; const unsigned int kEndOfRun = 7; SetTestTime(kStartOfRun); TaskStopwatch stopwatch; stopwatch.Start(); SetTestTime(kEndOfRun); stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task, stopwatch); ProcessDataSnapshot process_data; ThreadData::Snapshot(0, &process_data); ExpectSimpleProcessData(process_data, kFunction, kMainThreadName, kMainThreadName, 1, 2, 4); } // We will deactivate tracking before starting a life cycle, and neither // the birth nor the death will be recorded. TEST_F(TrackedObjectsTest, LifeCyclePreDeactivatedToSnapshotMainThread) { // Start in the deactivated state. ThreadData::InitializeAndSetTrackingStatus(ThreadData::DEACTIVATED); const char kFunction[] = "LifeCyclePreDeactivatedToSnapshotMainThread"; Location location(kFunction, kFile, kLineNumber, NULL); TallyABirth(location, kMainThreadName); const TrackedTime kTimePosted = TrackedTime::FromMilliseconds(1); const base::TimeTicks kDelayedStartTime = base::TimeTicks(); // TrackingInfo will call TallyABirth() during construction. base::TrackingInfo pending_task(location, kDelayedStartTime); pending_task.time_posted = kTimePosted; // Overwrite implied Now(). const unsigned int kStartOfRun = 5; const unsigned int kEndOfRun = 7; SetTestTime(kStartOfRun); TaskStopwatch stopwatch; stopwatch.Start(); SetTestTime(kEndOfRun); stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task, stopwatch); ProcessDataSnapshot process_data; ThreadData::Snapshot(0, &process_data); ASSERT_EQ(1u, process_data.phased_snapshots.size()); auto it = process_data.phased_snapshots.find(0); ASSERT_TRUE(it != process_data.phased_snapshots.end()); const ProcessDataPhaseSnapshot& process_data_phase = it->second; ASSERT_EQ(0u, process_data_phase.tasks.size()); EXPECT_EQ(base::GetCurrentProcId(), process_data.process_id); } TEST_F(TrackedObjectsTest, TwoLives) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); const char kFunction[] = "TwoLives"; Location location(kFunction, kFile, kLineNumber, NULL); TallyABirth(location, kMainThreadName); const TrackedTime kTimePosted = TrackedTime::FromMilliseconds(1); const base::TimeTicks kDelayedStartTime = base::TimeTicks(); // TrackingInfo will call TallyABirth() during construction. base::TrackingInfo pending_task(location, kDelayedStartTime); pending_task.time_posted = kTimePosted; // Overwrite implied Now(). const unsigned int kStartOfRun = 5; const unsigned int kEndOfRun = 7; SetTestTime(kStartOfRun); TaskStopwatch stopwatch; stopwatch.Start(); SetTestTime(kEndOfRun); stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task, stopwatch); // TrackingInfo will call TallyABirth() during construction. base::TrackingInfo pending_task2(location, kDelayedStartTime); pending_task2.time_posted = kTimePosted; // Overwrite implied Now(). SetTestTime(kStartOfRun); TaskStopwatch stopwatch2; stopwatch2.Start(); SetTestTime(kEndOfRun); stopwatch2.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task2, stopwatch2); ProcessDataSnapshot process_data; ThreadData::Snapshot(0, &process_data); ExpectSimpleProcessData(process_data, kFunction, kMainThreadName, kMainThreadName, 2, 2, 4); } TEST_F(TrackedObjectsTest, DifferentLives) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); // Use a well named thread. ThreadData::InitializeThreadContext(kMainThreadName); const char kFunction[] = "DifferentLives"; Location location(kFunction, kFile, kLineNumber, NULL); const TrackedTime kTimePosted = TrackedTime::FromMilliseconds(1); const base::TimeTicks kDelayedStartTime = base::TimeTicks(); // TrackingInfo will call TallyABirth() during construction. base::TrackingInfo pending_task(location, kDelayedStartTime); pending_task.time_posted = kTimePosted; // Overwrite implied Now(). const unsigned int kStartOfRun = 5; const unsigned int kEndOfRun = 7; SetTestTime(kStartOfRun); TaskStopwatch stopwatch; stopwatch.Start(); SetTestTime(kEndOfRun); stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task, stopwatch); const int kSecondFakeLineNumber = 999; Location second_location(kFunction, kFile, kSecondFakeLineNumber, NULL); // TrackingInfo will call TallyABirth() during construction. base::TrackingInfo pending_task2(second_location, kDelayedStartTime); pending_task2.time_posted = kTimePosted; // Overwrite implied Now(). ProcessDataSnapshot process_data; ThreadData::Snapshot(0, &process_data); ASSERT_EQ(1u, process_data.phased_snapshots.size()); auto it = process_data.phased_snapshots.find(0); ASSERT_TRUE(it != process_data.phased_snapshots.end()); const ProcessDataPhaseSnapshot& process_data_phase = it->second; ASSERT_EQ(2u, process_data_phase.tasks.size()); EXPECT_EQ(kFile, process_data_phase.tasks[0].birth.location.file_name); EXPECT_EQ(kFunction, process_data_phase.tasks[0].birth.location.function_name); EXPECT_EQ(kLineNumber, process_data_phase.tasks[0].birth.location.line_number); EXPECT_EQ(kMainThreadName, process_data_phase.tasks[0].birth.thread_name); EXPECT_EQ(1, process_data_phase.tasks[0].death_data.count); EXPECT_EQ(2, process_data_phase.tasks[0].death_data.run_duration_sum); EXPECT_EQ(2, process_data_phase.tasks[0].death_data.run_duration_max); EXPECT_EQ(2, process_data_phase.tasks[0].death_data.run_duration_sample); EXPECT_EQ(4, process_data_phase.tasks[0].death_data.queue_duration_sum); EXPECT_EQ(4, process_data_phase.tasks[0].death_data.queue_duration_max); EXPECT_EQ(4, process_data_phase.tasks[0].death_data.queue_duration_sample); EXPECT_EQ(kMainThreadName, process_data_phase.tasks[0].death_thread_name); EXPECT_EQ(kFile, process_data_phase.tasks[1].birth.location.file_name); EXPECT_EQ(kFunction, process_data_phase.tasks[1].birth.location.function_name); EXPECT_EQ(kSecondFakeLineNumber, process_data_phase.tasks[1].birth.location.line_number); EXPECT_EQ(kMainThreadName, process_data_phase.tasks[1].birth.thread_name); EXPECT_EQ(1, process_data_phase.tasks[1].death_data.count); EXPECT_EQ(0, process_data_phase.tasks[1].death_data.run_duration_sum); EXPECT_EQ(0, process_data_phase.tasks[1].death_data.run_duration_max); EXPECT_EQ(0, process_data_phase.tasks[1].death_data.run_duration_sample); EXPECT_EQ(0, process_data_phase.tasks[1].death_data.queue_duration_sum); EXPECT_EQ(0, process_data_phase.tasks[1].death_data.queue_duration_max); EXPECT_EQ(0, process_data_phase.tasks[1].death_data.queue_duration_sample); EXPECT_EQ(kStillAlive, process_data_phase.tasks[1].death_thread_name); EXPECT_EQ(base::GetCurrentProcId(), process_data.process_id); } TEST_F(TrackedObjectsTest, TaskWithNestedExclusion) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); const char kFunction[] = "TaskWithNestedExclusion"; Location location(kFunction, kFile, kLineNumber, NULL); TallyABirth(location, kMainThreadName); const TrackedTime kTimePosted = TrackedTime::FromMilliseconds(1); const base::TimeTicks kDelayedStartTime = base::TimeTicks(); // TrackingInfo will call TallyABirth() during construction. base::TrackingInfo pending_task(location, kDelayedStartTime); pending_task.time_posted = kTimePosted; // Overwrite implied Now(). SetTestTime(5); TaskStopwatch task_stopwatch; task_stopwatch.Start(); { SetTestTime(8); TaskStopwatch exclusion_stopwatch; exclusion_stopwatch.Start(); SetTestTime(12); exclusion_stopwatch.Stop(); } SetTestTime(15); task_stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task, task_stopwatch); ProcessDataSnapshot process_data; ThreadData::Snapshot(0, &process_data); ExpectSimpleProcessData(process_data, kFunction, kMainThreadName, kMainThreadName, 1, 6, 4); } TEST_F(TrackedObjectsTest, TaskWith2NestedExclusions) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); const char kFunction[] = "TaskWith2NestedExclusions"; Location location(kFunction, kFile, kLineNumber, NULL); TallyABirth(location, kMainThreadName); const TrackedTime kTimePosted = TrackedTime::FromMilliseconds(1); const base::TimeTicks kDelayedStartTime = base::TimeTicks(); // TrackingInfo will call TallyABirth() during construction. base::TrackingInfo pending_task(location, kDelayedStartTime); pending_task.time_posted = kTimePosted; // Overwrite implied Now(). SetTestTime(5); TaskStopwatch task_stopwatch; task_stopwatch.Start(); { SetTestTime(8); TaskStopwatch exclusion_stopwatch; exclusion_stopwatch.Start(); SetTestTime(12); exclusion_stopwatch.Stop(); SetTestTime(15); TaskStopwatch exclusion_stopwatch2; exclusion_stopwatch2.Start(); SetTestTime(18); exclusion_stopwatch2.Stop(); } SetTestTime(25); task_stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task, task_stopwatch); ProcessDataSnapshot process_data; ThreadData::Snapshot(0, &process_data); ExpectSimpleProcessData(process_data, kFunction, kMainThreadName, kMainThreadName, 1, 13, 4); } TEST_F(TrackedObjectsTest, TaskWithNestedExclusionWithNestedTask) { ThreadData::InitializeAndSetTrackingStatus(ThreadData::PROFILING_ACTIVE); const char kFunction[] = "TaskWithNestedExclusionWithNestedTask"; Location location(kFunction, kFile, kLineNumber, NULL); const int kSecondFakeLineNumber = 999; TallyABirth(location, kMainThreadName); const TrackedTime kTimePosted = TrackedTime::FromMilliseconds(1); const base::TimeTicks kDelayedStartTime = base::TimeTicks(); // TrackingInfo will call TallyABirth() during construction. base::TrackingInfo pending_task(location, kDelayedStartTime); pending_task.time_posted = kTimePosted; // Overwrite implied Now(). SetTestTime(5); TaskStopwatch task_stopwatch; task_stopwatch.Start(); { SetTestTime(8); TaskStopwatch exclusion_stopwatch; exclusion_stopwatch.Start(); { Location second_location(kFunction, kFile, kSecondFakeLineNumber, NULL); base::TrackingInfo nested_task(second_location, kDelayedStartTime); // Overwrite implied Now(). nested_task.time_posted = TrackedTime::FromMilliseconds(8); SetTestTime(9); TaskStopwatch nested_task_stopwatch; nested_task_stopwatch.Start(); SetTestTime(11); nested_task_stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking( nested_task, nested_task_stopwatch); } SetTestTime(12); exclusion_stopwatch.Stop(); } SetTestTime(15); task_stopwatch.Stop(); ThreadData::TallyRunOnNamedThreadIfTracking(pending_task, task_stopwatch); ProcessDataSnapshot process_data; ThreadData::Snapshot(0, &process_data); ASSERT_EQ(1u, process_data.phased_snapshots.size()); auto it = process_data.phased_snapshots.find(0); ASSERT_TRUE(it != process_data.phased_snapshots.end()); const ProcessDataPhaseSnapshot& process_data_phase = it->second; // The order in which the two task follow is platform-dependent. int t0 = (process_data_phase.tasks[0].birth.location.line_number == kLineNumber) ? 0 : 1; int t1 = 1 - t0; ASSERT_EQ(2u, process_data_phase.tasks.size()); EXPECT_EQ(kFile, process_data_phase.tasks[t0].birth.location.file_name); EXPECT_EQ(kFunction, process_data_phase.tasks[t0].birth.location.function_name); EXPECT_EQ(kLineNumber, process_data_phase.tasks[t0].birth.location.line_number); EXPECT_EQ(kMainThreadName, process_data_phase.tasks[t0].birth.thread_name); EXPECT_EQ(1, process_data_phase.tasks[t0].death_data.count); EXPECT_EQ(6, process_data_phase.tasks[t0].death_data.run_duration_sum); EXPECT_EQ(6, process_data_phase.tasks[t0].death_data.run_duration_max); EXPECT_EQ(6, process_data_phase.tasks[t0].death_data.run_duration_sample); EXPECT_EQ(4, process_data_phase.tasks[t0].death_data.queue_duration_sum); EXPECT_EQ(4, process_data_phase.tasks[t0].death_data.queue_duration_max); EXPECT_EQ(4, process_data_phase.tasks[t0].death_data.queue_duration_sample); EXPECT_EQ(kMainThreadName, process_data_phase.tasks[t0].death_thread_name); EXPECT_EQ(kFile, process_data_phase.tasks[t1].birth.location.file_name); EXPECT_EQ(kFunction, process_data_phase.tasks[t1].birth.location.function_name); EXPECT_EQ(kSecondFakeLineNumber, process_data_phase.tasks[t1].birth.location.line_number); EXPECT_EQ(kMainThreadName, process_data_phase.tasks[t1].birth.thread_name); EXPECT_EQ(1, process_data_phase.tasks[t1].death_data.count); EXPECT_EQ(2, process_data_phase.tasks[t1].death_data.run_duration_sum); EXPECT_EQ(2, process_data_phase.tasks[t1].death_data.run_duration_max); EXPECT_EQ(2, process_data_phase.tasks[t1].death_data.run_duration_sample); EXPECT_EQ(1, process_data_phase.tasks[t1].death_data.queue_duration_sum); EXPECT_EQ(1, process_data_phase.tasks[t1].death_data.queue_duration_max); EXPECT_EQ(1, process_data_phase.tasks[t1].death_data.queue_duration_sample); EXPECT_EQ(kMainThreadName, process_data_phase.tasks[t1].death_thread_name); EXPECT_EQ(base::GetCurrentProcId(), process_data.process_id); } } // namespace tracked_objects
39.81734
80
0.76473
[ "object" ]
70dafe8daaff398f009776204b29cb42f84e95af
345
cpp
C++
Unidad-1/Aula04/3.cpp
luismoroco/ProgrCompetitiva
011cdb18749a16d17fd635a7c36a8a21b2b643d9
[ "BSD-3-Clause" ]
null
null
null
Unidad-1/Aula04/3.cpp
luismoroco/ProgrCompetitiva
011cdb18749a16d17fd635a7c36a8a21b2b643d9
[ "BSD-3-Clause" ]
null
null
null
Unidad-1/Aula04/3.cpp
luismoroco/ProgrCompetitiva
011cdb18749a16d17fd635a7c36a8a21b2b643d9
[ "BSD-3-Clause" ]
null
null
null
#include <bits/stdc++.h> using namespace std; // Square each value in a sorted array and // return the output in sorted order int main() { vector<int> array = {-4, -3, 1, 2, 3}; for (auto &v : array) v = v * v; sort(array.begin(), array.end()); for (auto v : array) cout << v << ' '; return EXIT_SUCCESS; }
20.294118
42
0.55942
[ "vector" ]